
# wpmerge
# usage:  wpmerge  [-c] <form file> <data file> <output file>
# 
# NOTE:  WPFORMAT will overwrite the output file.

# INITIALIZE VARIABLES
USAGE="Usage: wpmerge [-c] form_file data_file output_file"
USAGE2="Use -c to convert the data_file to WordPerfect format before merging."
USAGE3="Note: The output_file will be overwritten if it exists."

# TEST FOR CONVERT FLAG
if test "$1" = "-c"
then
		CONVERT="True"
		shift
fi

# READ COMMANDLINE OPTIONS
if test "$3" = ""						# Must have all three commandline options
then
		echo $USAGE						# Just send usage statement
		echo " "$USAGE2
		echo " "$USAGE3
		exit
fi

FORMFILE=$1
DATAFILE=$2
OUTPUTFILE=$3

# Find the default directory for wprint
WPPWD=`pwd`
if   [ "$0" = wpmergec ]; then
	for Dir in `echo $PATH | sed "y/:/ /"`; do		# part of path 
		if [ -f $Dir/wp -a -x $Dir/wp ]; then
			Work=$Dir/$0; break;
		fi;
	done;
elif [ `echo $0 | sed 's|/.*$|/|'` = "/" ]; then	# root path
	Work=$0;
else Work=`echo $WPPWD/$0 | sed 's|/\./|/|'`;		# relative path
fi;

while [ "`echo $Work | grep '\.\.'`" != "" ]; do	# simplify it
	Work=`echo $Work | sed 's|[^/]*/\.\./||'`; done;

while [ ! -f "$Work" ]; do						# ask if bad
	echo;
	echo $N "  Enter WordPerfect Installation Directory: $C"; read Work;
	Work=$Work/wpbin/wp;
done

DIRECTORY=`echo $Work | sed 's|/[^/]*$||' | sed 's|/[^/]*$||'`;

WPRINT=$DIRECTORY/shbin10/wprint		# Path to WPRINT
WPFORMAT=$DIRECTORY/shbin10/wpformat	# Path to WPFORMAT		
CVT=$DIRECTORY/shbin10/cvt				# Path to CVT
cd $WPPWD

if [ "$CONVERT" = "True" ]
then
	if [ -f $CVT ]
	then
		CVTOUT=/tmp/wpmerge_`date +%y%m%d_05/04/98M`
		$CVT $DATAFILE $CVTOUT wp60 -s -i=DTXT
			#NOTE: DTXT refers to "Delimited Text" type.
			#	   To change the delimiters, start WordPerfect (xwp)
			#	   and chose "Preferences" and then "Convert"
		ERROR=$?
		if [ $ERROR != 0 ]				# Did it convert OK?
		then
        	echo "wpmerge: $CVT failed"
			echo
			exit $ERROR
 		fi

		#Now use converted file
		DATAFILE=$CVTOUT

	else
		echo "wpmerge: $CVT not found"
		echo 
		exit 2
	fi
fi

if [ -f $WPRINT ]						# Make sure executable exists
then
	if [ -f $WPFORMAT ]					# Make sure executable exists
	then
		# Merge (-m) the files 
		# and wait (-w) until submitted to spooler before continuing
		$WPRINT -w -m  $FORMFILE $DATAFILE $OUTPUTFILE 
		rm -f $CVTOUT
	else
		rm -f $CVTOUT
		echo "wpmerge: $WPFORMAT not found"
		echo
		exit 1
	fi
else
	rm -f $CVTOUT
	echo "wpmerge: $WPRINT not found"
	echo
	exit 2
fi

echo

