#
#  Generic make commands for rebuilding a library from source files
#  For GNU make; will not work with most other make programs
#
#  Usage:
#	SOURCES = a.c b.c ...
#	LIBNAME = libtsp	# default libtsp (cc) or libuti (f77)
#       HEADERS = a.h
#	include ../Make_lib
#
#  Optional make variables:
#	DEFS = ...		# passed to C-preprocessor
#	libdir = ...		# library directory
#	includedir = ...	# include file directory
#
#  Environment variable:
#	tspdir			# root directory for lib and include
#				#   (default /usr/local)

# $Id: Make_lib,v 1.14 1996/04/28 libtsp-V2R7a $

SHELL = /bin/sh

ifndef tspdir
  tspdir = /usr/local
endif

exec_prefix = $(tspdir)
libdir = $(exec_prefix)/lib
includedir = $(tspdir)/include

# Object modules
OBJ_1 = $(SOURCES:.c=.o)
OBJ_2 = $(OBJ_1:.f=.o)
OBJECTS = $(OBJ_2:.F=.o)

# Determine which language will be used
LANG = C
ifeq (.f,$(findstring .f,$(SOURCES)))
  LANG = FORTRAN
endif
ifeq (.F,$(findstring .F,$(SOURCES)))
  LANG = FORTRAN
endif

# Set the default library name
ifeq ($(LANG),FORTRAN)
  DEF_LIBNAME = libuti
else
  ifeq ($(CC),CC)
    DEF_LIBNAME = libtspCC
  else
    ifeq ($(CC),gcc)
      DEF_LIBNAME = libtspgcc
    else
      DEF_LIBNAME = libtsp
    endif
  endif
endif

# Library name
ifndef LIBNAME
  LIBNAME = $(DEF_LIBNAME)
endif
LIB = $(libdir)/$(LIBNAME).a
LIB_MODULES = $(LIB)($(OBJECTS))

# Compile flags
ifndef CFLAGS
  ifeq ($(CC),gcc)
    CFLAGS = -O3 -Wall
  else
    CFLAGS = -O2
  endif
endif
ifndef FFLAGS
  FFLAGS = -u -O
endif
ifndef LINTFLAGS
  LINTFLAGS = -u -x
endif
ifndef COFLAGS
  COFLAGS = -M
endif

.PRECIOUS: $(LIB)
.PHONY:	lint test

# Default target: update the library
$(LIB):	$(LIB_MODULES)
	ranlib $(LIB)
	@echo $(LIB) updated

ifdef HEADERS
$(LIB_MODULES):	$(HEADERS)
endif

# run test programs
test:
	@-test -d test && cd test && $(MAKE) test

# run lint
lint:	$(SOURCES)
	$(LINT) -I$(includedir) $(LINTFLAGS) $?

# implicit C compile rule with include directory and DEFS
# implicit Fortran (with preprocessor) compile rule with DEFS
.c.o:
	$(CC) -c -I$(includedir) $(CFLAGS) $(CPPFLAGS) $(DEFS) $< -o $@
.F.o:
	$(FC) -c $(FFLAGS) $(CPPFLAGS) $(DEFS) $< -o $@
