#!/bin/sh -
#
# gif2xpm [-t] files...
#
#   This uses the pbmplus package to convert GIF files into
# X bitmaps and X pixmap format files approriately. If a -t flag is
# given and the destination is a pixmap, than it will also set the
# None Color in the X Pixmap file to that used in the GIF file.
#
# WARNING: the -t option required "giftrans" to also be available on
# your path so that it can figure out the transparent color to modify.
#
# Anthony Thyssen    1 September 1995    <anthony@cit.gu.edu.au>
#
b="                                                                         
"
TRANS=
TMP=/tmp/gif2xbm.$$
trap "rm -f $TMP; exit 1" 1 2 3 15

Usage() {
  echo >&2 "Usage: gif2xbm [-t] [-q #] Gifs..."
  echo >&2 "    -t     preserve transparency"
  exit 10
}

loop=true
while [ "$loop" ]
do
  case "$1" in
  -t) TRANS=true; shift ;;      # preserve transparenty
  --) loop=; shift ;;
  *) loop= ;;
  esac
done

trap "rm -f $TMP; exit 0" 1 2 3 15

for i in "$@" ; do
  echo -n "${b}  converting \"$i\"
"
  if [ ! -f "$i" ]; then
    echo -n "${b}"
    echo >&2 "Unable find file \"$i\""
    continue
  fi

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

  if [ "$suffix" != "gif" ]; then
    echo -n "${b}"
    echo >&2 "Suffix not \".gif\" : \"$i\" -> \"$suffix\""
    continue
  fi

  # Determine transparent color if present
  tcolor=
  if [ "$TRANS" ]; then
    giftrans -L "$i" 2>&1 | grep Color > $TMP
    if  grep "Transparent Color Flag: True" $TMP >/dev/null; then
      tcolor=`nawk '#  Figure out the Transparent color 
        $1 == "Color" && $2 ~ /^[0-9][0-9]*:$/ {
                color[substr($2, 1, length($2)-1)+0] = $9; }  # color table
        /Transparent Color Index:/ { c = $4; }          # TRANS color index
        END { print color[c] }                   # output transparent color
        ' $TMP | tr 'a-f' 'A-F' `
    fi
  fi

  # Convert gif and figure out destination format
  # case on the standard error on gif filter!!
  case  "`giftopnm -verbose "$i" 2>&1 >$TMP`"  in
    *PBM*)
      dest="$name.xbm"
      pbmtoxbm < $TMP |
        sed 's/static  *char/static unsigned char/;
             s/noname\([[_]\)/'"$name"'\1/'  > "$dest"
      ;;
    *P?M*)
      dest="$name.xpm"
      if [ "$tcolor" ]; then
        ppmtoxpm $TMP 2>/dev/null |
          sed "/colors/,/pixels/s/c $tcolor/c None/" |
          xpm-fix -o "$dest"
      else
        ppmtoxpm $TMP 2>/dev/null | xpm-fix -o "$dest"
      fi
      ;;
    *) echo -n "${b}"
       echo >&2 "Unable to Parse GIF file \"$i\"!!!!"
       continue
  esac

  if [ ! -s "$dest" ]; then
    rm -f "$dest"
    echo -n "${b}"
    echo >&2 "Failed to convert \"$i\""
  fi

done

echo "${b}DONE!"

rm -f $TMP

