#!/bin/bash
#------------------------------------------------
#$Id$
#------------------------------------------------
#
set -u
#
inxml=0
insrc=0
while [ $# -gt 0 ]   # Until you run out of parameters . . . 
do    
    case "$1" in 
        --inxml) inxml=1 ;;
        --insrc) insrc=1 ;;
    esac
    shift       # Check next set of parameters. 
done 
#
xmlfile=${1:-"../CONFIG/ORCA2_LIM/EXP00/iodef.xml"}
#
srcdir=${2:-"../NEMO/OPA_SRC ../NEMO/LIM_SRC_2"}
#
#------------------------------------------------
#
[ $inxml -eq 1 ] && grep "< *field * id *=" $xmlfile
[ $insrc -eq 1 ] && find $srcdir -name "*.[Ffh]90" -exec grep -iH "^[^\!]*call  *iom_put *(" {} \;
[ $(( $insrc + $inxml )) -ge 1 ] && exit
#
#------------------------------------------------
#
# list of file containing "CALL iom_put" in $srcdir
#
srclist=$( find $srcdir -name "*.[Ffh]90" -exec grep -il "^[^\!]*call  *iom_put *(" {} \; )
#
# list of variables used in "CALL iom_put"
#
varlistsrc=$( find $srcdir -name "*.[Ffh]90" -exec grep -i  "^[^\!]*call  *iom_put *(" {} \; | sed -e "s/.*iom_put *( *[\"\']\([^\"\']*\)[\"\'] *,.*/\1/" | sort -d )
#
# list of variables defined in the xml file
#
varlistxml=$( grep "< *field * id *=" $xmlfile  | sed -e "s/^.*< *field * id *= *[\"\']\([^\"\']*\)[\"\'].*/\1/" | sort -d )
#
# list of variables to be outputed in the xml file
#
varlistout=$( grep "< *field * ref *=" $xmlfile  | sed -e "s/^.*< *field * ref *= *[\"\']\([^\"\']*\)[\"\'].*/\1/" | sort -d )
#
echo "--------------------------------------------------"
echo  check if all iom_put found in $srcdir
echo  have a corresponding variable definition in $xmlfile
echo "--------------------------------------------------"
for var in $varlistsrc
do
    tst=$( echo " "$varlistxml" " | grep -c " $var " )
    if [ $tst -ne 1 ] 
    then
	echo "$tst problem with $var, defined in"
	for f in $srclist
	do
	    grep -iH "^[^\!]*call  *iom_put *( *[\"\']${var}[\"\'] *," $f
	done
	echo
    fi
done
#
echo "--------------------------------------------------"
echo  check if all variables defined in $xmlfile
echo  have a corresponding \"call iom_put\" in sources found in $srcdir
echo "--------------------------------------------------"
#
for var in $varlistxml
do
    found=$( echo " "$varlistsrc" " | grep -c " $var " )
    if [ $found -eq 0 ] 
    then
	echo \"call iom_put\" not found for variable $var
	grep "< *field * id *= *[\"\']${var}[\"\']" $xmlfile
	echo
    fi
done
#
echo "--------------------------------------------------"
echo  ${xmlfile}: check if all variables to be outputed in files are really defined...
echo "--------------------------------------------------"
#
# list of variables defined in the xml file
for var in $varlistout
do
    found=$( echo " "$varlistxml" " | grep -c " $var " )
    [ $found -eq 0 ] && echo variable to be outputed but not defined: $var 
done



exit
