#!/bin/ksh
# $Id$
##set -vx
############################################################
#
# Purpose :
# This script aims to create create the AA_make file
# in the WORK directory. 
# AA_make contains :
#    - compilation options speccific to NEMO
#    - compilation rules
#    - dependancies
# Running the modipsl/util/ins_make command is needed AFTER
# fait_AA_make.
#
# Method :
# We use temporary files to perform the following steps :
#    1- search all CPP keys in the code
#    2- write compilation rules 
#    3- add compilation options add the beginning of AA_make 
#    4- search and write dependancies
#    5- add some specific rules (links creation in the WORK)
#
############################################################
#-
echo "This script must be run from the ../modipsl/config/CONFIG_NAME directory"
echo ""

#- Save the previous BB_make file before its rebuild
echo "Save the previous BB_make file before its rebuild"
cp scripts/BB_make scripts/BB_make_save

#- Start the BB_make rebuild step
echo "Start the BB_make rebuild step"

cd WORK
pwd

# Test version of echo
stringtest=`echo "\c"`
if [ "$stringtest" ]; then
   echo 'aliasing echo with /bin/echo -e ...'
   alias echo='echo -e'
fi

#-
#- Search CPP keys ---
liste_cle=$(egrep '^# *if[!( &]*def|^# *elif' *.[Fh] *.[Fh]90  2> /dev/null | grep key_ | sed 's/||/\
/' | sed 's/\&\&/\
/' | sed 's/^.*key_/key_/' | sed 's/ *[) ] *$//' | sort -u  )

#-
#- Write main compilation rules ---
cat > tampon <<end

.SUFFIXES: .f90 .F90 .F

# Target
all :	diroce libioipsl key keyverif src_file_list libioserver libagrif \$(IOIPSL_LIB) \$(AGRIF_LIB)
		@echo --------------------------------------------
		time gmake \$(EXEC_BIN) -j \$(NBPRC)
		@echo --------------------------------------------
		@cp SRC_FILE_LIST.temp SRC_FILE_LIST
		@echo OPA model is OK

# Cleaning objects, libraries and executables
clean:
ifeq (\$(AGRIF),use)
		-@(cd OPAFILES; ./efface)
