#!/bin/sh -
#
# pnmsplitup  size  file
#  where size  is  #  or  #x#
#
#  splitup a pnm file into small pixmaps
#
if [ $# -ne 2 ]; then
  echo "usage: $0 size pnmfile"
fi

case "$1" in
  *x*)           #  resize to fully specified size
      Width=`expr "$1" : '\([0-9]*\)'`
      Height=`expr "$1" : '[0-9]*x\([0-9]*\)'`
      shift ;;
  *)             #  resize to a square of this size
      if  size=`expr "$1" : '\([0-9]*\)'`;  then
        Width=$size
        Height=$size
        shift
      else 
        Usage;
      fi ;;
esac

file=$2

name="`basename $file`"
name="`expr "$name" : '\([^.]*\)'`"

OUT=.
#mkdir $OUT

Xsize=`expr "\`pnmfile $file\`" : '.*, \([0-9]*\)'`
Ysize=`expr "\`pnmfile $file\`" : '.*by \([0-9]*\)'`

X=`expr $Xsize / $Width`   # columns
Y=`expr $Ysize / $Height`  # rows

if expr \( $X \* $Width \) != $Xsize;  then
  echo >&2 "WARNING: $file not split width-wise correctly"
  X=`expr $X + 1`
fi

if expr \( $Y \* $Height \) != $Ysize;  then
  echo >&2 "WARNING: $file not split width-wise correctly"
  Y=`expr $Y + 1` 
fi

x=0; y=0; i=0
while [ $y -lt $Y ]; do
  x=0;
  while [ $x -lt $X ]; do
    # split a pixmap from picture
    n=${name}_`echo $i | awk '{ printf "%x", $1 }'`
    echo "$x x $y  -> $n.ppm"
    pnmcut `expr $x \* $Width`   `expr $y \* $Heigth`
           $Width  $Height  $file  >  $OUT/$n.ppm
    i=`expr $i + 1`
    x=`expr $x + 1`
  done
  y=`expr $y + 1`
done

