#!/bin/sh -
#
#  Recolor all the X pixmap files so as to use a specific colormap
#
progname=`basename $0`

Usage() {
  echo >&2 "usage: $progname [-f colormap] Xpixmaps...."
}

cmap="$HOME/icons/local/colormap.ppm"
b="                                                           
"
flag=''

if [ "X$1" = 'X-f' ]; then
  cmap=$2
  shift; shift
fi

if [ "X$1" = 'X-fs' ]; then
  flag=-fs
  shift
fi

if [ ! -r $cmap ]; then
  echo "`basename $0`: unable to find colormap to recolor icons with"
  exit 10;
fi

# find number of colors in recoloring colormap
numcolors() {
  expr `ppmhist $1 | wc -l` - 2
}
cmap_col=`numcolors $cmap`

TMP1=/tmp/recolor$$.1
TMP2=/tmp/recolor$$.2
trap "rm -f $TMP1 $TMP2; exit 0" 1 2 3 15

for i in "$@" ; do
  if [ ! -r "$i" ]; then
    echo -n "${b}"
    echo >&2 "Unable to find pixmap \"$i\""
    continue
  fi
  case "$i" in
   *_recol.xpm | *_recol_bad.xpm ) 
     echo -n "${b}"
     echo >&2 "Skipping recolored pixmap \"$i\"" 
     continue ;;
   *.xpm ) ;; # this is ok
   * )        # anything else
     echo -n "${b}"
     echo >&2 "Skipping non-pixmap \"$i\"" 
     continue ;;
   esac
  echo -n "${b}  recoloring \"$i\"
"

  # --- find out the type ---
  name="`expr "//$i" : '.*/\([^/]*\)'`"          # remove path to file
  name="`expr "$name" : '\(.*\)\.[^.]*$'`"       # remove last suffix

  # --- convert to PbmPlus format ---
  x2p.sed "$i" | xpmtoppm 2>/dev/null > $TMP1
  if [ ! -s $TMP1 ]; then
    echo -n "${b}"
    echo >&2 "Unable to convert \"$i\" to ppm"
    continue
  fi

  # get the original number of colors
  orig_col=`numcolors $TMP1`
  
  # do the recolor (with a bit of color twiking for the old color-cube)
  ppmquant $flag -map $cmap $TMP1 > $TMP2 2>/dev/null

  # find out the result
  if [ ! -s $TMP2 ]; then
    echo -n "${b}"
    echo >&2 "Recoloring (ppmquant) failed for \"$i\""
    continue
  fi
  new_col=`numcolors $TMP2`

  if [ $orig_col -ne $new_col ]; then
    # -- record it as recol_bad --
    echo -n "${b}"
    echo >&2 "WARNING: Color Reduction in \"$i\" ($orig_col to $new_col)"
    ppmtoxpm < $TMP2 2>/dev/null | xpm-fix -o "${name}_recol_bad.xpm"
  else
    # -- copy to recol file --
    ppmtoxpm < $TMP2 2>/dev/null | xpm-fix -o "${name}_recol.xpm"
  fi

done
echo "${b}Done!"

rm -f $TMP1 $TMP2
