#!/bin/@SHL@

DEFAULT_PROCNUM=4

function getproc
{
@AWK@  ' $2 ~ "[Pp][Rr][Oo][Cc][Ee][Ss][Ss][Oo][Rr][Ss]" {
	split($NF,a,"(");
	split(a[2],b,")");
	split(b[1],c,",");
	num=1;
        for ( var in c )  {
                if (c[var] == "number_of_processors") n = '$DEFAULT_PROCNUM'
                else n=c[var]
                num = num * n
        }
	printf num
	exit
} '  ${program}.f
}

function cpgfile
{
case `hostname` in
hnode* ) host=hnode;;
node* ) host=node;;
* )  exit 0 ;;
esac

MAX_NODE=8
echo "${host}1 0 `pwd`/${program}"  > pgfile
count=2
no=2

while test $count -le $1
do
echo "${host}${no} 1 `pwd`/${program}"  >> pgfile
count=`expr $count + 1`
no=`expr $count - 1`
no=`expr $no % $MAX_NODE`
no=`expr $no + 1`
done
}

function exist_adlib
{
if [ -x $ADLIBHOME/src/script/$exec ]
then
	path=$ADLIBHOME/src/script/$exec
elif [ -x $ADLIBHOME/bin/$exec ]
then
	path=$ADLIBHOME/bin/$exec
else
	echo "$exec not found !" &&  exit 1
fi
}

hpfc_flag=
record_flag=0

# parse the flag
for ac_option
do
	case "$ac_option" in
	-record )  record_flag=1 ; shift   ;;
	-*)  	   hpfc_flag=$hpfc_flag" "$1 ; shift   ;;
	esac
done

prefix=@prefix@
exec_prefix=@exec_prefix@
bindir=@bindir@
HPFHOME=@HPFHOME@
ADLIBHOME=@ADLIBHOME@
SCRIPTHOME=@COMPILERHOME@/scripts

exec=pcrcf;  exist_adlib ; pcrcf=$path
exec=prun;  exist_adlib ; prun=$path

program=`echo $1 | sed '/\./s/\.f.*$//' `
outfile=`echo $1 | sed 's/\.f.*$/\.out/' `
sourcef=$*

test "$record_flag" = 1 && touch $outfile

if grep '^!HPF\$' ${program}.f >/dev/null 2>/dev/null || grep -i 'forall' ${program}.f >/dev/null 2>/dev/null
then
  para=1
  echo "$program: ${program}f.f"      > tmp.1
  echo "	${pcrcf} -o ${program} ${program}f.f ; " >> tmp.1
  echo "${program}f.f: ${sourcef}"      >> tmp.1
  echo "	echo \"${SCRIPTHOME}/hpfc $hpfc_flag ${sourcef}\" ;  \\" >> tmp.1
  echo "	${SCRIPTHOME}/hpfc $hpfc_flag ${sourcef} ; " >> tmp.1
else
  para=0
  echo "$program: ${program}.f"      > tmp.1
  echo "	$pcrcf -o ${program} ${program}.f " >> tmp.1
  grep -i 'mpi_init' ${program}.f >/dev/null 2>/dev/null  && para=1
fi

make -f tmp.1 
status=$? && rm -f tmp.1
test $status = 0 || exit 1 

if test $para = 1 
then 
	echo "*********Parallel:${PROGRAM}:`date`***********"
        PROCNUM=`getproc`
        test -z "$PROCNUM" && PROCNUM=$DEFAULT_PROCNUM 
        echo "$prun $PROCNUM `pwd`/$program"
	test "$record_flag" = 1  && $prun $PROCNUM $program > $outfile || $prun $PROCNUM $program 
else
	echo "*********Sequence:${program}:`date`**********"
	test "$record_flag" = 1  && $program > $outfile || $program 
fi
