# Build the LPJ library

set lib_name = lib_lpj
mkdir -p $executable:h:h/$lib_name

set pathnames = $executable:h:h/$lib_name/lpj_paths-$$

# sigh. prepare the list of LPJ files. This is a little more work
setenv LPJSRC LPJmL
#setenv LPJSRC LPJ_20121005
#setenv LPJSRC LPJmL_internal.git

if ( ! -f $code_dir/land_atlantes/$LPJSRC/Makefile.inc ) then
    echo "Error: no file $code_dir/land_atlantes/$LPJSRC/src/Makefile.inc"
    cat $code_dir/land_atlantes/README
    exit 1
endif

# Autumn 2020: compile without -DDAILY_ESTABLISHMENT but with -DPERMUTE
(cd $code_dir/land_atlantes/$LPJSRC/src ; make -B -n libs getbuild.o lpj_climber4.o) |& \
  awk 'BEGIN { lpjsrc="'$code_dir/land_atlantes/$LPJSRC'"; dir=lpjsrc "/src"; } \
	/Entering directory/ { dir=gensub("'\''","","g",$NF); } \
	/Leaving directory/ { dir=lpjsrc "/src"; } \
	/ -c / { \
	    base=$NF; \
	    if (base=="iterate.c"||base=="iterateyear.c"||base=="iterateyear_river.c") next; \
	    $NF=""; \
	    file=dir "/" base; \
	    sub("-I\\.\\./\\.\\./","-I" lpjsrc); \
	    sub("-I\\.\\./","-I" lpjsr); \
	    sub("-DSTORECLIMATE",""); \
	    sub("-DPERMAFROST",""); \
	    print $0, "$(LPJ_OPTFLAGS) $(LPJ_DEBUGFLAGS) -DCOUPLING_WITH_FMS -DUSE_FMSCLOCK -DPERMUTE", file;}' >> $pathnames

if( $status ) then
    echo "failed to create $lib_name/pathnames"
    rm $pathnames
    exit 1
endif

if ( "$?debug" && "$debug" == "-debug" ) then
    sed -e 's/-O.//' -e 's/-ipo//' -e 's/-x[-a-zA-Z0-9]*//' $pathnames > $pathnames-new
    mv $pathnames-new $pathnames
    #sed -e 's/-g/-g -check=stack\,uninit -check-pointers=rw -check-pointers-dangling=all -fstack-security-check/' $pathnames > $pathnames-new && mv $pathnames-new $pathnames
endif

cd $executable:h:h/$lib_name
$mkmf_lib -p $lib_name.a -c "$cppDefs -DCOUPLING_WITH_FMS -DUSE_FMSCLOCK -DPERMUTE"  -o "-I$executable:h:h/lib_FMS -I$code_dir/land_atlantes/$LPJSRC/include" $pathnames $lib_include_dirs
if( $status ) then
    echo "mkmf failed to create $lib_name/Makefile"
    rm $pathnames
    exit 1
endif
rm $pathnames
make

if( $status ) then
    echo "Make failed to create $lib_name.a"
    exit 1
endif