endif
		\$(RM) model.o \$(EXEC_BIN)
		\$(RM) \$(MODDIR)/oce_\$(NEMOLIB)/\$(COMP)/*.mod
		\$(RM) \$(MODEL_LIB)/*.o
		\$(RM) ../../../tmp/tmp_\$(NEMOLIB)/\$(COMP)/* 
		@echo OPA model \(.o .mod libraries and executables are removed\)

# Dependancies
diroce:
		@if [ ! -d ../../../lib/oce_\$(NEMOLIB) ] ; then mkdir ../../../lib/oce_\$(NEMOLIB) ; fi
		@if [ ! -d ../../../tmp/tmp_\$(NEMOLIB) ] ; then mkdir ../../../tmp/tmp_\$(NEMOLIB) ; fi
		@if [ ! -d ../../../lib/oce_\$(NEMOLIB)/\$(COMP) ] ; then mkdir ../../../lib/oce_\$(NEMOLIB)/\$(COMP) ; fi
		@if [ ! -d ../../../tmp/tmp_\$(NEMOLIB)/\$(COMP) ] ; then mkdir ../../../tmp/tmp_\$(NEMOLIB)/\$(COMP) ; fi

\$(EXEC_BIN) :	 \$(MODEL_LIB) agrif2model.o model.o
ifeq (\$(AGRIF),use)
		\$(F_L) \$(L_X) -o \$(EXEC_BIN) model.o agrif2model.o \$(MODEL_LIB)/*.o \$(OASISMPI2_LIB) \$(IOIPSL_LIB) \$(AGRIF_LIB) \$(NCDF_LIB) \$(USER_LIB) \$(LIBMPI) \$(LIBMP)
else
		\$(F_L) \$(L_X) -o \$(EXEC_BIN) model.o \$(MODEL_LIB)/*.o \$(OASISMPI2_LIB) \$(IOIPSL_LIB) \$(NCDF_LIB) \$(USER_LIB) \$(LIBMPI) \$(LIBMP)
endif

# ioserver library
libioserver :
ifeq (\$(IOSERVER),use)
ifeq (\$(FCM),use)
	(cd ../../../modeles/XMLF90; ./configure -arch \$(FCM_ARCH); fcm build; mkdir -p ../../lib/libxmlio_server  ; cd ../../lib/libxmlio_server ; ln -sf ../../modeles/XMLF90/lib/*.a .; ln -sf ../../modeles/XMLF90/inc/*.mod .)
	(cd ../../../modeles/XMLIO_SERVER; ./configure -arch \$(FCM_ARCH); fcm build ; cd ../../lib/libxmlio_server ; ln -sf ../../modeles/XMLIO_SERVER/lib/*.a . ; ln -sf ../../modeles/XMLIO_SERVER/inc/* . ; cd ../../bin ; ln -sf ../modeles/XMLIO_SERVER/bin/server.exe ioserver)
else
	(cd ../../../modeles/XMLF90/external ; \$(M_K) -f Makefile )
	(cd ../../../modeles/XMLIO_SERVER/external ; \$(M_K) -f Makefile P_P="\$(IOSERVER_MPI)" )
endif
endif

# Agrif library and conv
libagrif : firstagrif mpiagrif
ifeq (\$(AGRIF),use)
	@( if [ ! -d OPAFILES ]; then mkdir OPAFILES; fi )
	@( if [ ! -d OPAFILES/AGRIF_INC ]; then mkdir OPAFILES/AGRIF_INC ; fi )
	@( if [ ! -d OPAFILES/AGRIF_MODELFILES ]; then mkdir OPAFILES/AGRIF_MODELFILES ; fi )
	@(cd ../../../modeles/AGRIF ; \$(M_K) -f Makefile P_P="\$(AGRIF_MPI)" )
	@cp -rf ../../../modeles/AGRIF/agrif_opa.in OPAFILES/. 
	@cp -rf ../../../modeles/AGRIF/conv OPAFILES/. 
	@cp -rf ../../../modeles/AGRIF/efface OPAFILES/. 
endif

# Agrif interface with NEMO
agrif2model.o :
ifeq (\$(AGRIF),use)
	@\$(P_C) \$(P_O) -IOPAFILES/AGRIF_INC \$*.F90 > OPAFILES/\$*.F90 
	@\$(F_C) \\
#-Q- aix6		-qsuffix=f=F90 \\
#-Q- babel		-qsuffix=f=F90 \\
#-Q- osxxlf		-qsuffix=f=F90 \\
	\$(P_P) \$(F_O) \\
#-Q- fjvpp		-Z \$*.L \\
#-Q- sx8mercure		-R2 \\
#-Q- sx8brodie		-R2 \\
#-Q- sxdkrz		-R2 \\
#-Q- eshpux		-R2 \\
#-Q- aix6		-qsource \\
#-Q- babel		-qsource \\
	   OPAFILES/\$*.F90 || { mv \$(PREF).L \$(TMP) ; false ; exit ; }
endif

# IOIPSL library 
libioipsl :
	(cd ../../../modeles/IOIPSL/src ; \$(M_K) -f Makefile )

# Main program
model.o :	\$(MODEL_LIB) model.f90
		@\$(F_C) \$(F_O) -c model.f90

# if the make script is stopped, one doesn't destroy library
.PRECIOUS : \$(MODEL_LIB)
#-Q- sxdkrz .PRECIOUS : \$(SXMODEL_LIB)
#-Q- eshpux .PRECIOUS : \$(SXMODEL_LIB)

# library dependancies
\$(MODEL_LIB):	\$(LIB_OBJ)
		@echo
		@echo The library is up-to-date
		@echo

# Default rules
.DEFAULTS:

# rules for the .f90 files
\$(MODEL_LIB)/%.o : %.f90           
		@\$(F_C) \$(P_P) \$(F_O) \\
#-Q- fjvpp		-Z \$*.L \\
#-Q- sx8mercure		-R2 \\
#-Q- sx8brodie		-R2 \\
#-Q- sxdkrz		-R2 \\
#-Q- eshpux		-R2 \\
#-Q- aix6		-qsource \\
#-Q- babel		-qsource \\
		\$*.f90 || { if [ -f \$(PREF)\$*.L ] ; then mv \$(PREF)\$*.L \$(TMP) ; fi ; false ; exit ; }
		@mv \$*.o \$(MODEL_LIB)/.
		@\$(RM) \$*.[f]
		@if [ -f \$*.mod ] ; then mv \$*.mod \$(MODDIR)/oce_\$(NEMOLIB)/\$(COMP) ; fi
#-Q- aix6		@mv \$(PREF)\$*.lst \$(PREF)\$*.L
#-Q- babel		@mv \$(PREF)\$*.lst \$(PREF)\$*.L
#-Q- linux		@mv \$(PREF)\$*.lst \$(PREF)\$*.L
#-Q- osxxlf		@mv \$(PREF)\$*.lst \$(PREF)\$*.L
		@if [ -f \$(PREF)\$*.L ] ; then mv \$(PREF)\$*.L \$(TMP) ; fi

# rules for the .F90 files
\$(MODEL_LIB)/%.o : %.F90           
ifeq (\$(AGRIF),use) 
		@\$(P_C) \$(P_O) -IOPAFILES/AGRIF_INC \$*.F90 > OPAFILES/\$*.F90 
		@(cd OPAFILES ; ./conv agrif_opa.in -rm \\
#-Q- linux		-SubloopScalar \\
#-Q- g95			-SubloopScalar \\
#-Q- f95			-SubloopScalar \\
#-Q- osf1			-SubloopScalar \\
		-comdirin ./ -comdirout AGRIF_MODELFILES/. -convfile \$*.F90)
		-@mv -f OPAFILES/AGRIF_MODELFILES/\$*.F90 OPAFILES/\$*.F90
		@\$(P_C) \$(P_O) -IOPAFILES/AGRIF_INC OPAFILES/\$*.F90 > OPAFILES/AGRIF_MODELFILES/\$*.F90
		-@mv -f OPAFILES/AGRIF_MODELFILES/\$*.F90 OPAFILES/\$*.F90
		@\$(F_C) \$(P_P) \$(F_O) \\
#-Q- fjvpp		-Z \$*.L \\
#-Q- sx8mercure		-R2 \\
#-Q- sx8brodie		-R2 \\
#-Q- sxdkrz		-R2 \\
#-Q- eshpux		-R2 \\
#-Q- aix6		-qsource \\
#-Q- babel		-qsource \\
		OPAFILES/\$*.F90 || { if [ -f \$(PREF)\$*.L ] ; then mv \$(PREF)\$*.L \$(TMP) ; fi ; false ; exit ; } 
else
		@\$(F_C) \$(P_P) \$(F_O) \\
#-Q- fjvpp		-Z \$*.L \\
#-Q- sx8mercure		-R2 \\
#-Q- sx8brodie		-R2 \\
#-Q- sxdkrz		-R2 \\
#-Q- eshpux		-R2 \\
#-Q- aix6		-qsource \\
#-Q- babel		-qsource \\
		\$*.F90 || { if [ -f \$(PREF)\$*.L ] ; then mv \$(PREF)\$*.L \$(TMP) ; fi ; false ; exit ; }
endif
		@mv \$*.o \$(MODEL_LIB)/.
		@\$(RM) \$*.[f]
		@if [ -f \$*.mod ] ; then mv \$*.mod \$(MODDIR)/oce_\$(NEMOLIB)/\$(COMP) ; fi
#-Q- aix6		@mv \$(PREF)\$*.lst \$(PREF)\$*.L
#-Q- babel		@mv \$(PREF)\$*.lst \$(PREF)\$*.L
#-Q- linux		@mv \$(PREF)\$*.lst \$(PREF)\$*.L
#-Q- osxxlf		@mv \$(PREF)\$*.lst \$(PREF)\$*.L
		@if [ -f \$(PREF)\$*.L ] ; then mv \$(PREF)\$*.L \$(TMP) ; fi

end
#-
#- Compilation options ---
exec 1> AA_make
MAIN="model"
echo '# some variables'
echo 'TMP = ../../../tmp/tmp_$(NEMOLIB)/$(COMP)'
echo ''
echo '#WARNING : NEMO does NOT support fortran 95 signed zero behaviour when using intrinsec SIGN function'
echo '#          This doesnt happen whith Fortran 90 compilers but'
echo '#          Check your compilers option in consequence when using real F95 compilers'
echo ''
echo '#-Q- platine # Compiler options NEMO (CCRT Itanium Bull) '
echo '#-Q- platine F_O = -O3 -i4 -r8 -module $(MODEL_LIB) -I $(MODDIR) -I$(MODEL_LIB) -I$(NCDF_INC) $(USER_INC) '
echo '#-Q- platine L_X = $(L_O) '
echo '#-Q- sx8mercure  # Compiler options NEMO (CEA SX8-NEC) '
echo '#-Q- sx8mercure  F_O = -f2003 nocbind -size_t64 -dw -Wf\"-A dbl4\" -sx8 -C vopt -Wf"-P nh" -Wf',-pvctl noassume loopcnt=10000 shape=10000000 -L transform' -I $(MODDIR) -I $(MODEL_LIB) -I $(NCDF_INC) $(USER_INC)'
echo '#-Q- sx8mercure  L_X = $(L_O)'
echo '#-Q- sx8brodie  # Compiler options NEMO (IDRIS SX8-NEC) '
echo '#-Q- sx8brodie  F_O = -f2003 nocbind -dw -Wf\"-A idbl4\" -sx8 -C vopt -Wf"-init stack=nan" -Wl"-f nan" -Wf"-P nh -O overlap" -Wf,-pvctl noassume loopcnt=10000 -L transform -I $(MODDIR) -I $(MODEL_LIB) -I $(NCDF_INC) $(USER_INC)'
echo '#-Q- sx8brodie  L_X = $(L_O)'
echo '#-Q- sxdkrz  # Compiler options for NEMO (DKRZ SX6-NEC) '
echo '#-Q- sxdkrz  F_O =  -f2003 nocbind -ew -sx6 -ftrace -C vopt -Wf"-init stack=nan" -Wl"-f nan" -Wf"-P nh -O overlap" -Wf"-pvctl noassume loopcnt=10000" -L transform -I $(MODDIR) -I $(MODEL_LIB) -I $(NCDF_INC) $(USER_INC)'
echo '#-Q- sxdkrz  L_X = $(L_O) -ftrace'
echo '#-Q- eshpux  # Compiler options for NEMO (Earth Simulator)'
echo '#-Q- eshpux  # for super perfs!'
echo '#-Q- eshpux  # F_O = -f2003 nocbind $(FTRACE) -pi nest=5 line=10000 expin=Fmpplib.F -Wf,-A idbl4 -C hopt -Wf"-P nh -O overlap" -Wf,-pvctl noassume loopcnt=10000 -L transform -I $(MODDIR) -I $(MODEL_LIB) -I $(NCDF_INC) $(USER_INC)'
echo '#-Q- eshpux  # regular options!'
echo '#-Q- eshpux  F_O = -f2003 nocbind $(FTRACE) -Wf,-A idbl4 -C vopt -P stack -Wf"-P nh -O overlap" -Wf,-pvctl noassume loopcnt=10000 -L transform -Wf,-pvctl nomsg -Wf"-O nomsg" -I $(MODDIR) -I $(MODEL_LIB) -I $(NCDF_INC) $(USER_INC)'
echo '#-Q- eshpux  L_X = $(L_O)'
echo '#-Q- linux  # Compiler options for NEMO (pgf version)'
echo '#-Q- linux  F_O = -Mlist -O3 -byteswapio -r8  -I $(MODDIR) -I$(MODEL_LIB) -I $(NCDF_INC) $(USER_INC)'
echo '#-Q- linux  L_X = -r8 -O3'
echo '#-Q- lxiv7  # Compiler options for NEMO (ifc version)'
echo '#-Q- lxiv7  F_O = -O3 -r8  -I $(MODDIR) -I$(MODEL_LIB) -I $(NCDF_INC) $(USER_INC)'
echo '#-Q- lxiv7  L_X = -r8 -O3'
echo '#-Q- lxiv8  # Compiler options for NEMO (ifort version)'
echo '#-Q- lxiv8  F_O = -O3 -r8  -I $(MODDIR) -I$(MODEL_LIB) -I $(NCDF_INC) $(USER_INC)'
echo '#-Q- lxiv8  L_X = -r8 -O3'
echo '#-Q- g95  # Compiler options for NEMO (g95 version)'
echo '#-Q- g95  F_O = -O3 -fno-second-underscore -r8 -funroll-all-loops -I $(MODDIR) -I $(MODEL_LIB) -I $(NCDF_INC) $(USER_INC)'
echo '#-Q- g95  L_X = -r8 -O3'
echo '#-Q- gfortran  # Compiler options for NEMO (gfortran version)'
echo '#-Q- gfortran  F_O = -fno-second-underscore -fdefault-real-8 -funroll-all-loops -I $(MODDIR) -I $(MODEL_LIB) -I $(NCDF_INC) $(USER_INC)'
echo '#-Q- gfortran  L_X = -fdefault-real-8'
echo '#-Q- aix6  # Compiler options for NEMO (aix6 version)'
echo '#-Q- aix6  F_O = -O3 -qsave -qrealsize=8 -qsuffix=f=f90 -qsuffix=cpp=F90 -qextname -qsource -q64 -qlargepage -qmaxmem=-1 -I $(MODDIR) -I $(MODEL_LIB) -I $(NCDF_INC) $(USER_INC)' 
echo '#-Q- aix6  L_O = $(F_P) -q64 -O3'
echo '#-Q- aix6  L_X = $(L_O)'
echo '#-Q- babel  # Compiler options for NEMO (blue gene version)'
echo '#-Q- babel  F_O =  -O3 -qsave -qrealsize=8 -qsuffix=f=f90 -qsuffix=cpp=F90 -qsource -qextname=flush -qlargepage -qmaxmem=-1 -I $(MODDIR) -I $(MODEL_LIB) -I $(NCDF_INC) $(USER_INC)'
echo '#-Q- babel  L_X = $(L_O)'
echo '#-Q- osxxlf    # Compiler options for NEMO (osxxlf version)'
echo '#-Q- osxxlf    F_O = -O3 -qsave -qrealsize=8 -qsuffix=f=f90 -qsuffix=cpp=F90 -qsource -qextname -qstrict -qmaxmem=-1 -I $(MODDIR) -I $(MODEL_LIB) -I $(NCDF_INC) $(USER_INC)' 
echo '#-Q- osxxlf    L_X = -qrealsize=8 -O3'

echo 'PREF='
echo '#-Q- sx8mercure	PREF=i.'
echo '#-Q- sx8brodie	PREF=i.'
echo '#-Q- sxdkrz	PREF=i.'
echo '#-Q- eshpux	PREF=i.'
echo ''
echo '#Run type: mon, mpi or omp '
echo 'ifeq ($(COMP),mon)'
echo '#-Q- osxxlf  override F_C = xlf90 -c'
echo '#-Q- osxxlf  override F_L = xlf90'
echo 'endif'
echo ''
echo 'ifeq ($(COMP),memo)'
echo '#-Q- sx8brodie  F_O := $(F_O) -P static'
echo '#-Q- osxxlf     F_O := $(F_O) -qnosave'
echo 'endif'
echo ''
echo 'ifeq ($(COMP),mpi)'
echo 'P_P := $(P_P) key_mpp_mpi'
echo '#-Q- osxxlf  override F_C = mpif90 -c'
echo '#-Q- osxxlf  override F_L = mpif90'
echo 'endif'
echo ''
echo 'ifeq ($(COMP),omp)'
echo 'P_P := $(P_P) key_mpp_omp'
echo '#-Q- sx8brodie F_O := $(F_O) -P auto'
echo '#-Q- sx8brodie override F_F = $(F_O) '
echo '#-Q- sx8brodie L_X := $(L_X) -P auto'
echo 'endif'
echo ''
echo 'ifeq ($(USE_IOMPUT),true)'
echo 'P_P := $(P_P) key_iomput'
echo 'endif'
echo ''
echo '# add suffix to P_P'
echo 'P_P := $(P_P:%=$(prefix)%)'
echo ''
echo '# Some tests to define variables related to Agrif compilation'
echo '# Please do not change '
echo 'ifneq (,$(findstring key_agrif,$(P_P)))'
echo 'AGRIF=use'
echo 'else'
echo 'AGRIF=notuse'
echo 'AGRIF_LIB='
echo 'endif'
echo 'ifneq (,$(findstring key_mpp_mpi,$(P_P)))'
echo 'AGRIF_MPI=-DAGRIF_MPI'
echo 'else'
echo 'AGRIF_MPI='
echo 'endif'
echo ''
echo '# Some tests to define variables related to xmlioserver compilation'
echo '# Please do not change '
echo 'ifneq (,$(findstring key_iomput,$(P_P)))'
echo 'IOSERVER=use'
echo 'override USER_LIB += -L../../../lib/libxmlio_server -lioserver -lxmlio -lxmlf90'
echo 'override USER_INC += -I../../../lib/libxmlio_server'
echo 'ifneq (,$(findstring key_mpp_mpi,$(P_P)))'
echo 'IOSERVER_MPI='
echo 'else'
echo 'IOSERVER_MPI=-DNO_MPI'
echo 'endif'
echo 'else'
echo 'IOSERVER=notuse'
echo 'endif'
echo ''

echo '# A variables related to xmlioserver compilationi (fcm or AA_make)'
echo '# Please do not change '
echo 'override FCM += notuse'

 echo ''
# Write the cpp key list with one key by line
echo 'KEY_LIST = \c'
for i in ${liste_cle}
do
 echo "\\"
 echo "     $i \c"
done

echo ''
echo '# .o file list in the library'
echo 'LIB_OBJ = \c'
#
# find all .f90 in the current directory
# build object files list  LIB_OBJ
# one dependancy by line

for i in `ls *.f90  `
do
  bn=`basename $i .f90`
  if [ "${bn}" != "${MAIN}" ] 
  then 
  if [ "${bn}" != "agrif2model" ] 
  then 
    echo "\\"
    echo "		\$(MODEL_LIB)/$bn.o\c"
  fi
  fi
done

# find all .F90 in the current directory
# build object files list  LIB_OBJ
# one dependancy by line

for i in `ls *.F90  `
do
  bn=`basename $i .F90`
  if [ "${bn}" != "${MAIN}" ] 
  then 
  if [ "${bn}" != "agrif2model" ] 
  then 
    echo "\\"
    echo "		\$(MODEL_LIB)/$bn.o\c"
  fi
  fi
done

echo ""

cat tampon
rm tampon
#-
#- Write all dependancies ---

for fic in `ls *.f90 *.F90  *.F 2> /dev/null `
do
    if [ "${fic}" != "agrif2model.F90" ]
    then
    if [ "${fic}" != "${MAIN}.[Ff]" ]
    then
	i=0
	j=0
	dep=""
	inc=""
	inc2=""
	inc3=""
	luse0=""
	luse1=""
	luse2=""
	luse3=""
	key=""
#- search include files (old ice model form, should it be suppressed ?)
	for inc in `sed -n 's/^[  	]*[iI][nN][cC][lL][uU][dD][eE][ 	]*\(['\''"]\)\([^'\''"]*\)\1.*/\2/p' $fic | sort -u`
	do
	    dep="$dep\n$inc"
	done

