#!/usr/bin/perl -w
use Fcntl 'SEEK_SET';

@INFILES=("tucnakcor");
$OUTFILE="../src/cordata.inc";
$OUTH="../src/cordata.h";
$PREFIX="cor";


open GD, ">$OUTFILE" or die "Can't open file $OUTFILE";
print GD "/* Automatically generated by cor2inc.pl */\n\n";

$hh="/* Automatically generated by corinc.pl */\n\n";

for $filename (@INFILES){

    open (FD, $filename) or die;
    sysseek(FD, 0, 2);
    $len=sysseek(FD, 0, 1);
    sysseek(FD, 0, 0);
    sysread(FD, $icon, $len);
    close(FD);

    $ident=$filename;
    $ident=~s/\..*//;
    $items=$len/5;

    print GD "const struct cpoint $PREFIX"."_$ident"."[COR_ITEMS] = {\n    ";
    $hh.=sprintf "#ifdef Z_HAVE_SDL\n";
    $hh.=sprintf "#define COR_ITEMS %d\n\n", $items;
    $hh.=sprintf "extern const struct cpoint $PREFIX"."_$ident"."[COR_ITEMS];\n";
    $hh.=sprintf "#endif /* Z_HAVE_SDL */\n";
    $line="";
    for ($i=0; $i<$len; $i+=5){
        $w=unpack ("C", substr($icon, $i+0, 1))+256*unpack ("C", substr($icon, $i+1, 1));
        if ($w > 32767) { $w -= 65536; }
        $h=unpack ("C", substr($icon, $i+2, 1))+256*unpack ("C", substr($icon, $i+3, 1));
        if ($h > 32767) { $h -= 65536; }
        $t=unpack ("C", substr($icon, $i+4, 1));
        
        $line.=sprintf "{%d,%d,%d}", $w, $h, $t;
        if ($i<$len-5) { 
            $line.=","; 
            if (length($line)>70) {
                print GD $line."\n    ";
                $line="";
            }
        }
    }
    print GD $line;

    print GD "\n};\n\n";
}

close GD;

#print $hh;

$oldh=`cat $OUTH`;
if (!$oldh or $hh ne $oldh){
    print "new header\n";
    open FD, ">$OUTH" or die;
    print FD $hh;
    close FD;
}else{
    print "same header\n";
}
