#!/bin/sh

SELF=$0

GCT_PROG=$1
if [ "$GCT_PROG" = "" ]
then
  echo "You must give the name of a GCT shell script as an argument."
  exit 1
fi

# Used to pass in -v for debugging.
VERBOSE_OPTION=$2

echo "Is the compiler that $GCT_PROG uses an ANSI C compiler? (y/n)"
read answer

ANSI=false
if [ "$answer" = "y" ]
then 
  ANSI=true
fi

# First argument is "varargs" or "stdarg".
run_one()
{
  WHICH=$1
  FAILURE=false
  make clean
  gct-init
  if [ $? != 0 ] 
  then
    FAILURE=true
    echo "FAILURE:  gct-init failed.  Are you running this before you made GCT?"
    echo "Is the installed version of GCT in your path?"
    return
  fi

  $GCT_PROG -o $WHICH $VERBOSE_OPTION $WHICH.c main.c
  if [ $? != 0 ] 
  then
    FAILURE=true
    echo "FAILURE: Either GCT or the compiler failed.  No executable was created."
    echo "See the Troubleshooting section of the installation guide."
    echo "The second cause of check-varargs problems is the more likely."
    echo "If you're stumped, report the problem.  Include the results of"
    echo "$SELF $GCT_PROG -v"
    return
  fi

  if $WHICH -normal > /dev/null
  then
    echo "\"Normal\" function arguments (integers, doubles, and pointers) work."
  else
    FAILURE=true
    echo "FAILURE: \"Normal\" function arguments (integers, doubles, and pointers) "
    echo "DON'T work.  See the Troubleshooting section of the installation guide."
    echo "The first cause of check-varargs problems is the more likely."
  fi

  if $WHICH -struct > /dev/null
  then
    echo "Structure arguments to functions work."
  else
    FAILURE=true
    echo "FAILURE:  Structure arguments to functions DON'T work."
    echo "See the Troubleshooting section of the installation guide."
    echo "The first cause of check-varargs problems is the more likely."
  fi

  if [ "$FAILURE" = true ]	# Coverage will surely be wrong.
  then
    return
  fi

  greport -all GCTLOG | sed "s/$WHICH.c/FILE/" > LOG.report
  if diff LOG.report REF > /dev/null
  then 
    echo "Coverage results are correct."
  else
    FAILURE=true
    echo "FAILURE: Coverage was INCORRECTLY measured.  Please report this likely GCT bug."
  fi

  if [ "$FAILURE" = false ]
  then
    echo "SUCCESS"
  fi
}


# MAIN


cd varargs
echo
echo "Processing a program that uses <varargs.h>"
if [ "$VERBOSE_OPTION" != "" ]
then
  set -x
fi

run_one varargs
if [ $ANSI = true ]
then
  echo
  echo "Processing a program that uses <stdarg.h>"
  run_one stdarg
fi

exit 0
