# -*- makefile-gmake -*-

# rules used by the Makefiles in various test directories

DEFERRED ?= no

DOTS ?= ../..
ifeq "@DEBUG@" "no"
TLIMIT ?= 90
# one test doesn't work with only 150MB RAM, ext-total.m2, on a 64 bit intel machine:
MLIMIT ?=  800000
VLIMIT ?= 2000000
else
# give the debug version more time and space
TLIMIT ?= 140
MLIMIT ?= 1200000
VLIMIT ?= 2000000
endif
# make the stack limit always the same as it would be under MacOS
SLIMIT ?= 8192

LIMIT :=
ifeq (@ULIMIT_T@,yes)
LIMIT += ulimit -t $(TLIMIT) ;
endif
ifeq (@ULIMIT_M@,yes)
LIMIT += ulimit -m $(MLIMIT) ;
endif
#ifeq (@ULIMIT_V@,yes)
#LIMIT += ulimit -v $(VLIMIT) ;
#endif
ifeq (@ULIMIT_S@,yes)
LIMIT += ulimit -s $(SLIMIT) ;
endif

TESTFILES := $(wildcard $(SRCDIR)/*.m2)

RESULTS := $(notdir $(patsubst %.m2, %.out, $(TESTFILES))) \
	   $(notdir $(patsubst %.m2-input, %.out, $(wildcard $(SRCDIR)/*.m2-input)))

PAT := 'internal error|:[0-9][0-9]*:[0-9][0-9]*:\([0-9][0-9]*\):|^GC|^0x|^out of mem|non-zero status|^Command terminated|user.*system.*elapsed|^[0-9]+\.[0-9]+user'
FILTER := $(if $(VERBOSE),tail,egrep -a $(PAT))

ifeq ($(DEFERRED),no)
check: $(RESULTS)
else
check: check-deferred-warning
check-deferred-warning:
	@ for i in $(TESTFILES) ; do echo "$$i:1: warning: test file deferred" >&2 ; done
endif

$(RESULTS) : @pre_exec_prefix@/bin/M2 always

ARGS := --silent --stop -q -e 'path=join(path,{"$(SRCDIR)/","$(SRCDIR)/$(DOTS)/packages/"})'
ARGS += --no-debug --print-width 140
ARGS += --no-randomize

# ARGS += -e 'errorDepth=0'
# ARGS += -e 'gbTrace=5'

status: status-files
status-files: $(TESTFILES)
	@ egrep -n '^--status:' $(TESTFILES) /dev/null || true

%.out : %.m2
	@ echo testing: $<
	@ $(LIMIT) \
		echo "--*- compilation -*-" >$*.errors; \
		if (echo 'input "$<"'; echo 'collectGarbage()'; echo exit 0) | \
		   GC_MAXIMUM_HEAP_SIZE=400M time @pre_exec_prefix@/bin/M2 $(ARGS) >>$*.errors 2>&1 ; \
		then mv $*.errors $@ ; \
		else a=$$?; \
		     <$*.errors $(FILTER) ; \
		     echo "$*.errors:0: error output left here for the errors above:" >&2 ; \
		     egrep -n '^--status:' $< /dev/null || true ; \
		     exit $$a ; \
		fi
%.out : %.m2-input
	@ echo testing: $<
	@ egrep -n '^--status:' $< /dev/null || true
	@ $(LIMIT) \
		echo "--*- compilation -*-" >$*.errors; \
		if GC_MAXIMUM_HEAP_SIZE=400M time @pre_exec_prefix@/bin/M2 $(ARGS) <$< >>$*.errors 2>&1 ; \
		then mv $*.errors $@ ; \
		else a=$$?; \
		     echo "$*.errors:0: error output left here; some errors follow" >&2 ; \
		     <$*.errors $(FILTER) ; \
		     exit $$a ; \
		fi

review:
	@ echo error: `ls *.errors | wc -l` errors occurred
	@ echo summary of errors:
	@ for i in *.errors ; \
	  do echo `basename $$i .errors`.m2: ; \
	     <$$i $(FILTER) ; \
	  done

clean:; rm -f *.okay *.out core *.errors
distclean: clean; rm -f Makefile

# Local Variables:
# compile-command: "make -k -C $M2BUILDDIR/Macaulay2/packages/Macaulay2Doc/test check "
# End:
