#!/bin/sh

if [ "x$GCTLIB" = "x" ]
then
  GCTLIB=`pwd`/../../../../
  PATH=.:`pwd`/../../../..:$PATH; export PATH
fi

ROOT=../..
. $ROOT/run.source

########### DOUBLE calls.

call_double()
{
  expected_retval=$1

  I 
  true_retval=$?

  if [ $true_retval != $expected_retval ]
  then
	echo "Wanted $expected_retval got $true_retval"
  fi 
}


say double
clean; /bin/rm -f GCTLOG
cp ctrl.double gct-ctrl
make_constant_objects
make_I double-main
call_double 0
greport -all GCTLOG > double1.glog; diff double1.glog double1.gref
call_double 0
greport -all GCTLOG > double2.glog; diff double2.glog double2.gref
# Do it once more to increase chance of finding bug.
call_double 0
greport -all GCTLOG > double3.glog; diff double3.glog double3.gref

########### EXIT

call_exit()
{
  ARG=$1
  NEXTARG=$2
  expected_retval=$3

  I $ARG $NEXTARG
  true_retval=$?

  if [ $true_retval != $expected_retval ]
  then
	echo "Wanted $expected_retval got $true_retval"
  fi
}

doit_exit()
{
  TAG=$1
  say $TAG
  clean; /bin/rm -f GCTLOG
  cp ctrl.$TAG gct-ctrl
  make_constant_objects

  gct -c -B$GCTLIB exit-main.c
  cc -c fake-abort.c
  gct -o I exit-main.o fake-abort.o

  call_exit call simple  3
  call_exit call funcall 4
  call_exit call complex  6
  call_exit call abort  33
  call_exit no-call simple  13
  call_exit no-call funcall 14
  call_exit no-call complex  1
  call_exit no-call abort  33
  call_exit plain-exit ignored 55
  call_exit no-exit-fun ignored 19
  call_exit no-writelog ignored 20
}

doit_exit exit-norace
greport -all GCTLOG > exit-norace.glog ; diff exit-norace.glog exit-norace.gref

doit_exit exit-noinst
if [ -f GCTLOG ] 
then
	echo FAILURE:  GCTLOG should not have been created.
fi


say 2arg-exit
clean; /bin/rm -f GCTLOG
cp ctrl.2arg-exit gct-ctrl
make_constant_objects
gct -c -B$GCTLIB 2arg-exit.c
cc -c fake-abort2.c
gct -o I 2arg-exit.o fake-abort2.o
call_exit dummy dummy 33
greport -all GCTLOG > 2arg.glog; diff 2arg.glog 2arg.gref

########### RETURNS FROM MAIN

call_ret()
{
  ARG=$1
  expected_retval=$2

  I $ARG
  true_retval=$?

  if [ $true_retval != $expected_retval ]
  then
	echo "Wanted $expected_retval got $true_retval"
  fi 
}

doit_ret()
{
  TAG=$1
  say $TAG
  clean; /bin/rm -f GCTLOG
  cp ctrl.$TAG gct-ctrl
  make_constant_objects
  make_I ret-main

  call_ret simple-token-noinst 0
  call_ret complex-noinst-top 3
  call_ret complex-inst-lower 5
  call_ret multi-return-inst 1
  call_ret funcall-inst 4
  call_ret branch-inst 7
  I return-no-expr
}

doit_ret ret-norace
greport -all GCTLOG > ret-norace.glog ; diff ret-norace.glog ret-norace.gref

doit_ret ret-noinst
if [ -f GCTLOG ] 
then
	echo FAILURE:  GCTLOG should not have been created.
fi

exit 0
