#!/bin/bash

ROOT=$PWD
MOD=$ROOT/xmod
INC=/usr/lib64/openmpi/1.8.8-gfortran49/include

function parse()
{
    cd $1 ; shift
    for SRC in $* ; do
	F_Front -M $MOD -I $INC $SRC.f90 -o $ROOT/xml/$SRC.xml > $ROOT/xml/$SRC.err 2>&1
    done
    cd $ROOT
}

function add_srcfiles()
{
    while (($# > 0)) ; do
	DIR=$1
	SRC=$2
#	echo $SRC ${dir[$SRC]}
	if [[ -z ${dir[$SRC]} ]] ; then
#	    echo "add_srcfiles : $NUMFILE $DIR $SRC"
	    src[$NUMFILE]=$SRC
	    dir[$SRC]=$DIR
	    ok[$SRC]=NO
	    ((NUMFILE++))
	fi
	shift ; shift
    done
}

NETCDF=netcdf-fortran-4.4.5
if [ ! -d "$NETCDF" ]; then
    tar xzvf ${NETCDF}.tar.gz
fi

rm -f xml/* xmod/*
echo "Parsing NetCDF ..."
parse ${NETCDF}/fortran typeSizes netcdf4
echo "... done."

# create arrays
declare -a src
declare -A dir
declare -A ok 
NUMFILE=0

# first read from text file parse_order.txt
touch parse_order.txt
add_srcfiles $(cat parse_order.txt)
# then, for completeness and bootstrapping, add files found in relevant places
for DIR in $(find ../tools/ioipsl ../src ../ppsrc external_src -type d) ; do
    cd -P $ROOT/$DIR
    for F90 in $(ls *.f90 2>/dev/null) ;  do
	SRC=$(echo "$F90" | cut -d'.' -f1)
	add_srcfiles $DIR $SRC
    done
done
cd $ROOT

echo "$NUMFILE files to be parsed."
rm -f parse_order.txt

PASS=0
AGAIN=YES

while [[ "$AGAIN" == "YES" ]] ; do
    AGAIN=NO
    ((PASS++))
    echo "------------------ pass $PASS ------------------"
    for SRC in ${src[@]} ; do
	DIR=${dir[$SRC]}
	YESNO=${ok[$SRC]}
	if [[ "$YESNO" == "NO" ]] ; then
	    parse $DIR $SRC
	    grep 'failed to import module' xml/$SRC.err > /dev/null
	    if [ $? -ne 0 ]; then
		echo "$SRC : $DIR/$SRC.f90"
		echo "$DIR $SRC" >> parse_order.txt
		ok[$SRC]=YES
		AGAIN=YES
	    else
		rm xml/$SRC.xml
	    fi
	fi
    done
done

echo "------------------------------------"
for SRC in ${!dir[@]} ; do
    DIR=${dir[$SRC]}
    YESNO=${ok[$SRC]}
    if [[ "$YESNO" == "NO" ]] ; then
	echo "Unable to parse : $SRC $DIR/$SRC.f90, check xml/$SRC.err"
    fi
done

# cleanup
find xml -name '*.err' -size 0 -print0 | xargs -0 rm
