#!/usr/bin/perl

use File::Basename;
use Getopt::Long;

unless ( GetOptions (

	"c=s"		=> \$config,
	"config=s"	=> \$config,

	"h"		=> \$usage,
	"help"		=> \$usage,

	"g=s"		=> \$group,
	"group=s"	=> \$group,

	"i=s"		=> \$input,
	"input=s"	=> \$input,

	"o=s"		=> \$output,
	"output=s"	=> \$output

)) { Usage(); exit(1); }

# Usage help
( Usage(), die "\n" ) if ($usage);

# Load in config
$config = "$ENV{CROPS_CONFIG}" unless ($config);
$config = "/etc/crops/crops.conf" unless ($config);
do "$config" or die "Can't load '$config' ($!)";

# Check arguments
"$input" or die "No --input file specified\n";
( $group = basename($input), $group =~ s#\..*## ) unless ($group);
die "Invalid input .afm filename: '${input}'\n" if (! (-e "$input" ));
if (! ($output)) {
	$output = basename($input);
	if (! ($output =~ s#\.#-c\.#)) {$output .= "-c.afm"};
}

# Print summary
if (1) {
	for my $p (qw/config group input output/) {
		print "$p : ${$p}\n";
	}
}


# Work starts here :)


# Read in the list of interesting composites for specific group
$file = "${SPECSDIR}/${group}.spec";
open(SPEC, "< $file") or die "Can't open specifics file '$file' ($!)\n";
while (<SPEC>) {
	my $line = $_;
	#chomp($line);
	@els = split(/ +/, $line) if ( $line =~ /^CC/);
	$additional{$els[1]} = $line;
	push (@chars, $els[1]);
}
close(SPEC);


# Read in AFM file
open (AFM, "< $input") or die "Can't open --input file '$input' ($!)\n";
push (@afm_file, $_ ) while ( $_ = <AFM> );

for my $char (@chars) {
	$flag = 0;
	for my $line2 (@afm_file) {
		if ($line2 =~ /$char/ ) {
			$flag = 1;
		}
	} 
	push (@needed, $char)  if (! ($flag));
}

for my $elems (qw/StartFontMetrics FontName/ ) { # FamilyName too? ttf2afm doesn't generate that field
	foreach $ln2 (@afm_file) {
		if ( $ln2 =~ /^($elems .*)/ ) { push (@header, $1); goto FOUND };
	}
	print "Can't locate $elems field in '$input' file\n"; 
	die "\n";
FOUND:
}


# Prepare output file and stuff
open (OUT, "> $output") or die "Can't open --output file '$output' ($!)\n";
foreach my $l (@header) { print OUT "$l\n"; }
print OUT "StartComposites ", scalar(@needed), "\n";
foreach my $li (@needed) { print OUT "$additional{$li}" };
print OUT "EndComposites\nEndFontMetrics\n";
close(OUT);


exit(0);


#
# CODE END, only helper functions below
# TODO: Turn to manpage
sub Usage {
        print STDERR "See crops-genmissing(1) man page for usage instructions\n";
}

