#!/bin/sh -
#
#  x2p [-t]  files...
#
#   This script converts xbm and xpm files to the pbmplus format
# Modified to allow conversion of the transparent colour for xpm files
#
# NOTE: created files are placed in the current directory.
#
# Anthony Thyssen   3 November 1995    anthony@cit.gu.edu.au
#
b="                                                                         
"
TRANS=
if [ "X$1" = "X-t" ]; then
  TRANS="#BFBFBF"  # the transparent color to use.
  shift
fi

for i in "$@" ; do
  if [ ! -r "$i" ]; then
    echo -n "${b}"
    echo >&2 "Unable to read \"$i\""
    continue
  fi

  echo -n "${b}  converting \"$i\"
"

  # --- find out the type ---
  name="`expr "//$i" : '.*/\([^/]*\)'`"               # remove path
  suffix="`expr "$name" : '.*\.\([^.]*\)$'`"          # extract last suffix 
  dest="`echo "$name" | sed 's/.x\([bp]\)m$/.p\1m/'"  # destination name

  case "$suffix" in
    xbm)
      # just direct convert (no transparancy)
      sed 's/unsigned //' "$i" | xbmtopbm > "$dest"
      ;;
    xpm)
      if [ $TRANS ] && grep 'c  *None' "$i" >/dev/null; then
        # convert None to transparent color (above)
        sed "s/c  *[Nn]one/c $TRANS/g" "$i" |
           x2p.sed | xpmtoppm > "$dest"
      else
        # straight conversion
        x2p.sed "$i" | xpmtoppm > "$dest"
      fi
      ;;
    *)
      echo -n "${b}"
      echo >&2 "Unknown suffix for \"$i\""
      continue ;;
  esac

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

done
echo "${b}DONE!"
