#!/bin/sh
#
# xbm-mask [-e] [-b] bitmap/pixmap...
#
#   Take a X bitmap or X pixmap file and create a mask bitmap file
# of the image. Masks for X bitmaps are created in the same way
# and pbmmask, and the background is automatically determined.
#
# For Xpixmaps the background is white by default. If it is not
# white unexpected results can happen. The -b flag allow you
# to use balck instead of white as the background color.
#
# Any color in a X pixmap which is NOT the background is ensured
# as being part of the resulting mask. This is different to the
# masking method given in the pbmmask manpage which uses a 
# threshold to determine what is and is not part of the mask.
# 
# Mask files for X pixmaps are often created for the sole purpose
# of adding the transparent color into the X Pixmap file. For more
# information on this see  xpm-mask.
#
# OPTIONS
#    -b     Background is black - not white
#    -e     Expand mask by one pixel to form a border
#
# Anthony Thyssen    2 September 1995    <anthony@cit.gu.edu.au>
#
b="                                                                        
"
white=true

# ---- Process options ----
Usage() {
  echo >&2 "Usage: xbm-mask [-e] [-b] bitmap/pixmap..."
  exit 10
}

loop=true
while [ "$loop" ]
do
  case "$1" in
  --) loop= ;;
  -b) white=; shift ;;          # Black background
  -e) expand=-expand; shift ;;  # Expand mask border
  -*) Usage ;;
  *)  loop= ;;
  esac
done

# ---- Process Files ----
TMP1=/tmp/xbm-mask$$.1
TMP2=/tmp/xbm-mask$$.2
trap "rm -f $TMP1 $TMP2; exit 1" 1 2 3 15

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

  # --- convert it to PbmPlus ---
  name="`basename $i`"
  suffix="`expr "$name" : '.*\.\([^.]*\)'`"
  name="`expr "$name" : '\([^.]*\)'`"
  name="`basename $name _masked`"
  name="`basename $name _recol`"
  name="`basename $name _recol_bad`"

  case "$suffix" in
    xbm) sed 's/unsigned //' "$i" | xbmtopbm > $TMP1 ;;
    xpm) x2p.sed "$i" | xpmtoppm  > $TMP1 ;;
    *)   echo -n "${b}"
         echo >&2 "Unknown suffix for \"$i\""
         continue ;;
  esac
  if [ ! -f $TMP1 -o ! -s $TMP1 ]; then
    echo -n "${b}"
    echo >&2 "Unable to Convert \"$i\" to Pbmplus"
    continue
  fi

  # Do the task and convert back
  if [ "$white" ]
  then  pnminvert $TMP1
  else  cat $TMP1
  fi | ppmtopgm | pnmnoraw | sed '4,$s/[1-9][0-9]*/255/g' |
    pgmtopbm -threshold | pbmmask $expand > $TMP2

  if [ ! -f $TMP2 -o ! -s $TMP2 ]; then
    echo -n "${b}"
    echo >&2 "Failed to Create a mask for \"$i\""
    continue
  fi
  
  # --- convert to "_mask.xbm" ---
  pbmtoxbm < $TMP2 |
    sed 's/static  *char/static unsigned char/;
         s/noname\([[_]\)/'"$name"'\1/' > "${name}_mask.xbm"

done
echo "${b}Done"

rm -f $TMP1 $TMP2

