#!/bin/sh
#
# This script is a part of FreeUSP - the UNIX Seismic Processing system.
#

QUERY="false"

case "$1" in
  "-?"|"-h")
	echo Usage: rmprint [-i] [-h] [-?]
	echo "         -i - query user before file deletion occurs"
	echo "         -h"
	echo "      or -? - print this help"
	exit 0;;
  "-i")
	QUERY="true";;
esac
#
# - modified 7/25/96 to use grep's regular expressions. - jmw
#
# - changed first part of matching rule to include special characters
#   '_' and ':'  
#
# - also limited it to files that start with two letters or a letter-number
#   combination (note - no special characters in the first two letters)
#
if  [ -x /bin/awk ]
then
  AWK=/bin/awk
else
  if  [ -x /usr/bin/awk ]
  then
    AWK=/usr/bin/awk
  else
    AWK=awk
  fi
fi

if  [ -x /bin/sed ]
then
  SED=/bin/sed
else
  if  [ -x /usr/bin/sed ]
  then
    SED=/usr/bin/sed
  else
    SED=sed
  fi
fi

#
# Added this to prevent upper/lower case matching on Linux
#
LC_ALL=C
export LC_ALL

MATCHEDFILES=""

FILELIST=`ls -1 | egrep '(^[A-Z][0-9A-Z][_:0-9A-Z]*[.][0-9][0-9]*[0-9]$|^[A-Z][_0-9A-Z]*[.][0-9][0-9]*[0-9][.].*$)' | grep -v 'README[.]*' `

if test "${FILELIST}" = ""
then
   echo No files found
   exit 0
fi

for prt in $FILELIST

do
type=`usp file ${prt} | ${AWK} -F: '{print $2}'  | tr '[A-Z]' '[a-z]' |\
   ${SED} 's/^\([^a-z]*\)\([a-z].*\)$/\2/'`

case "$prt" in
  *.usp)
	type="usp";;
  *.USP)
	type="usp";;
  *.segy)
	type="segy";;
  *.SEGY)
	type="segy";;
  *.sgy)
	type="segy";;
  *.SGY)
	type="segy";;
esac

case "$type" in
  text*)
	MATCHEDFILES="${MATCHEDFILES} ${prt}";;
  english*)
	MATCHEDFILES="${MATCHEDFILES} ${prt}";;
  ascii*)
	MATCHEDFILES="${MATCHEDFILES} ${prt}";;
  empty*)
	MATCHEDFILES="${MATCHEDFILES} ${prt}";;
  usp*)
	echo "file ${prt} is USP format data; bypassing";;
  segy*)
	echo "file ${prt} is SEGY format data; bypassing";;
  data*)
	echo "file ${prt} appears to be data ; bypassing";;
  *)
	echo "cannot identify file ${prt} ( type-${type} ) ; bypassing";;
esac
done

if test "${MATCHEDFILES}" = ""
then
	exit 0
fi

if test ${QUERY} = "true"
then
( echo "Files to be deleted:" ; echo $MATCHEDFILES | ${AWK} '{for (file=1; file <= NF; file ++){printf("     %s\n",$file)}}' ; echo 'OK to remove (yn) ? ') | more

read ans

if test "${ans}" = "y"
then
	rm ${MATCHEDFILES}
	echo ' '
	echo "*** files removed ***"
	exit 0
fi
else
	rm ${MATCHEDFILES}
fi
