#!/usr/local/bin/perl
# -*- Perl -*-
# usage: fix_xpmcolors file1 [..filen]
#
# file is crossfire archetypefile. NOT xpm file 
# fixes colors in black&white crossfire xpm pixmaps
# script assumes that faces are in same directory as archetype file.
#
# Modified to convert to XPM color standard (ie, colors in
# xpm.template

%colorconv = 
    ("black","Black",
     "white","White",
     "blue","Navy",
     "red","Red",
     "orange","Orange",
     "light_blue","DodgerBlue",
     "dark_orange","Chocolate",
     "green","SeaGreen",
     "light_green","PaleGreen",
     "grey","Grey50",
     "brown","sienna",
     "yellow","Gold",
     "khaki","Khaki"
     );
  

while ($f = shift) {
#chop $f;
    print ">$f<\n";
    open (AR, "<$f") || die "aargh";
    while ($_=<AR>) {
        if (/^Object/) {
            $fg = "black";
            $bg = "khaki";
            @faces = ();
        } elsif (/^color_fg (.+)/) {
            $fg = $1;
        } elsif (/^color_bg (.+)/) {
            $bg = $1;
        } elsif (/^face (.+)/) {
            push (@faces, $1);
        } elsif (/^anim$/) {
            while (($_=<AR>) && !/^mina$/) {
                chop;
                push (@faces, $_);
            }
        } elsif (/^end/) {
            $dir = ($f =~ /(.*)\/([^\/]*)$/) ? $1 : ".";
            print "fg $fg bg $bg\n";
            &do_faces;
        }
    }
    close (AR);
}

sub do_faces {
    foreach $face (@faces) {
        print "dir $dir/$face\n";
        open (FA, "<$dir/$face.xpm") || warn "aargh";
        open (OR, ">pah") || die "aargh";
        $changed = 0;
        while ($_ = <FA>) {
            if (/\/\*\s*colors\s*\*\//) {
                print OR "/* colors */\n";
                while (($_ = <FA>) && /"(.) (.) #(...)",/) {
                    print "$1 $2 $3";
                    if ($3 eq "000") { # 
                        print OR "\"$1 $2 $colorconv{$fg}\",\n"; 
                        print " -> $colorconv{$fg}"; 
                        $changed++;
                    } elsif ($3 eq "FFF") {
                        print OR "\"$1 $2 $colorconv{$bg}\",\n";
                        print " -> $colorconv{$bg}"; 
                        $changed++;
                    } else {
                        print OR $_;
                    }
                    print "\n";
                }
            }
            print OR $_;
        }
        close (FA);
        close (OR);
        if ($changed) {
            unlink ("$dir/$face.xpm");
            rename ("pah", "$dir/$face.xpm") || die "rename";
        }
    }
}
