include make.config

obj = config.cmo ksi.cmo lexer.cmo gontutil.cmo gontmodule.cmo \
      parser.cmo gontbind.cmo gonttypes.cmo gontcodegen.cmo \
      gontlink.cmo gont.cmo ciface.cmo main.cmo
opt_obj = ${obj:.cmo=.cmx}
target = gontc
OCAMLC = ocamlc -g
OCAMLC_OPT = ocamlopt

CMA_LIBS = unix.cma str.cma

all: make.config $(target) fake-gonttree

lib: make-runtime

world: all lib

cycle: clean world tests

tests:
	$(MAKE) -C t

make-runtime:
	$(MAKE) -C runtime

native: opt

opt: $(target).opt

$(target): $(obj)
	$(OCAMLC) -o $@ $(CMA_LIBS) $(obj)

$(target).opt: $(opt_obj)
	$(OCAMLC_OPT) -o $@ ${CMA_LIBS:.cma=.cmax} $(opt_obj)

.PHONY: tags

tags:
	otags -vi *.ml *.mli

.SECONDARY: parser.ml lexer.ml parser.mli
.PHONY: t

t:
	$(MAKE) -C t

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

%.cmi: %.mli
	$(OCAMLC) -c $<

%.cmx: %.ml
	$(OCAMLC_OPT) -c $<

%.ml: %.mll
	ocamllex $<

%.ml %.mli: %.mly
	ocamlyacc -v $<

# ocamldebug is stupid and needs it
fake-gonttree: gonttree.cmo

gonttree.cmo: gonttree.mli
	cp gonttree.mli gonttree.ml
	$(OCAMLC) -c gonttree.ml
	rm gonttree.ml

config.ml:
	( echo "(* Autogenerated. Location of the runtime. *)"; \
	  echo 'let prefix = "$(PWD)/runtime"'; \
	  echo -n 'let libgc = "'; \
	  test -f /usr/lib/libgc.so || test -f /usr/local/lib/libgc.so && \
	  echo -n '-lgc -ldl'; \
	  echo '";;') > config.ml

deps:
	ocamldep *.ml *.mli > .deps
	
.deps: parser.ml lexer.ml
	ocamldep *.ml *.mli > .deps

include .deps

# Kludge... 

gontutil.cmx: lexer.cmi

clean:
	rm -f *.cmo *.cmi *.o *.cmx core $(target) $(target).opt parser.output
	$(MAKE) -C runtime clean
	$(MAKE) -C t clean
	$(MAKE) -C work clean
	$(MAKE) -C doc clean

nuke: clean
	rm -f parser.ml parser.mli lexer.ml parser.output config.ml 
	rm -f .deps TAGS tags make.config

count:
	wc `ls *.ml *.mli *.mly *.mll | egrep -v '(parser|lexer)\.(ml|mli)$$'`

VER := pre$(shell cat VERSION)
DISTDIR := gont-$(VER)

dist:
	$(MAKE) -C doc all
	rm -rf $(DISTDIR)
	mkdir $(DISTDIR)
	find . ! -name $(DISTDIR) -mindepth 1 -maxdepth 1 | \
		xargs tar cf - | \
		(cd $(DISTDIR) && tar xf -)
	$(MAKE) -C $(DISTDIR) nuke
	rm -rf $(DISTDIR)/doc
	tar cf - doc | (cd $(DISTDIR) && tar xf -)
	find $(DISTDIR) -name CVS -o -name '*.tar.gz' | xargs rm -rf
	$(MAKE) -C $(DISTDIR)/doc clean-aux
	tar cf - $(DISTDIR) | gzip -9nf > $(DISTDIR).tar.gz
	rm -rf $(DISTDIR)

www:
	$(MAKE) -C doc all
	rm -rf www-doc
	mkdir www-doc
	(cd doc && tar cf - .) | (cd www-doc && tar xf -)
	find www-doc -name CVS -o -name '*.tar.gz' | xargs rm -rf
	$(MAKE) -C www-doc clean-aux
	(cd www-doc && tar zcf -) | ssh team 'cd gontwww && tar vzxf -'
	rm -rf www-doc

make.config: make.template Makefile
	CPPFLAGS= ; \
	if test -f /usr/include/gc/gc.h || \
	   test -f /usr/local/include/gc/gc.h ; then \
	     CPPFLAGS=-DGONT_USE_GC ; \
	fi ; \
	sed -e "s/^CPPFLAGS =.*/CPPFLAGS = $$CPPFLAGS/" \
		make.template > make.config
