#!/bin/sh
#
# Standardize the include guard in the given header file.
# The guard (ending with _H) is replaced by:
#  #ifndef <package>_<file>_H
#  #define <package>_<file>_H
# where <package> is the package name in uppercase (e.g. scimath)
# and <file> is the base name of the file (in uppercase) without the .h part.
# The package name is derived from the file path.
#
# The change means that all #ifndef and #define lines containing a single
# name ending with _H get changed, so in theory other lines than the
# include guard might get changed.
# To make that risk as small as possible, a diff of the old and new file
# is printed and it is checked if only 2 lines have been changed.
# If not, the message "Warning: 2 lines should have been changed" is written.
#
# The script dosedguard makes use of this script. For dosedguard purposes
# The old guard is appended to guard.allold and the new guard is appended
# to guard.allnew.
#
# Run as:
#    dosedguard_one <file>


# Determine the include tag from the file name.
# Add the current path to the file name.
# Remove ./ from it.
  fil=`pwd`/$1
  fil=`echo $fil | sed -e 's%\./%%g'`
# Use package_filename (all in uppercase) followed by _H as the guard.
  a1=`echo $fil | sed -e 's%^code/%%' -e 's%.*/code/%%' -e 's%^\./%%'`
  apkg=`echo $a1 | sed -e 's%/.*%%'`
  a3=`echo $a1 | sed -e 's%.*/%%'`
  afil=`echo $a3 | sed -e 's%\.%_%'`
  anm=`echo "${apkg}_$afil" | tr '[a-z]' '[A-Z]'`
# For a few .h files in casa/implement _STD is added to the include tag to
# avoid that it is the same as some other ones.
  if [ "$a3" = "vector.h" -o "$a3" = "math.h" -o "$a3" = "string.h" -o "$a3" = "complex.h" ]; then
    anm=`echo $anm | sed -e 's/_/_STD_/'`
  fi

# Save the guard and the filename.
  a4=`egrep '^# *define *.*_H_? *$' $1 | sed -e 's/ \+//g' -e 's/^#define//'`
  echo "$a4 $1" >> guard.allold
  echo "$anm $1" >> guard.allnew
  echo "Changing guards of $1 ..."
  sed $1 -e "s/^# *ifndef .*_H_\? *\$/#ifndef $anm/" \
         -e "s/^# *if *! *defined *(.*_H_\? *) *\$/#ifndef $anm/" \
         -e "s/^# *if *! *defined *.*_H_\? *\$/#ifndef $anm/" \
         -e "s/^# *define *.*_H_\? *\$/#define $anm/" > $1.new
# Check if the guards are in the correct format.
  isok=0
  egrep '^# *ifndef .*_H$' $1.new > atmp
  egrep '^# *define .*_H$' $1.new >> atmp
  nlin=`wc -l atmp | awk '{ print $1 }'`
  if [ $nlin = 2 ]; then
    l1=`head -1 atmp`
    l2=`tail -1 atmp`
    if [ "$l1" = "#ifndef $anm"  -a  "$l2" = "#define $anm" ]; then
      isok=1
    fi
  fi
  if [ "$isok" != "1" ]; then
    echo "Warning: 2 lines should have been changed"
  fi
  diff $1.new $1
  \rm -f atmp
  mv $1.new $1