#- take into account CPP dependancies  keys only (par_trc_trp example)
	for key in `sed -n 's/^#[       eElL]*[iF][fF][         ]*[dD][eE][fF][iI][nN][eE][dD][         ]*//p' $fic | sort -u`
	do
	    j=1
	done

#- search include files on 3 levels
	for inc in `sed -n 's/^#[ 	]*[iI][nN][cC][lL][uU][dD][eE][ 	]*\(['\''"]\)\([^'\''"]*\)\1.*/\2/p' $fic | sort -u`
	do
	    j=1
	    dep="$dep\n$inc"
		for inc2 in `sed -n 's/^#[ 	]*[iI][nN][cC][lL][uU][dD][eE][ 	]*\(['\''"]\)\([^'\''"]*\)\1.*/\2/p' $inc | sort -u`
		do
		    dep="$dep\n$inc2"
		    #- search include  in include (third level !!!)
		    for inc3 in `sed -n 's/^#[  	]*[iI][nN][cC][lL][uU][dD][eE][ 	]*\(['\''"]\)\([^'\''"]*\)\1.*/\2/p' $inc2 | sort -u`
		    do
			dep="$dep\n$inc3"
		    done
		done
	done

#- search USE in include files
	for inc in `sed -n 's/^#[ 	]*[iI][nN][cC][lL][uU][dD][eE][ 	]*\(['\''"]\)\([^'\''"]*\)\1.*/\2/p' $fic | sort -u`
	do
		for fuse0 in `sed -n 's/^[ 	]*[uU][sS][eE] [ 	]*\([^!,;]*\).*/\1/p' $inc | sort -u`
		do
                    [ -f $fuse0.[hfF]90 ] || continue
		    lfuse0=$fuse0.f90
		    [ -f $fuse0.F90 ] && lfuse0=$fuse0.F90
		    luse0="$luse0\n$lfuse0\n\$(MODEL_LIB)/$fuse0.o"
		done

