#!/usr/bin/perl

###########################################################################
# converts from the old month-year.txt format to a single appointments.txt
#
# by Michael (mike@fuzzymonkey.org)
###########################################################################

if(-e "appointments.txt"){
	die("error: appointments.txt already exits.  Refusing to clobber file.  Please rename or move this file!");
}

# read in all of the month-year files
@files = glob("*.txt");
foreach $file (@files){
	if($file =~ /([0-9]{1,2})-([0-9]{4,4})\.txt/){
		print "processing $file ...";
		if(open(INFILE,"<$file")){ # sucess opening file
			$month ="$1";
			$year = "$2";
			#print "month $month and year $year ";
			while(<INFILE>){
				chomp();
				($day,$appointment_text) = split(/\t/,"$_");
				@appointments_on_day = split(/##/,$appointment_text);
				foreach $appointment_on_day (@appointments_on_day){
					push(@{$appointments{"$month-$day-$year"}},"$appointment_on_day");
				}
			}
			close(INFILE);
		}else{ #oops opeining file
			print "\t[FAILED] $!\n";
			next;
		}
	
		print "\t[OK]\n";
	}
}

# write out the new appointments.txt file
if(open(OUTFILE,">appointments.txt")){
	foreach $date (sort keys %appointments){
		# print "$date has \t", scalar(@{$appointments{$date}})," appointments ";
		foreach $appointment (sort @{$appointments{$date}}){
			print OUTFILE "$date\t$appointment\t0\n";
		}
		print "[OK]\n";
	}
	close(OUTFILE);
}else{
	die("error: $!")

}
