#! /bin/csh
#
# Extract cliches a la PRECOMP.
#
set na=$#argv
#
if ($na == 1) then
  set infile=$1
  set outfile=p$1
else if ($na == 2) then
  set infile=$1
  set outfile=$2
else
  echo ''
  echo "### PRECOMP:"
  echo "### Extract cliches into include files."
  echo ''
  echo 'Usage:'
  echo ''
  echo 'precomp <infile> [<outfile>]'
  echo ''
  echo 'If <outfile> is not supplied, it is named "p<infile>".'
  exit 1
endif
#
# Check that the input file will not be overwritten.
#
if ("$outfile" == "$infile") then
  echo ''
  echo "### PRECOMP:"
  echo '### ERROR: Input and output file names are identical.'
  exit 1
endif
#
# Process the input file.
#
sed 's/^\([ 	]*\)use[ 	][ 	]*\([a-zA-Z][a-zA-Z0-9]*\)[ 	]*$/\1include '"'"'\2.inc'"'"'/' $infile  |\
awk '\
BEGIN {divert = 0; ofile="'$outfile'"; newof=1}\
{if (NF == 2 && $1 == "cliche") {divert=1; ifile=$2 ".inc"; newif=1; next}}\
{if (NF == 1 && $1 == "endcliche") {divert=0; next}}\
{if (divert == 0)\
   if (newof == 1) {print >ofile; newof=0} else print >>ofile\
 else\
   if (newif == 1) {print >ifile; newif=0} else print >>ifile\
}'
