#!/usr/bin/perl

$mpg_dir   = "/home/pictures";
$video_dir = "/home/videos/HomeVideos"; 

opendir(DIR, "$mpg_dir");
@year_dirs = grep { /\d\d\d\d/ } readdir(DIR);
closedir(DIR);
chdir $mpg_dir;

foreach $year_dir (sort @year_dirs) {
    chdir "$mpg_dir/$year_dir";
    #print "Parsing $mpg_dir/$year_dir\n";
    opendir(DIR, "$mpg_dir/$year_dir");
    @month_dirs = readdir(DIR);
    closedir(DIR);
    foreach $month_dir (sort @month_dirs) {
	chdir "$mpg_dir/$year_dir/$month_dir";
	#print "Parsing $year_dir/$month_dir\n";
	opendir(DIR, "$mpg_dir/$year_dir/$month_dir");
	@mpg_files = grep { /\.mpg|\.MPG/ } readdir(DIR);
	closedir(DIR);
	foreach $mpg_file (sort @mpg_files) {
	    #print "Found $year_dir/$month_dir/$mpg_file\n";
	    $mpg_file =~ /(\d\d)(\w\w\w)/; $day = $1;
	    $month_dir =~ /(\d\d)/; $month = $1;
	    $year = $year_dir;
	    $merged_file = "$video_dir/$year/$year-$month-$day.mpg";
	    $new_merged_file = "$merged_file.new";
	    if(-e "$merged_file") { next; }
	    if(-e "$new_merged_file") {
		print "Merging $mpg_file with $new_merged_file\n";
		#print "/usr/bin/mpgtx -j $new_merged_file $mpg_file -o $new_merged_file.tmp\n";
		#print "mv \"$new_merged_file.tmp\" \"$new_merged_file\"\n";
		system("/usr/bin/mpgtx -j \"$new_merged_file\" \"$mpg_file\" -o \"$new_merged_file.tmp\"");
		system("mv \"$new_merged_file.tmp\" \"$new_merged_file\"");
		$new_files{$new_merged_file} = 1;
	    } else {
		print "Merging $mpg_file with $new_merged_file\n";
		#print "cp $mpg_file $new_merged_file\n";
		system("cp \"$mpg_file\" \"$new_merged_file\"");
		$new_files{$new_merged_file} = 1;
	    }
	}
    }
}

foreach $file (keys %new_files) {
    $newfile = $file;
    $newfile =~ s/\.new//g;
    #print "mv $file $newfile\n";
    system("mv $file $newfile");
}



