#!/usr/local/bin/perl
#
# xpmmergemask
#
# Copyright (C) 1998,2000 Taiji Yamada <taiji@aihara.co.jp>

require 'getopts.pl';
$opt_m = "black";
$opt_n = "None";
&Getopts('m:n:')
    || die "usage: $0 [-m <mask value>] [-n <none value>] < in > out\n".
    "\tdefault           ... mask: black, none: None\n".
    "\t-m white -n black ... mask: white, none: black\n".

$header = 0;
$name = ""; $chars_per_pixel = 0; $chars_per_line = 0;
$colors = 0;
$pixels = 0;
$pixels_flag = 0;
$y = 0;
while (<>) {
  if (/\/\*\s*XPM\s\*\//) {
    $header = !0;
  }
  elsif ($header && $chars_per_pixel
         && (/\/\*\s*colors\s\*\//
             || /\"[^\"]{$chars_per_pixel,$chars_per_pixel}\s+((c|m|g|g4|s)\s+[^\"]+)+\"/)) {
    $colors = !0;
  }
  elsif ($header && $colors && $chars_per_line
         && (/\/\*\s*pixels\s\*\//
             || /\"[^\"]{$chars_per_line,$chars_per_line}\"/)) {
    $pixels = !0;
  }
  if ($header && !$colors && !$pixels) {
    if (/static\s+char\s+\*\s*(.*)\[\]\s*=\s*\{/) {
      $name = $1;
      print "/* XPM */\n";
      print "static char *$name\[\] = {\n";
    }
    elsif (/\"\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s*\"/) {
      ($width,$height,$num_colors,$chars_per_pixel) = ($1,$2,$3,$4);
      $chars_per_line = $width*$chars_per_pixel;
      $pixel = "[^\"]{$chars_per_pixel,$chars_per_pixel}";
      print "/* width height num_colors chars_per_pixel */\n";
      print "\"$width $height 2 1\",\n";
      print "/* colors */\n";
      printf("\"  %s\",\n", ($opt_n=~/None/)?"c None":"c $opt_n");
      printf("\"# %s\",\n", ($opt_m=~/None/)?"c None":"c $opt_m");
      $colors = !0;
    }
  }
  elsif ($colors && !$pixels) {
    if (/\"([^\"]{$chars_per_pixel,$chars_per_pixel})\s+((c|m|g|g4|s)\s+[^\"]+)+\"/) {
      ($pixel,$value) = ($1,$2);
      if ($value =~ /[nN]one/ || $value =~ /[tT]ransparent/) {
        $mask = $pixel;
      }
    }
  }
  elsif ($pixels) {
    if (!$pixels_flag) {
      print "/* pixels */\n";
      $pixels_flag = !0;
    }
    if (/\"([^\"]*)\"/) {
      $buf = $1;
      print "\"";
      for ($x=0; $x<$width; $x++) {
        if (substr($buf,$x*$chars_per_pixel,$chars_per_pixel) eq $mask) {
          print " ";
        }
        else {
          print "#";
        }
      }
      print "\",\n";
      $y++;
    }
  } 
}
print "};\n";
