CFLAGS := -m32 -g -Wno-deprecated-declarations -std=c99 -g
LDFLAGS := -m32
LDLIBS := -lm
SHELL := /bin/bash

.PHONY: all clean check

# All tests
tests := $(sort $(patsubst %.c,%,$(wildcard test_*.c)))
# Out of Memory tests
oom := $(filter %_oom,$(tests))

all: $(tests)
clean:
	$(RM) $(tests) $(tests:=.o) bn.o test.o test_fun.o bad_malloc.o
%.o: %.s
	$(CC) -c -o $@ $(CFLAGS) $<

check: all
	@passed=yes; \
	points=0; \
	results=; \
	for x in $(tests); do \
		err=`mktemp`; \
		output=(`./$$x 2>"$$err"`); \
		if [ $$? != 0 ]; then \
			passed=no; \
			echo "$$x:"; \
			cat "$$err"; \
			echo; \
		fi; \
		rm -f "$$err"; \
		p=$${output[1]-0}; \
		points=$$((points + $${p%%/*})); \
		results="$$results$$(printf '%-20s%12s%10s|' "$$x" $${output[0]-0} $${output[1]-0})"; \
	done; \
	printf '%-20s%12s%10s\n' 'Test Name' 'Passed Tests' Points; \
	echo -n "$$results"|tr '|' '\n'; \
	if [ $$passed = yes ]; then \
		echo 'All tests passed'; \
	else \
		echo 'Some tests failed'; \
	fi; \
	echo 'Total points:' $$points '+ points for comments';

$(tests): bn.o test_fun.o test.o
$(tests:=.o): bn.h test.h
test.o: test.h

$(oom): bad_malloc.o
$(oom:=.o): bad_malloc.h
bad_malloc.o: bad_malloc.h
