# CONFIG (overwritable)
FC := gfortran
# to compile with support for netCDF climate input set to any value
WITH_NETCDF := 1

## debug friendly flags, but enable FFLAGS commandline appending
FASTFFLAGS := -cpp -w -Ofast $(FFLAGS)
override FFLAGS += 	\
	-Wall \
	-cpp -Wall -Og -fbounds-check -fcheck=all -ffpe-trap=invalid -fbacktrace -fdump-core -g \
    -ffree-line-length-none --debug \
	-fall-intrinsics -std=f95
IFORTFFLAGS := -extend_source -ipo -O3 -no-prec-div -fp-model fast=2 -xHost $(FASTFFLAGS)
PROG := swim


# SOURCES AND OBJECTS
F95SRCS = ${wildcard *.f95}
F95SRCS := $(filter-out %/time.f95, $(F95SRCS))
OBJS = ${patsubst %.f95, %.o, $(F95SRCS)}

# $(DEP_FILE) is a .dep file generated by fortdepend
DEP_FILE = Makefile.dep
MAKEDEPEND = fortdepend

ifdef WITH_NETCDF
    NCDF := $(shell nc-config)
    ifndef NCDF
        $(error NetCDF with Fortran support is required)
    endif
    ifeq ("$(shell nc-config --has-fortran)","no")
        $(error Fortran support is required for NetCDF (see nc-config --has-fortran))
    endif
    override FFLAGS += ${shell nc-config --fflags} -Dwith_netcdf
    override LDFLAGS += ${shell nc-config --flibs --libs} -lnetcdff
endif

# TARGETS

default: $(PROG)

fast:
	$(MAKE) FFLAGS="$(FASTFFLAGS)" $(PROG)

cluster:
	$(MAKE) FC=ifort FFLAGS="$(IFORTFFLAGS)" $(PROG)

clean:
	rm -f $(PROG) *.o *.mod


# LINKING
$(PROG): $(OBJS)
	$(FC) $(FFLAGS) $(LDFLAGS) $(OBJS) -o $@

# COMPILATIONS
%.o: %.f95
	$(FC) $(FFLAGS) -c $<

# To autogenerate Makefile.dep with file dependencies
#
# 	$ pip3 install fortdepend
# 	$ fortdepend -f *.f95 -o Makefile.dep
#
$(DEP_FILE): #$(F95SRCS)
	$(MAKEDEPEND) -w -o $(DEP_FILE) -f $(F95SRCS)

include Makefile.dep