#! /bin/bash
# script to compile C programs that are linked 
# against Fortran libraries
# last modified 12 Oct 21 th

exec 3>&2
exec 2> /tmp/fcc.log.$$
set -x

args=
compileonly=
objs=
ldflags=
fldflags=
cdefs=

cc="${REALCC:-cc}"
cc+=" $cdefs"
cxx="${REALCXX:-c++}"
cxx+=" $cdefs"
[[ "${0%.in}" =~ f++$ ]] && cc="$cxx"

while test $# -gt 0; do
  printf -v arg "%q" "$1"
  case "$1" in
  -st | -b32 | -b64)
	;; # ignore mcc-specific flags
  -arch)
	shift
	;;
  -lstdc++)
	cc="$cxx"
	;; # or else -static-libstdc++ has no effect
  -Wno-long-double)
	;; # mcc adds this on Macs & gcc 4 doesn't like it
  -L*CompilerAdditions*)
	ldflags+=" $arg"
	mldir="${1#-L}"
	mldir="${mldir%%CompilerAdditions*}"
	mldir="${mldir/Links\/MathLink\/DeveloperKit/Libraries}"
	[[ "$cc" == *-m32* ]] && mldir="${mldir//-x86-64}"
	test -f "$mldir/libuuid.a" && ldflags+=" -L'$mldir'" fldflags+=" -luuid"
	;;
  -[Ll]* | -Wl*)
	ldflags+=" $arg"
	;;
  *.tm.o)
	objs="$arg $objs"
	;;
  *.a | *.o | *.so)
	objs+=" $arg"
	;;
  *.cc)
	args+=" $arg"
	cc="$cxx"
	;;
  -c)
	compileonly="-c"
	;;
  -o)
	args+=" -o '$2'"
	shift
	;;
  *.tm.c)
	args+=" $arg"
	tmc+=" $arg"
	;;
  *)
	args+=" $arg"
	tmargs+=" $arg"
	;;
  esac
  shift
done

test -n "$DEBUG" && for tm in $tmc; do
  eval "$cc $tmargs -E -P -o ${tm//.c}.i $tm 2>&3"
done

eval "set -x; exec $cc $args ${compileonly:-$objs $ldflags $fldflags} 2>&3"

