#!/bin/sh
 
#    Jul 27/92 - E. Chan 

#id  fixvar  - changes variables MAX and MIN to MAXX and MINN in files 
#id            containing Fortran code 

#    AUTHOR  - E. Chan (Jul 15/92)

#hd  PURPOSE - "fixvar" changes the variable names MAX and MIN to MAXX and
#hd            MINN in order to avoid conflicts with the Fortran intrinsic
#hd            functions with the same names. 

#pr  PARAMETERS:
#pr 
#pr    POSITIONAL
#pr 
#pr      fn1 fn2 ... fnm = list of m files that require fixing
#pr    
#pr    SECONDARY
#pr
#pr      change = switch to make changes permanent or to just list out
#pr               the possible changes (='no'/'yes')

#ex  EXAMPLE
#ex  
#ex   fixvar * change
#ex  
#ex   The above example fixes all files in the current directory. 

#  * Check for options.

for arg 
do
  case $arg in 
    change) eval 'change=yes'              ;;   
	 *) file_list="$file_list $arg"
  esac
done

#  * Loop over all files in the input list.

for file in $file_list
do

  # Ensure that only existing ascii text files are operated on.

  info=`file $file 2>/dev/null `
  infox=`expr "$info" : '.*\(data.*\).*'`
  if [ "$infox" != 'data or International Language text' ] ; then
   file_status=`expr "$info" : '.*\(text\).*'`
   file_status=${file_status:=`expr "$info" : '.*\(character\).*'`}
  fi

  if [ ! -f "$file" ] ; then
    echo "file $file does not exist: resuming execution with next file in list"
  elif [ -z "$file_status" ] ; then
    echo "file $file is not an ascii text file: file skipped"
  else
    if [ "$change" = 'yes' ] ; then
      sed '/[^A-Z0-9]MAX[^A-Z0-9]/{
	   /^C/b
	   /......FORMAT/b
	   :labl1
	   s/\([^A-Z0-9]\)MAX\([^A-Z0-9]\)/\1MAXX\2/
	   t labl1
	   s/MAXX\( *(\)/MAX\1/g
	   }
           /[^A-Z0-9]MIN[^A-Z0-9]/{
	   /^C/b
	   /......FORMAT/b
	   :labl2
	   s/\([^A-Z0-9]\)MIN\([^A-Z0-9]\)/\1MINN\2/
	   t labl2
	   s/MINN\( *(\)/MIN\1/g
           }'                                   $file > tmpfile$$
      mv tmpfile$$ $file
    else
      sed -n '1p
              /[^A-Z0-9]MAX[^A-Z0-9]/{
	      /^C/b
	      /......FORMAT/b
	      :labl1
	      s/\([^A-Z0-9]\)MAX\([^A-Z0-9]\)/\1MAXX\2/
	      t labl1
	      s/MAXX\( *(\)/MAX\1/g
	      /MAXX/p
	      }
              /[^A-Z0-9]MIN[^A-Z0-9]/{
	      /^C/b
	      /......FORMAT/b
	      :labl2
	      s/\([^A-Z0-9]\)MIN\([^A-Z0-9]\)/\1MINN\2/
	      t labl2
	      s/MINN\( *(\)/MIN\1/g
	      /MINN/p
	      }'                               $file
    fi
  fi 
done

exit
