#! /bin/sh
#  HimML linker and archiver.
#  Copyright (C) 2002-2005 Jean Goubault-Larrecq
#  and LSV, CNRS UMR 8643 & INRIA Futurs projet Secsi & ENS Cachan.
#
#  This file is part of HimML.
#
#  HimML is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2, or (at your option)
#  any later version.
#
#  HimML is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with HimML; see the file COPYING.  If not, write to
#  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.

TMPFILE=himml$$.ml
TMPFILEX=himml$$.mlx

ARCHIVE=0
# By default, ARCHIVE is unset, meaning that it is checked whether
# everything links OK and there is a main entry.
case $1 in
  -a) ARCHIVE=1; shift;;
esac

TARGET=$1
shift

himmlrun `which himmlpack` "$@" >$TMPFILE
if `himml -c $TMPFILE`
then
  OK=1
else
  OK=0
fi

if [ $OK -ne 0 ]
then
  if [ $ARCHIVE -ne 0 ]
  then
    OK=1
  else
    if `himml -cmd "open* \"$TMPFILEX\"; fn _ => main (); quit 0;"`
    then
      OK=1
    else
      echo "himmllnk: some symbols were not resolved.  Stop."
      OK=0
    fi
  fi
fi

if [ $OK -ne 0 ]
then
  mv ${TMPFILE}x $TARGET && chmod a+x $TARGET
  rm $TMPFILE
else
  rm $TMPFILE
  rm $TMPFILEX
fi

