# $Id$

CMI_FILES=$(MODULES:=.cmi)
CMO_FILES=$(MODULES:=.cmo)
CMX_FILES=$(MODULES:=.cmx)
CMA_FILES=$(LIBRARIES:=.cma)
CMXA_FILES=$(LIBRARIES:=.cmxa)
ML_LEX_FILES=$(LEX_MODULES:=.ml)
ML_YACC_FILES=$(YACC_MODULES:=.ml)
MLI_YACC_FILES=$(YACC_MODULES:=.mli)
ML_FILES=$(ML_LEX_FILES) $(ML_YACC_FILES)
O_FILES=$(C_FILES:=.o)
ADD_CMO_FILES=$(ADD_MODULES:=.cmo)
ADD_CMX_FILES=$(ADD_MODULES:=.cmx)

GENERATED_SOURCES=$(ML_LEX_FILES) $(ML_YACC_FILES) $(MLI_YACC_FILES)

CUSTOM_FLAG=`if [ -z "$(C_FILES)" ]; then true; else echo '-custom'; fi`
ADD_CFLAGS+=$(CUSTOM_FLAG)

default: compile run

compile: $(ML_FILES) $(CMO_FILES) $(CMX_FILES) $(MAIN_MODULE).cmo $(MAIN_MODULE).cmx
	@for file in $(C_FILES); do \
	  $(NATIVECC) $(NATIVECCCOMPOPTS) -c -I$(TOPDIR)/byterun $$file.c; \
	done;
	@$(OCAMLC) $(ADD_COMPFLAGS) $(ADD_CFLAGS) -o program.byte $(O_FILES) $(CMA_FILES) $(CMO_FILES) $(ADD_CMO_FILES) $(MAIN_MODULE).cmo
	@$(OCAMLOPT) $(ADD_COMPFLAGS) -o program.native $(O_FILES) $(CMXA_FILES) $(CMX_FILES) $(ADD_CMX_FILES) $(MAIN_MODULE).cmx

run:
	@printf " ... testing with ocamlc"
	@./program.byte $(EXEC_ARGS) > $(MAIN_MODULE).result || (echo " => failed" && exit 1)
	@diff -q $(MAIN_MODULE).reference $(MAIN_MODULE).result > /dev/null || (echo " => failed" && exit 1)
	@printf " ocamlopt"
	@./program.native $(EXEC_ARGS) > $(MAIN_MODULE).result || (echo " => failed" && exit 1)
	@diff -q $(MAIN_MODULE).reference $(MAIN_MODULE).result > /dev/null || (echo " => failed" && exit 1)
	@echo " => passed"

clean: defaultclean
	@rm -f *.result ./program.* $(GENERATED_SOURCES) $(O_FILES)
