
use strict;

my %idmap = ();

sub create_idmap {
	open( HTML, "labeled_faces/matches.html" );
	while ( <HTML> ) {
		chomp;
		if ( /<!-- MAP: ([0-9]*) -> ([0-9]*) -->/ ) {
			$idmap{$1} = $2;
		}
	}
	close( HTML );
}

sub crop_faces {
	my $id = $idmap{$_[0]};
	my $original_image = $_[1];
	my $labeled_image = "labeled_faces/$id.jpg";
	open( DATA, "labeled_faces/$id.dat" ) or die "unable to open labeled_faces/$id.dat";
	my $line = <DATA>;
	chomp $line;
	$line =~ /^ ([0-9]*) -- number of faces$/ or die "format 1: $line";
	my $number = $1;
	for my $i ( 1..$number ) {
		<DATA>;
		my $type = <DATA>;
		my $position = <DATA>;
		my $size = <DATA>;
		my $confidence = <DATA>;

		chomp $type;
		$type =~ s/^ ([0-9]*). (.*)$/\2/;
		if ( $type eq "Frontal Face" ) {
			$position =~ /^ *([0-9]*) *([0-9]*) *-- Position/ or die "format 2: $position";
			my $x = $1;
			my $y = $2;

			my $width = 0;
			my $height = 0;
			$size =~ /^ *(-*[0-9]*) *-- size$/ or die "format 2: $size";
			my $size_index = $1;
			my $width = int(24*(1.189207**$size_index)+0.5);
			my $height = int(32*(1.189207**$size_index)+0.5);

			$x = $x - int( $width / 2 );
			$y = $y - int( $height / 2 );

			my $cmd = "convert -crop $width\x78$height+$x+$y $original_image cropped_faces/color/$id\_$i.jpg";
			print "$cmd\n";
			`$cmd`;

			my $cmd = "convert -colorspace gray cropped_faces/color/$id\_$i.jpg cropped_faces/bw/$id\_$i.jpg";
			print "$cmd\n";
			`$cmd`;
		}
	}
	close( DATA );
}

$#ARGV == 1 or die "usage";
my $id = $ARGV[0];
my $url = $ARGV[1];

&create_idmap;
&crop_faces($id,$url);


