#!/usr/bin/perl

# requires your system to have the imageMajick tools installed
# specifically jpeg2yuv and mpeg2enc 

use strict;
use Date::Calc qw(Add_Delta_YMDHMS);

my $parent_dir='BASE_DIR_TO_FRAMES';  #should be same as parent in grab_frames

opendir(DIR, $parent_dir);
my @cams = grep { !/^\./ } readdir(DIR);
closedir(DIR);

foreach my $cam (@cams)
{
	#get the date in the appropriate format
	my $DAY;
	my $MONTH;
	my $YEAR;
	my $HOUR;
	($HOUR, $DAY, $MONTH, $YEAR,) = (localtime)[2,3,4,5];
	#put the date in the right format
	$YEAR = $YEAR + 1900;
	$MONTH = $MONTH + 1;
	#and now subtract an hour
	($YEAR,$MONTH,$DAY, $HOUR, my $MIN, my $SEC) = Add_Delta_YMDHMS($YEAR,$MONTH,$DAY,$HOUR,'0','0', '0','0','0','-1','0','0');
	if ( $HOUR < 10 )
	{
		$HOUR="0$HOUR";
	}
	if ( $DAY < 10 )
	{
		$DAY = '0'.$DAY;
	}
	if ( $MONTH < 10 )
	{
		$MONTH = '0'.$MONTH;
	}
	my $day_dir = "$YEAR".'-'."$MONTH".'-'."$DAY";

	opendir(DIR, "$parent_dir/$cam/$day_dir" );
	my @frames = grep { /^$day_dir-$HOUR/ } readdir(DIR);
	closedir(DIR);

	@frames = sort @frames;

	my $counter = 0;
	foreach my $frame (@frames)
	{
		if ( $counter < 10 )
		{
			system("mv $parent_dir/$cam/$day_dir/$frame $parent_dir/$cam/$day_dir/${HOUR}_000$counter.jpg");
		}
		elsif ( $counter < 100 )
		{
			system("mv $parent_dir/$cam/$day_dir/$frame $parent_dir/$cam/$day_dir/${HOUR}_00$counter.jpg");
		}
		elsif ( $counter < 1000 )
		{
			system("mv $parent_dir/$cam/$day_dir/$frame $parent_dir/$cam/$day_dir/${HOUR}_0$counter.jpg");
		}
		else
		{
			system("mv $parent_dir/$cam/$day_dir/$frame $parent_dir/$cam/$day_dir/${HOUR}_$counter.jpg");
		}
		print "$frame \n";
		$counter++;
	}
	system("/usr/bin/jpeg2yuv -f 25 -I p -j $parent_dir/$cam/$day_dir/${HOUR}_%04d.jpg | /usr/bin/mpeg2enc -o $parent_dir/$cam/$day_dir/$HOUR.mpg");
	my $new_counter='0';
	while ( $new_counter <= $counter )
	{
		if ( $new_counter < 10 )
		{
			system("rm $parent_dir/$cam/$day_dir/${HOUR}_000${new_counter}.jpg");
		}
		elsif ( $new_counter < 100 )
		{
			system("rm $parent_dir/$cam/$day_dir/${HOUR}_00${new_counter}.jpg");
		}
		elsif ( $new_counter < 1000 )
		{
			system("rm $parent_dir/$cam/$day_dir/${HOUR}_0${new_counter}.jpg");
		}
		else
		{
			system("rm $parent_dir/$cam/$day_dir/${HOUR}_${new_counter}.jpg");
		}
		$new_counter++;
	}	
}
