# Standalone makefile for MPIglut
#  MPIglut itself it trivially easy to build--just use an MPI compiler.
#  It does need a special patched freeglut, however.

# Compiler and flags
CCC=mpiCC
CC=mpicc
OUTFLAG=-o 
OPTS=-O2

CFLAGS=-I. $(OPTS)

# This is the output library name.
LIB=libmpiglut.a
# These are the object files our library requires.
OBJS=mpiglut.o dmx.o

all: $(LIB)

# Build libmpiglut.a from object files
$(LIB): libglut.a $(OBJS)
	cp libglut.a $(LIB)  # Start with freeglut library
	ar cr $(LIB) $(OBJS) # Add our object files
	@echo '# Excellent! You now have a fully-build $(LIB).'
	@echo '# You can now "make install", or else compile and link with -I'`pwd`' -L'`pwd`' -lmpiglut'
	@echo '# Then build your application, changing your #include to "GL/mpiglut.h",'
	@echo '# compile your code with mpiCC, and link with -lmpiglut!'

# Build mpiglut.o
mpiglut.o: mpiglut.c GL/mpiglut.h
	$(CC) $(CFLAGS) -c $< $(OUTFLAG) $@

# Extract libdmx.a to get dmx.o (this avoids the need to link with -ldmx)
dmx.o: libdmx.a
	ar x libdmx.a dmx.o

libdmx.a: 
	cp /usr/lib/libdmx.a .

# Build our patched version of freeglut
FG_VER=freeglut-2.4.0.tar.gz
$(FG_VER):
	@echo "MPIglut is downloading and unpacking freeglut 2.4.0..."
	wget http://internap.dl.sourceforge.net/sourceforge/freeglut/$(FG_VER)

freeglut/patched: freeglut_patch $(FG_VER)
	tar xzvf $(FG_VER)
	mv freeglut-2.4.0 freeglut
	@echo "MPIglut is patching freeglut source..."
	[ -r freeglut/patched ] || ( cd freeglut; patch --strip 1 < ../freeglut_patch )
	touch freeglut/patched

freeglut/src/Makefile: freeglut/patched
	cd freeglut; CFLAGS="-O2" ./configure

libglut.a: freeglut/src/Makefile
	cd freeglut/src; make
	cp freeglut/src/.libs/libglut.a .


# Install MPIglut library into system directories *alongside* existing GLUT
install: $(LIB)
	cp $(LIB) /usr/lib/
	cp GL/mpiglut.h /usr/include/GL/
	@echo "$(LIB) has been installed to /usr/lib, and the MPIglut header to /usr/include/GL"
	@echo "Warning: if you do not have freeglut installed on the system, copy GL/*.h to /usr/include/GL"

clean:
	-rm $(OBJS) $(LIB) freeglut/src/*.*o libglut.a

superclean: clean
	-rm -fr *.a freeglut $(FG_VER)
