#!/bin/sh
#

FILPAT="PNG image data"
FILEXT=png

conv_img() 
{
  FILNAM="$1"
###
### Check if file parmater is present
###
  if [ -z "$FILNAM" ] ; then
    echo "Error: no file parameter"
    echo "Usage: `basename $0` $FILEXT-file"
    exit 1
  fi
###
### Check if extension is specified
###
  EXTPAT=".${FILEXT}$"
  if [ -z `echo $FILNAM|grep "$EXTPAT"` ] 
  then INPNAM="$FILNAM.$FILEXT"
  else INPNAM="$FILNAM"
       FILNAM="`echo $FILNAM|sed \"s/$EXTPAT//\"`"
  fi
###
### Check if file is present
###
  if [ ! -f "$INPNAM" ] ; then
    echo "Error: file $INPNAM does not exist"
    exit 2
  fi
###
### Check if file is a correct $FILEXT file
###
  RES=`file $INPNAM|grep "$FILPAT"`
  if [ -z "$RES" ] ; then
    echo "Error: file $INPNAM is no valid $FILEXT-file"
    exit 3
  fi
###
### Create output name
###
  if [ ! -z "$2" ] 
  then FILOUT="$2.gif"
  else FILOUT="$FILNAM.gif"
  fi
###
### Do conversion...
###
  
  ${FILEXT}topnm "$INPNAM" | ppmquant 256 | ppmtogif  > "$FILOUT"
  if [ -f $FILOUT ] 
  then rm $INPNAM
  else echo "Error: no output file created."
  fi
}

for F in $*
do echo "Converting $F..."
   conv_img $F
done
