OPT := # -O2 -nodebug
MIMPL := CFOR
BIMPL := NOBUSY
BCHECK := NOBARGINGCHECK

CXX = u++					# uC++ compiler
#CXX = /u/cs343/cfa-cc/bin/cfa			# CFA compiler
CXXFLAGS = -g -Wall -Wextra -multi -MMD ${OPT} -D"${MIMPL}" \
		-D"${BIMPL}" -D"${BCHECK}"	# compiler flags
MAKEFILE_NAME = ${firstword ${MAKEFILE_LIST}}	# makefile name

ifeq ($(notdir $(strip ${CXX})),cfa)
CXXFLAGS := $(filter-out -multi,${CXXFLAGS})	# remove uC++ -multi flag
CXXFLAGS += "-Wno-implicit-fallthrough"
OBJECTS2 += # object files forming 2nd executable with prefix "q3"
CFA=fa
.SUFFIXES :					# remove other default suffix rules
.SUFFIXES : .cfa .o				# add CFA default rules
.cfa.o :
	${CXX} ${CXXFLAGS} -c $<
endif

OBJECTS1 = # object files forming 1st executable with prefix "q2"
EXEC1 = matrixmultiply				# 1st executable name

OBJECTS2 += # object files forming 2nd executable with prefix "q3"
EXEC2 = buffer					# 2nd executable name

OBJECTS = ${OBJECTS1} ${OBJECTS2}		# all object files
DEPENDS = ${OBJECTS:.o=.d}			# substitute ".o" with ".d"
EXECS = ${EXEC1} ${EXEC2}			# all executables

.PHONY : all clean
.ONESHELL :

all : ${EXECS}					# build all executables

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

-include MatrixImpl

# same implementation concurrency/type as last time ?
ifeq (${IMPLMIMPL},${MIMPL})			# same implementation type as last time ?
${EXEC1} : ${OBJECTS1}
	${CXX} ${CXXFLAGS} $^ -o $@
else						# implementation type has changed => rebuilt
.PHONY : ${EXEC1}
${EXEC1} :
	rm -f MatrixImpl
	touch q2matrixmultiply.h${CFA}
	${MAKE} ${EXEC1} OPT="${OPT}" MIMPL="${MIMPL}"
endif

MatrixImpl :
	echo "IMPLMIMPL=${MIMPL}" > MatrixImpl
	sleep 1

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

-include BufImpl

# same implementation concurrency/type as last time ?
ifeq (${shell if [ "${BUFIMPL}" = "${BIMPL}" -a "${BCHECKIMPL}" = "${BCHECK}" ] ; \
		then echo true ; fi },true)
${EXEC2} : ${OBJECTS2}
	${CXX} ${CXXFLAGS} $^ -o $@
else						# implementation type has changed => rebuilt
.PHONY : ${EXEC2}
${EXEC2} :
	rm -f BufImpl
	touch q3buffer.h${CFA}
	${MAKE} ${EXEC2} OPT="${OPT}" BIMPL="${BIMPL}" BCHECK="${BCHECK}"
endif

BufImpl :
	echo "BUFIMPL=${BIMPL}\nBCHECKIMPL=${BCHECK}" > BufImpl
	sleep 1

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

${OBJECTS} : ${MAKEFILE_NAME}			# OPTIONAL : changes to this file => recompile

-include ${DEPENDS}				# include *.d files containing program dependences

clean :						# remove files that can be regenerated
	rm -f *.d *.o ${EXECS} MatrixImpl BufImpl
