#!/usr/bin/perl
use strict;
use Data::Dumper;

my $name;
my %entries;

system("p4 edit grib_templates.h");
open(OUT,">grib_templates.h") or "die grib_templates.h: $!";
print OUT "/* This file is automatically generated by $0, do not edit */\n\n";

foreach $name ( @ARGV )
{
     
    $name =~ /(\w+)\.grib/;
    my $proc = $1;

	print "$name\n";

    open(IN,"<$name") or die "$name: $!";

	my $ccproc = $proc;
	$ccproc =~ s/\W/_/;

    print OUT << "EOF";

/*
    $name
*/

unsigned char _grib_template_${ccproc}\[\] = {

EOF

	my $len; my $data;
	my $size = 0;

	while (($len = read(IN,$data,8)))
	{
	     foreach my $x ( unpack('C*', $data) )
		 {
		 	printf OUT " 0x%02x,", $x;
			 $size++;
		 }
		 print OUT "\n";
	}


    print OUT << "EOF";

};


EOF

	$entries{"\t{\"$proc\", _grib_template_${ccproc}, $size, },"}++;

}


print OUT "\nstatic grib_templates templates[] = {\n";

foreach my $k ( sort keys %entries )
{
	print OUT "$k\n";
}

print OUT "};\n\n";

close(OUT) or "die grib_templates.h: $!";
