OCAMLC = ocamlc
OCAMLOPT = ocamlopt
OCAMLFIND = ocamlfind
CC = gcc

BASE_SRCS = common.ml util.ml bConfig.ml
SRCS = $(BASE_SRCS) bantam_.ml
#BASE_BYTE_OBJS = $(BASE_SRCS:.ml=.cmo)
BASE_BYTE_OBJS = prefs.cmo $(BASE_SRCS:.ml=.cmo)
BYTE_OBJS = $(BASE_BYTE_OBJS) bantam.cmo
#BYTE_OBJS = prefs.cmo $(BASE_BYTE_OBJS) bantam.cmo
#NAT_OBJS = $(BASE_SRCS:.ml=.cmx) bantam.cmx
BASE_NAT_OBJS = prefs.cmx $(BASE_SRCS:.ml=.cmx)
#NAT_OBJS = prefs.cmx $(BASE_SRCS:.ml=.cmx) bantam.cmx
NAT_OBJS = $(BASE_NAT_OBJS) bantam.cmx
DEPS = "unix str lablgtk2 rascl"

NEW_ADD_WATCH = $(shell ./new_add_watch_test.sh)
ifeq ($(strip $(NEW_ADD_WATCH)), true)
	IN_COND = "[\`IN]"
	HUP_COND = "[\`HUP]"
else
	IN_COND = "\`IN"
	HUP_COND = "\`HUP"
endif

RELIEF = $(shell bash -c '\
	version=`ocamlc -version`; \
	major=$${version:0:4}; \
	minor=$${version:5}; \
	if [ $$major = "3.08" ] && [ $$minor ] && [ $$minor -ge 3 ]; then \
		echo "Solid"; \
	else \
		echo "Flat"; \
	fi' )

.PHONY : all byte opt install clean

all : $(DEFAULT_TARGET)

opt : $(NAT_OBJS) usleep.o bantam.sh
	$(OCAMLFIND) $(OCAMLOPT) -package $(DEPS) -predicates init \
	-linkpkg -o bantam.bin usleep.o $(NAT_OBJS)

byte : $(BYTE_OBJS) usleep.o bantam.sh
	$(OCAMLFIND) $(OCAMLC) -package $(DEPS) -predicates init \
	-linkpkg -custom -o bantam.bin usleep.o $(BYTE_OBJS)

bantam.sh : bantam.sh.0 bantam.sh.2
	-rm -f bantam.sh
	cat bantam.sh.0 >> bantam.sh
	echo "    BANTAM_HOME=$(BANTAM_HOME)" >> bantam.sh
	cat bantam.sh.2 >> bantam.sh

usleep.o : usleep.c
	$(CC) -I`ocamlc -where` -c usleep.c

prefs.cmo : prefs.ml 
	$(OCAMLFIND) $(OCAMLC) -package rascl -pp \
	'camlp4o -I `ocamlfind query rascl` pa_extend.cmo q_MLast.cmo \
	pa_rascl.cmo' -c prefs.ml
	cp config.example skeleton/config/prefs
prefs.cmx : prefs.ml 
	$(OCAMLFIND) $(OCAMLOPT) -package rascl -pp \
	'camlp4o -I `ocamlfind query rascl` pa_extend.cmo q_MLast.cmo \
	pa_rascl.cmo' -c prefs.ml
	cp config.example skeleton/config/prefs

bantam.cmx : bantam.ml
	#$(OCAMLFIND) $(OCAMLOPT) -package $(DEPS) \
	#	-pp "camlp4o pa_ifdef.cmo $(SOLID)" -c $<
	$(OCAMLFIND) $(OCAMLOPT) -package $(DEPS) -c $<
	#-pp "camlp4o pa_macro.cmo" $(NEW_ADD_WATCH) $< 

bantam.cmo : bantam.ml
	#$(OCAMLFIND) $(OCAMLC) -package $(DEPS) \
	#	-pp "camlp4o pa_ifdef.cmo $(SOLID)" -c $<
	$(OCAMLFIND) $(OCAMLC) -package $(DEPS) -c $<
	#-pp "camlp4o pa_macro.cmo" $(NEW_ADD_WATCH) $< 

bantam.ml : bantam_.ml
	sed "s/@IN_COND@/$(IN_COND)/" bantam_.ml \
	| sed "s/@HUP_COND@/$(HUP_COND)/" >bantam.ml

%.cmx : %.ml
	$(OCAMLFIND) $(OCAMLOPT) -package $(DEPS) -c $<

%.cmo : %.ml
	$(OCAMLFIND) $(OCAMLC) -package $(DEPS) -c $<
