#!/bin/ksh

# listvalidinst - list valid instruments from the instrument.list 
#	data file in sorted order.

# outputs results to temporary file /tmp/instruments

datadir=/data/rgroman/Inventory
inputfile=instrument.list
#inputfile=instrument.list-test
outputdir=/tmp
outputfile=${outputdir}/instruments
tempdir=/tmp
tempfile=$tempdir/instruments.tmp

cd $datadir

#echo " **DEBUG input data file = $datadir/$inputfile \n"

if [ -a $outputfile ]; then
	\rm $outputfile
fi

if [ ! -r $datadir/$inputfile ]; then
	echo "*** Error: Cannot read the instrument input file "
	echo "$datadir/$inputfile \n"
	exit 1
fi

now=` date +"%B %d,%Y %r" `
echo "#Instrument list created $now" > $outputfile

cat $datadir/$inputfile | while read record
do
set -A input $record
#echo " **DEBUG input= ${input[*]}"
if [[ ${#input[*]} -le 1 ]]; then
#	echo " **debug - instrument found with no equivalence. Record = $input \n"
	continue
fi

let hash=`echo  ${input[*]} | grep -c "#" `
if [[ $hash -ge 1 ]]; then
	continue
fi

# Parse record to get at "real" names, i.e. 2nd, 3rd, etc. entries
# Assumes spaces or tabs separate fields and that "real" spaces show
# up as "%".

let numbelements=${#input[*]}
#echo " **DEBUG numbelements = $numbelements \n"
while test $numbelements -gt 1
do
	let index=$numbelements-1
	echo "${input[$index]}" >> $outputfile
#	echo " **DEBUG output to outputfile= ${input[$index]}"
	let numbelements=$numbelements-1
	
done

done

if [ -a $tempfile ]; then
	\rm $tempfile
fi

sort -u $outputfile > $tempfile
\cp $tempfile $outputfile
\rm $tempfile
chmod 666 $outputfile
exit 0
