LIBSNDFILEDIR = $(realpath ../../libsndfile/lib)

CC = gcc
CFLAGS = -g -W -Wall -Werror -Wno-missing-field-initializers

OCAMLC = ocamlc
OCAMLOPT = ocamlopt
OCAMLDEP = ocamldep
OCAMLDOC = ocamldoc

SNDFILE_CFLAGS = $(shell pkg-config --cflags sndfile)
SNDFILE_LIBS = $(shell pkg-config --libs sndfile)

OCAML_BINDIR = $(shell which ocaml)
OCAML_LIBDIR = $(subst bin,lib,$(OCAML_BINDIR))
OCAML_CFLAGS = -I $(OCAML_LIBDIR)

LIBSNDFILE = -ccopt -L$(LIBSNDFILEDIR) -cclib -lsndfile -cclib -lm

all: sndfile.cma sndfile.cmxa

sndfile.cma: sndfile.ml sndfile.cmi sndfile_stub.o
	$(OCAMLC) -c sndfile.ml
	$(OCAMLC) -a -o $@  -custom sndfile_stub.o sndfile.cmo $(LIBSNDFILE)


sndfile.cmxa: sndfile.ml sndfile.cmi sndfile_stub.o
	$(OCAMLOPT) -c sndfile.ml
	$(OCAMLOPT) -a -o $@  sndfile.cmx sndfile_stub.o $(LIBSNDFILE)

Sndfile.html: sndfile.mli sndfile.cmi
	$(OCAMLDOC) -stars -html -colorize-code $<


sndfile_stub.o: sndfile_stub.c
	$(CC) $(CFLAGS) $(SNDFILE_CFLAGS) $(OCAML_CFLAGS) -c $<

sndfile_stub.e: sndfile_stub.c
	$(CC) $(CFLAGS) -E $(SNDFILE_CFLAGS) $(OCAML_CFLAGS) -c $< > $@

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


depend: sndfile.ml sndfile.mli
	$(OCAMLDEP) *.mli *.ml > .depend

.depend: sndfile.ml sndfile.mli
	$(OCAMLDEP) *.mli *.ml > .depend

include .depend

########################################################################

test_sndfile: sndfile.cma test_sndfile.ml
	$(OCAMLC) -o $@ sndfile.cma test_sndfile.ml

test_sndfile.opt: sndfile.cmxa test_sndfile.ml
	$(OCAMLOPT) -o $@ sndfile.cmxa test_sndfile.ml

check : test_sndfile test_sndfile.opt
	./test_sndfile
	./test_sndfile.opt

########################################################################

clean:
	rm -f *~ .*~ *.o *.cm[aiox] *.cmxa *.a *.so test_sndfile test_sndfile.opt
	@ find . -type f -perm +u=x -exec rm -f {} \;
	@ rm -f *.html *.css