CC = gcc
CFLAGS = -g -Wall
GCOVFLAGS = -fprofile-arcs -ftest-coverage
GPROFFLAGS = -pg
LDFLAGS = -L./CUnit -lcunit
CUNITFLAGS =
HEADERS = sort.h
OBJS = sort.o testsort.o

all: FORCE
	@echo "run 'make testsort' to make and run unit tests"
	@echo "run 'make testsort_coverage' to generate code coverage"
	@echo "run 'make filesort' to test for memory leaks"
	@echo "run 'make filesort_gprof' to generate gprof profile"
	@echo "run 'make filesort_callgrind' to generate callgrind profile"

filesort: clean
	$(CC) $(CFLAGS) -o filesort.o -c filesort.c
	$(CC) $(CFLAGS) -o sort.o -c sort.c
	$(CC) $(CFLAGS) -o filesort filesort.o sort.o $(LDFLAGS)
	valgrind --leak-check=full --show-reachable=yes \
		--track-origins=yes ./filesort sortfile.txt

filesort_gprof: clean
	$(CC) $(CFLAGS) $(GPROFFLAGS) -o filesort.o -c filesort.c
	$(CC) $(CFLAGS) $(GPROFFLAGS) -o sort.o -c sort.c
	$(CC) $(CFLAGS) $(GPROFFLAGS) -o filesort_gprof \
		filesort.o sort.o $(LDFLAGS)
	./filesort_gprof sortfile.txt
	@echo "If this gives you an error message about not finding"
	@echo "the 'dot' executable, you might need to run"
	@echo "'sudo yum install graphviz' and then try again"
	gprof -m 0 ./filesort_gprof | ./gprof2dot.py -n0 -e0 | \
		dot -Tpng | display

filesort_callgrind: clean
	$(CC) $(CFLAGS) -o filesort.o -c filesort.c
	$(CC) $(CFLAGS) -o sort.o -c sort.c
	$(CC) $(CFLAGS) -o filesort_callgrind filesort.o sort.o $(LDFLAGS)
	valgrind --tool=callgrind ./filesort_callgrind sortfile.txt
	@echo "If this gives you an error message about not finding"
	@echo "the 'kcachegrind' executable, you might need to run"
	@echo "'sudo yum install kdesdk' and then try again"
	callgrind_annotate callgrind.out.*
	(./gprof2dot.py -f callgrind -n0 -e0 callgrind.out.* | \
		dot -Tpng | display)&
	(kcachegrind)&


testsort_coverage: clean
	$(CC) $(CFLAGS) -o testsort.o -c testsort.c
	$(CC) $(CFLAGS) $(GCOVFLAGS) -o sort.o -c sort.c
	$(CC) -o testsort_coverage $(GCOVFLAGS) testsort.o sort.o $(LDFLAGS)
	./testsort_coverage
	@echo "If you see a 'cannot write to directory' error"
	@echo "it is because the lcov tool fails when it is working"
	@echo "in an sshfs-mounted directory.  Try copying your"
	@echo "exercise directory to ~/Desktop and running it there."
	lcov --directory . --capture --output-file ts.info
	mkdir html
	cd html; genhtml ../ts.info; firefox index.html &

testsort: clean $(OBJS) $(HEADERS)
	$(CC) -o testsort $(OBJS) $(LDFLAGS)
	./testsort

%.o: %.c $(HEADERS)
	$(CC) $(CFLAGS) -c $<

clean: FORCE
	/bin/rm -f *.o *~ testsort testsort_coverage
	/bin/rm -f filesort_gprof filesort_callgrind filesort
	/bin/rm -fr html
	/bin/rm -f *.gcda *.gcno *.info
	/bin/rm -f gmon.out callgrind.out.*

FORCE: