#!/bin/bash

function filter()
{
    PASS=$1 ; shift
    cpp -P -DPASS_$PASS $* -include ../macros.jin
}

function log()
{
    echo $*
    $*
}

function main()
{
    VARIANT=$SRCDIR/$1
    cd $VARIANT
    rm -f *~ tmp/*
    mkdir -p tmp
    cd tmp
    cp $SRCDIR/macros.jin . # jinja macros common to all variants
    cpp -P -DPASS_JINJA ../macros.jin >> macros.jin # variant-specific macros

    # first expand user-defined CPP and jinja macros
    cat $SRCDIR/kernels_*.jin | cpp -P > caldyn_all.jin
    $PYTHON -u $ROOT/jinja caldyn_all.jin > caldyn_all.dysl
    # then expand the code-generating CPP and jinja macros
    cat caldyn_all.dysl | filter PRE1 | filter PRE2 >> macros.jin
    $PYTHON -u $ROOT/jinja macros.jin > caldyn_all.k90
    # extract each kernel and apply post-jinja CPP macros
    KERNELS=$(grep KERNEL caldyn_all.dysl | cpp -P -D'KERNEL(x)=x')
    for NAME in $KERNELS ; do
	cat caldyn_all.k90 | filter POST1 -DKERNEL_${NAME} | filter POST2 | sed '/^$/d' > ../${NAME}.k90
	head ../${NAME}.k90
    done

    cd ..
    grep ERROR *.k90

    cd $VARIANT
    wc *.k90
    cd $ROOT
}

if [ -z "$CODEGEN_ENV_SET" ] ; then
    cat <<EOF
Before running this script, you must source one of the *.env scripts found in the env/ directory.
This will set up appropriate, machine-dependent values for the following environment variables :
PYTHON F90 C99 CFLAGS FFLAGS LINK SOFLAGS LDFLAGS LIBS ...
EOF
else
    set +x
    
    ROOT=$PWD
    LIBDIR=$ROOT/lib
    SRCDIR=$ROOT/src
    cd $SRCDIR
    grep FIXME *.jin

    for x in $* ; do
	echo "Generating code for variant : $x"
	main $x
    done
fi
