opt		=	-O2 -D_FILE_OFFSET_BITS=64
static		=	-static

xml		=
ifeq ($(xml),)
xml_h		=
xml_dir		=
else
ifeq ($(xml),.)
xml_h		=	-I.
xml_dir		=	-L.
else
xml_h		=	-I$(xml)/include
xml_dir		=	-L$(xml)/lib
endif
endif
xml_lib		=	$(xml_dir) -lexpat # -lxmltok -lxmlparse

root_fe		=	$(shell awk 'BEGIN {n=0} /^ *\#define (USE_ROOT_FE|OUTHIST)/ {n=1} END {print n}' reader.h outhist.h)
ifeq ($(root_fe),1)
root_h		=	$(shell root-config --cflags)
root_lib	=	$(shell root-config --glibs)
endif

gsl_fe		=	$(shell awk 'BEGIN {n=0} /^ *\#define RECONSTRUCT/ {n++} END {print n}' reader.h)
ifeq ($(gsl_fe),1)
ifdef I3_PORTS
gsl		=	$(I3_PORTS)
gsl_h		=	-I$(gsl)/include/gsl-1.8
gsl_lib		=	-L$(gsl)/lib/gsl-1.8 -lgsl -lgslcblas
else
gsl		=	/usr/local
gsl_h		=	-I$(gsl)/include/gsl
gsl_lib		=	-L$(gsl)/lib -lgsl -lgslcblas
endif
gsl_c		=	interpol.cxx llhreco.cxx
endif

i3m_fe		=	$(shell awk 'BEGIN {n=0} /^ *\#define I3HELPER/ {n++} END {print n}' reader.h)
ifeq ($(i3m_fe),1)
i3m_lib		=	-L. -li3helper $(shell ln -sf i3helper/public/i3helper/i3helper.h)
endif

rdmc_fe		=	$(shell awk 'BEGIN {n=0} /^ *\#define RECOF2KMC/ {n++} END {print n}' reader.h)
ifeq ($(rdmc_fe),1)
rdmc_h		=	-I.
rdmc_lib	=	-L. -lrdmc
endif

zlib_fe		=	$(shell awk 'BEGIN {n=0} /^ *\#define USEZLIB/ {n++} END {print n}' reader.h)
ifeq ($(zlib_fe),1)
zlib_lib	=	-lz
endif

version		=	$(shell sed -n "2s/^/-D VERSION='\"/p; 5s/^/(/; 5s/$$/)\"'/p" README)
i_all		=	$(xml_h) $(gsl_h) $(rdmc_h) $(root_h) 
l_all		=	$(i3m_lib) $(xml_lib) $(zlib_lib) $(gsl_lib) $(rdmc_lib) $(root_lib)
c_all		=	$(version) tcalfit.cxx $(gsl_c) fat-reader.cxx reader.cxx -o fat-reader $(opt) $(i_all) $(l_all)

all:	static
	strip fat-reader

jj-reader:
	c++ tcalfit.cxx -c $(opt)
	c++ jj-reader.cxx -o jj-reader $(opt) tcalfit.o && strip jj-reader

clean:
	rm *.o *~ jj-reader fat-reader >& /dev/null || true

static:
	c++ $(c_all) $(static)

simple:
	c++ $(c_all)

i3reco:
	sh -c "for i in *.{h,cxx}; do echo \$$i; cat \$$i | sed 's-I3FATreader-I3FRreco-' > foo; mv foo \$$i; done"

expat:
	ln -s $(I3_PORTS)/lib/expat-1.2/libexpat.a
	ln -s $(I3_PORTS)/include/expat-1.2/xmlparse/xmlparse.h expat.h

i3:
	./scripts/i3dirs.sh
	ln -s $(I3_BUILD)/lib/libi3helper.so
	ln -s $(I3_BUILD)/neutrinoflux/resources
