#!/bin/sh
#
# xbm-resize  [ -# | -#x# ]  bitmap...
#
#    Using the pbmplus package resize all the given bitmaps or pixmaps 
# to the size given on the command line. The default size is 64x54 pixels
#
#  Anthony Thyssen         29 Oct 1993       anthony@cit.gu.edu.au
#

Width=64    # default width and height of icon to produce
Height=54
Margin=35   # margin to add to the icon ( must be >= 1/2 * max(Width,Height) )

b="                                                                        
"

Usage() {
  echo >&2 "Usage: xbm-resize [ -# | -#x# ] bitmap/pixmap..."
  exit 10
}

loop=true
while [ "$loop" ]
do
  case "$1" in
  --) loop= ;;
  -*x*)           #  resize to fully specified size
      Width=`expr "$1" : '-\([0-9]*\)'`
      Height=`expr "$1" : '-[0-9]*x\([0-9]*\)'`
      size=$Width
      [ "$size" -lt "$Height" ] && size=$Height
      Margin=`expr $size / 2 + 1`
      shift ;;
  -*)             #  resize to a square of this size
      if  size=`expr "$1" : '-\([0-9]*\)'`;  then
        Width=$size
        Height=$size
        Margin=`expr $size / 2 + 1`
        shift
      else 
        Usage;
      fi ;;
  *)  loop= ;;
  esac
done

# ----- MAIN LOOP -----

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

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

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

  case "$suffix" in
    xbm)   xbmtopbm  > $TMP1 ;;
    xpm)   xpmtoppm  > $TMP1 ;;
    *)   echo -n "${b}"
         echo >&2 "Unknown suffix for \"$i\""
         continue
  esac

  # --- find out if we need to make a backup first (on cropped size) ---
  # NOTE: this does not always work!
  set - `pnmcrop $TMP1 2>/dev/null | pnmfile | sed 's/.*,//'`
  [ $? -ne 0 ] && continue
  if  expr  $1 \> $Width \| $3 \> $Height >/dev/null;  then
    echo "${b}"
    echo >&2 "Icon \"$i\" shrinks in size ... making copy"
    echo -n "  resizing \"$i\"
"
    merge -c $i $i
  fi

  # --- add margins and cut out to correct size ---
  set - `pnmfile $TMP1 | sed 's/.*,//'`
  X=`expr \( $1 - $Width \) / 2 + $Margin` 
  Y=`expr \( $3 - $Height - 1 \) / 2 + $Margin`  # -1 to lower picture
  pnmmargin $Margin $TMP1 | pnmcut $X $Y $Width $Height > $TMP2

  # --- convert back ---
  case "$suffix" in
    xbm) pbmtoxbm < $TMP2 > "$i" ;;
    xpm) ppmtoxpm < $TMP2 2>/dev/null > "$i" ;;
  esac
done
echo "${b}done"

