CFLAGS=-g -Wall -O
LDLIBS=-lfl
LSOURCES=lex.l
YSOURCES=grammar.y
CSOURCES=main.c list.c salloc.c suffixed.c
HSOURCES=list.h salloc.h suffixed.h ast.h
OBJECTS=$(LSOURCES:.l=.o) $(YSOURCES:.y=.tab.o) $(CSOURCES:.c=.o)
# Add non-source files that need to be included in the submit.tgz here
OTHER_FILES=Makefile

all: translate

translate: $(OBJECTS)
	$(CC) $(CFLAGS) -o $@ $^ $(LDLIBS)

calc: calc.tab.o list.o salloc.o
	$(CC) $(CFLAGS) -o $@ $^

%.o: %.c
	$(CC) -c -MMD -MG -MP -MF $*.d $(CFLAGS) -o $@ $<

%.c: %.l
	flex -o $@ $<

%.tab.c %.tab.h: %.y
	bison --verbose -d $<

ifneq ($(LSOURCES),)
$(LSOURCES:.l=.c): $(YSOURCES:.y=.tab.h)
endif

-include $(OBJECTS:.o=.d)

clean:
	rm -f $(OBJECTS) $(OBJECTS:.o=.d) $(YSOURCES:.y=.tab.c) $(YSOURCES:.y=.tab.h) $(YSOURCES:.y=.output) $(LSOURCES:.l=.c) translate calc.tab.[chdo] calc.output calc documentation2.aux documentation2.log documentation2.pdf submit.tgz highscore.tgz 2>/dev/null

TARFILES_BASE=$(CSOURCES) $(LSOURCES) $(YSOURCES) $(HSOURCES) $(OTHER_FILES)

1: $(TARFILES_BASE) documentation1.pdf
	tar czvf submit.tgz $^ || rm submit.tgz

2: $(TARFILES_BASE) documentation2.pdf
	tar czvf submit.tgz $^ || rm submit.tgz

highscore.tgz: $(TARFILES_BASE)
	tar czf highscore.tgz $^ || rm highscore.tgz

highscore: highscore.tgz
	@echo "NOTE: highscore uploads only work from TU Delft IP addressess"
	@USER=`whoami` ; read -p "NetID [$$USER]: " ALTUSER ; \
	NAME=`finger -l -m $$(whoami) | grep -o 'Name:.*' | sed 's/^Name: //'` ; read -p "Display name [$$NAME]: " ALTNAME ; \
	{ [ -n "$$ALTUSER" ] && USER="$$ALTUSER" ; [ -n "$$ALTNAME" ] && NAME="$$ALTNAME" ; \
	    NAME=`echo "$$NAME" | sed 's/%/%25/g'` ; \
		wget -nv -O- --post-file highscore.tgz "http://dutigw.st.ewi.tudelft.nl/cgi-bin/compiler-construction/direct.cgi?$$USER&$$NAME" 2>&1 | \
		grep -v http ; true ; }

documentation2.pdf: documentation2.tex
	pdflatex $<

.PHONY:all clean documentation1.pdf 1 2 highscore