#- search USE in  files included in included files and add to luse0

		for inc2 in `sed -n 's/^#[ 	]*[iI][nN][cC][lL][uU][dD][eE][ 	]*\(['\''"]\)\([^'\''"]*\)\1.*/\2/p' $inc | sort -u`
		do
		    for fuse0 in `sed -n 's/^[ 	]*[uU][sS][eE] [ 	]*\([^!,;]*\).*/\1/p' $inc2 | sort -u`
		    do
                        [ -f $fuse0.[hfF]90 ] || continue
		        lfuse0=$fuse0.f90
		        [ -f $fuse0.F90 ] && lfuse0=$fuse0.F90
		        luse0="$luse0\n$lfuse0\n\$(MODEL_LIB)/$fuse0.o"
		    done
  	        done
	done

#- search USE (and USE of USE and so on three levels)
	for fuse1 in `sed -n 's/^[ 	]*[uU][sS][eE] [ 	]*\([^!,;]*\).*/\1/p' $fic | sort -u`
	do
            [ -f $fuse1.[hfF]90 ] || continue
	    lfuse1=$fuse1.f90
	    [ -f $fuse1.F90 ] && lfuse1=$fuse1.F90
	    luse1="$luse1\n$lfuse1\n\$(MODEL_LIB)/$fuse1.o"
		for fuse2 in `sed -n 's/^[ 	]*[uU][sS][eE] [ 	]*\([^!,;]*\).*/\1/p' $lfuse1 | sort -u`
		do
                    [ -f $fuse2.[hfF]90 ] || continue
		    lfuse2=$fuse2.f90
		    [ -f $fuse2.F90 ] && lfuse2=$fuse2.F90
		    luse2="$luse2\n$lfuse2\n\$(MODEL_LIB)/$fuse2.o"
		    # on cherche les USE  dans le fichier deja USE (3eme niveau! balaise!)
		    for fuse3 in `sed -n 's/^#[  	]*[uU][sS][eE] [ 	]*\([^!,;]*\).*/\1/p' $lfuse2 | sort -u`
		    do
                        [ -f $fuse3.[hfF]90 ] || continue
			luse3="$luse3\n$lfuse3\n\$(MODEL_LIB)($fuse3.o)"
                    done
		done
	done
