SHELL = /bin/sh
CC = gcc

### psLib
PSLIB_INCLUDE := $(shell pslib-config --cflags)
PSLIB_LINK := $(shell pslib-config --libs)

### Additional flags for diagnostics, testing, etc
#PAP_CFLAGS = -DTESTING
#PAP_CFLAGS = -DCRFLUX

### Build flags
CFLAGS += -g -O2 -std=c99 -Werror -D_GNU_SOURCE -DPS_NO_TRACE $(PSLIB_INCLUDE) $(PAP_CFLAGS)
LDFLAGS += $(PSLIB_LINK)

### Ingredients for each program
STAC = stac.o stacConfig.o stacRead.o stacErrorImages.o stacTransform.o stacCheckMemory.o stacHelp.o \
	stacCombine.o stacInvertMaps.o stacRejection.o stacAreaOfInterest.o stacSize.o stacScales.o \
	stacTime.o

SHIFT = shift.o stacRead.o stacTransform.o stacCheckMemory.o stacInvertMaps.o stacSize.o

COMBINE = combine.o combineConfig.o stacRead.o stacErrorImages.o stacCombine.o stacScales.o \
	stacCheckMemory.o stacTime.o

SHIFTSIZE = shiftSize.o stacWrite.o stacConfig.o stacRead.o stacCheckMemory.o stacSize.o

FIXIMAGE = fixImage.o

CALCGRADIENT = calcGradient.o stacRejection.o

SUM = sum.o

### List of targets
TARGETS = stac shift combine shiftSize calcGradient sum


### Build recipes
.PHONY: tags clean empty test profile optimise all

.c.o:
		$(CC) -c $(CFLAGS) $(OPTFLAGS) $<

all:		$(TARGETS)

stac:		$(STAC)
		$(CC) $(CFLAGS) -o $@ $(STAC) $(LDFLAGS) $(OPTFLAGS)

shift:		$(SHIFT)
		$(CC) $(CFLAGS) -o $@ $(SHIFT) $(LDFLAGS) $(OPTFLAGS)

combine:	$(COMBINE)
		$(CC) $(CFLAGS) -o $@ $(COMBINE) $(LDFLAGS) $(OPTFLAGS)

shiftSize:	$(SHIFTSIZE)
		$(CC) $(CFLAGS) -o $@ $(SHIFTSIZE) $(LDFLAGS) $(OPTFLAGS)

calcGradient:	$(CALCGRADIENT)
		$(CC) $(CFLAGS) -o $@ $(CALCGRADIENT) $(LDFLAGS) $(OPTFLAGS)

sum:		$(SUM)
		$(CC) $(CFLAGS) -o $@ $(SUM) $(LDFLAGS) $(OPTFLAGS)


clean:
		-$(RM) *.o gmon.* profile.txt

empty:		clean
		-$(RM) $(TARGETS) TAGS

test:		stac test_0.fits test_1.fits test_2.fits test_3.fits
		-$(RM) testout.fits
		-$(RM) testout.fits.pre
		-$(RM) chi2_*.fits
		-$(RM) test_[0-3].fits.err
		-$(RM) test_[0-3].fits.mask
		-$(RM) test_[0-3].fits.shift.*
		-$(RM) test_[0-3].fits.shiftrej
		-$(RM) test_[0-3].fits.shifterr.*
		-$(RM) test_[0-3].fits.grad
		-$(RM) test_[0-3].fits.region
		-$(RM) test_[0-3].fits.rejmap
		-$(RM) leaks.dat
		./stac -v testout.fits test_0.fits test_1.fits test_2.fits test_3.fits

# Run profiling.
profile:	CFLAGS += -pg
profile:	empty $(TARGET)
		$(RM) gmon.*
		for ((i = 0; i < 10; i++)) \
		do \
			$(MAKE) test; \
			mv -f gmon.out gmon.$$i; \
		done
		gprof -p -q -l $(TARGET) gmon.* > profile.txt

# Do gcc optimisation
optimise:	clean
		-$(RM) $(TARGET)
		export OPTFLAGS=-fprofile-generate ; $(MAKE) test
		-$(RM) $(TARGET)
		$(MAKE) clean
		export OPTFLAGS=-fbranch-use ; $(MAKE) $(TARGET)
		-$(RM) *.da

# Tags for emacs
tags:
		etags `find . -name \*.[ch] -print`

