#!/bin/sh
#
# "fscale"	K. J. Turner	15/12/94
#
# This shell script takes one or more FrameMaker MIF (Maker Interchange
# Format) documents and replaces them with new versions according to the
# following:
#
#  -fn oldfont/newfont	to change a font
#  -fs oldsize/newsize	to change the size of all fonts
#
# The result code is 0 if there are no errors, otherwise 1.

extframe=".framemif"
prog=`basename $0`
code=0
font="xyz/xyz"
size="10/10"
files=""
tmpfile="/tmp/$prog$$"

if [ $# -eq 0 ]
  then
    echo "usage: $prog [-fn old/newfont] [-fs old/newsize] file[$extframe] ..."
    code=1
  else
    while [ $# -gt 0 ]
      do
        case $1 in
	  -fn)
	    font=$2; shift 2;;
	  -fn*)
	    font="`expr $1 : '-fn\(.*\)'`"; shift;;
	  -fs)
	    size=$2; shift 2;;
	  -fs*)
	    size="`expr $1 : '-fs\(.*\)'`"; shift;;
	  -*)
	    echo "$prog: illegal option $1"
	    exit 1;;
	  *)
	    files="$files $1"; shift;;
        esac
      done
      
    oldfont="`expr "$font" : '^\([^/]*\)'/.*`"
    newfont="`expr "$font" : '^.*/\([^/]*\)'`"
    oldsize="`expr "$size" : '^\([^/]*\)'/.*`"
    newsize="`expr "$size" : '^.*/\([^/]*\)'`"
    
    for file in $files
      do
	name="`expr Z$file : Z'\(.*\)\'$extframe`"
	if [ "$name" = "" ]
	  then name=$file; infile="$name$extframe"
	  else infile=$file
	fi
	if [ -f $infile -a -r $infile ]
	  then
	      awk '
	        BEGIN {
		  scale = '$newsize' / '$oldsize';
		}
		/<.*Family '\`$oldfont\''>/ {
		  print $1 " '\`$newfont\''>";
		  next;
		}
		/<FSize / || \
		  /<PgfSpBefore / || /<PgfSpAfter / || /<PgfLeading / || \
		  /<TblSpBefore / || /<TblSpAfter / || /<TblTitleGap / {
		    if ($1 == "<FSize")
		      printf ("%s %3.0f %s\n", $1, ($2 * scale) + 0.049, $3);
		    else
		      printf ("%s %3.1f %s\n", $1, ($2 * scale) + 0.049, $3);
		    next;
		  }
		/<TSX / || \
		  /<PgfFIndent / || /<PgfLIndent / || /<PgfRIndent / || \
		  /<TblColumnWidth / || /<RowHeight / {
		    split ($2, ins, "\"");
		    if (($1 == "<TSX") && (ins[1] >= 3.0))
		      print;
		    else
		      printf ("%s %3.1f\"%s\n", $1, \
		        (ins[1] * scale) + 0.049, ins[2]);
		    next;
		  }
		{print;}
	      ' $infile > $tmpfile
	      mv $tmpfile $infile
	  else
	    echo "$prog: cannot read \"$infile\""
	    code=1
	fi
      done
fi

exit $code