#-
#-  dep contains all dependancies 
	echo "\$(MODEL_LIB)/`echo $fic|awk -F. '{print $1}'`.o :       \c"
	for depele in `echo $luse3 | sort -u` `echo $luse2 | sort -u` `echo $luse1 | sort -u` `echo $luse0 | sort -u` `echo $dep | sort -u`
	do
	    echo "\\"
 	    echo "	$depele \c"
 	    let i=i+1 # pour signaler le premier
	done

#-
#- add dependancies with IOIPSL library (if source files contains IOIPSL)
        grep -i 'use *ioipsl' ${fic} >/dev/null && ( echo "\\" ; echo "	\$(IOIPSL_LIB) \c")

#-
#- add dependancies with IOIPSL library (if source files contains Agrif_*)
        grep -i 'use Agrif_*' ${fic} >/dev/null && ( echo "\\" ; echo "	\$(AGRIF_LIB) \c")

#-
#- add dependancies with KEY_CPP (if source file includes cpp  keys)
	if [ ${j} != "0" ] 
        then 
	  echo "\\"
	  echo "	KEY_CPP \c" 
	fi
#-
#- end with the file itself
	     echo "\\"
       	     echo "	$fic"
    fi
    fi
echo $fic done >/dev/tty
done
#-
#- Write some special rules ---
echo '# agrif previous use'
echo "firstagrif:"
echo "ifeq (\$(AGRIF),use)"
echo '	@if [ -z "`cat KEY_CPP | grep key_agrif`" ]; then $(RM) model.o $(MODDIR)/oce_$(NEMOLIB)/$(COMP)/*.mod $(SXMODEL_LIB); fi'
echo "else"
echo '	@if [ -n "`cat KEY_CPP | grep key_agrif`" ]; then $(RM) -r OPAFILES model.o $(MODDIR)/oce_$(NEMOLIB)/$(COMP)/*.mod $(SXMODEL_LIB); fi'
echo "endif"
#-
echo '#- RB : this rule is a pretty miserable trick to be able to re-compile NEMP-AGRIF-mono after NEMO-AGRIF-mpp'
echo '#- I guess the good correction should be in AGRIF/LIB/toamr.c for the conv, to remove useless allocation declarations in AGRIF_INC'
echo '# recompile all in this case' 
echo "mpiagrif:"
echo "ifeq (\$(AGRIF),use)"
echo "ifeq (,\$(AGRIF_MPI))"
echo '	@if [ -n "`cat KEY_CPP | grep key_mpp_mpi`" ]; then $(RM) -r OPAFILES model.o $(MODDIR)/oce_$(NEMOLIB)/$(COMP)/*.mod $(SXMODEL_LIB); fi'
echo "endif"
echo "endif"
#-
echo '# key changing control'
echo "key: "
echo "	@echo CHANGE of CPP KEYS yes/no ?"
echo "	-@if [ \"\`cat KEY_CPP\`\" != \"\$(P_P:\$(prefix)%=%)\" ] ; then \\"
echo "		echo CPP options changed ; echo \"\$(P_P:\$(prefix)%=%)\" > KEY_CPP ; fi "
#-
echo '# check key values'
echo "keyverif:"
echo '	@echo CHECKING KEY'
echo '	@echo KEY USED : '
echo '	@for v in ` echo $(P_P:$(prefix)%=%) ` ; \'
echo '	do \'
echo '	echo $$v ;\'
echo '        w=`echo $$v | cut -c1-3` ; \'
echo '        if [ $$w = `echo "key"` ] ; then \'
echo '        r=n ; \'
echo '        echo " $(KEY_LIST) " | (grep $$v >/dev/null 2>&1) || r=o ; \'
echo '           if [ $$r != "n" ] ; then \'
echo '              echo "UNKNOWN KEY" ;\'
echo '              false ;  \'
echo '              exit ;  \'
echo '           fi \'
echo '        fi \'
echo '	done'
echo '# Checking the number of routines'
echo "src_file_list: EMPTY"
echo '	@echo CHECKING THE NUMBER AND NAMES OF SOURCE FILES '
echo '	@$(RM) `ls | fgrep -v -f .patron` '
echo '	@check=`grep OPA_SRC .config`              ; \'
echo '	if [ -n "$$check" ] ; then                   \'
echo '	echo "   use OPA_SRC files"                ; \'
echo '	    ln -sf ../../../modeles/NEMO/OPA_SRC/*.[Ffh]90          . ; \'
echo '	    ln -sf ../../../modeles/NEMO/OPA_SRC/*/*.[Ffh]90      . ; \'
echo '  fi '
echo '	@check=`grep LIM_SRC_2 .config`              ; \'
echo '	if [ -n "$$check" ] ; then                   \'
echo '	echo "   use LIM_SRC_2 files"                ; \'
echo '      ln -sf ../../../modeles/NEMO/LIM_SRC_2/*.[Ffh]90          . ; \'
echo '  fi '
echo '	@check=`grep LIM_SRC_3 .config`              ; \'
echo '	if [ -n "$$check" ] ; then                   \'
echo '	echo "   use LIM_SRC_3 files"                ; \'
echo '      ln -sf ../../../modeles/NEMO/LIM_SRC_3/*.[Ffh]90          . ; \'
echo '  fi '
echo '	@check=`grep NST_SRC .config`              ; \'
echo '	if [ -n "$$check" ] ; then                   \'
echo '	echo "   use NST_SRC files"                ; \'
echo '      \$(RM) agrif_opa_interp.F90           ; \'
echo '      \$(RM) agrif_opa_sponge.F90           ; \'
echo '      \$(RM) agrif_opa_update.F90           ; \'
echo '      \$(RM) agrif_top_interp.F90           ; \'
echo '      \$(RM) agrif_top_sponge.F90           ; \'
echo '      \$(RM) agrif_top_update.F90           ; \'
echo '      ln -sf ../../../modeles/NEMO/NST_SRC/*.[Ffh]90      .     ; \'
echo '  fi '
echo '	@check=`grep C1D_SRC .config`              ; \'
echo '	if [ -n "$$check" ] ; then                   \'
echo '	echo "   use C1D_SRC files"                ; \'
echo '      ln -sf ../../../modeles/NEMO/C1D_SRC/*.[Ffh]90          . ; \'
echo '  fi '
echo '	@check=`grep TOP_SRC .config`              ; \'
echo '	if [ -n "$$check" ] ; then  \'
echo '	echo "   use TOP_SRC files"                ; \'
echo '      \$(RM) trcstp.F90                      ; \'
echo '      \$(RM) sms.F90                         ; \'
echo '      \$(RM) trcini.F90                      ; \'
echo '      ln -sf ../../../modeles/NEMO/TOP_SRC/*.[Ffh]90          . ; \'
echo '      ln -sf ../../../modeles/NEMO/TOP_SRC/*/*.[Ffh]90      . ; \'
echo '  fi '
echo '	@check=`grep OFF_SRC .config`              ; \'
echo '	if [ -n "$$check" ] ; then                   \'
echo '	echo "   use OFF_SRC files"                ; \'
echo '      ln -sf ../../../modeles/NEMO/OFF_SRC/*.[Ffh]90          . ; \'
echo '      ln -sf ../../../modeles/NEMO/OFF_SRC/*/*.[Ffh]90        . ; \'
echo '  fi '
echo ' '
echo '	@mn=`awk '"'"'{ print $$1 }'"'"' .config `  ; \'
echo '  myrep=../../../config/$$mn/MY_SRC ; \'
echo '  echo "*** Dealing with my modified source code, located in" $$myrep ; \'
echo '  for i in `ls $$myrep` ; do \'
echo '    [ -f $$i ] && \$(RM) $$i ;\'
echo '  done ; \'
echo '  myrep_list=`(cd $$myrep ; ls *.[Ffh]90 *.[Ffh] *.mk)` ; \'
echo '  if [ -n "$$myrep_list" ] ; then \'
echo '      for F in $$myrep_list; do \'
echo '         echo "---> Reconstruct link to MY_SRC/$$F" ; \'
echo '         ln -sf  $$myrep/$$F . ; \'
echo '      done ; \'
echo '  fi '
echo ' '
echo '	@\$(RM) tmplist'
echo '	@ls -1 | fgrep -v -f .patron >tmplist'
echo '	@cmp tmplist SRC_FILE_LIST.temp || { echo some routines have been added or suppressed ; \'
echo '	sdiff -s tmplist SRC_FILE_LIST.temp ; cp tmplist SRC_FILE_LIST.temp ; \'
echo '	\$(RM) model.o \$(MODEL_LIB)/*.o  \$(EXEC_BIN) ; \'
echo '	echo "Rebuilding the AA_make files" ; \'
echo '	cd ..  ; ../NVTK/fait_AA_make ; echo " " ; \'
echo '	echo "THE ins_make COMMAND in modipsl/util MUST BE RERUN PLEASE DO SO BEFORE gmake" ; \'
echo '	echo "========================================== " ; \'
echo '	../../util/ins_make -w \$(NEMOLIB) ; echo " " ;  false ; exit ; }'
echo "EMPTY: "
exec > /dev/null

