#!/bin/bash

 runtimesystem=""
 stdlib=""
 rtedlib=""

 for var in "$@"
 do
    parameter="$var"
    if [ "$parameter" = "-o" ]; then
      remove=$parameter;
    elif [ "x$parameter" = "x-pthread" ] ; then
     remove=$parameter;
    elif [ "x$parameter" = "xCppRuntimeSystem/libCppRuntimeSystem.la" ]; then
#     newOption=$newOption" CppRuntimeSystem/.libs/libCppRuntimeSystem.so";
     remove=$parameter
    elif [ "x$parameter" = "x-Winvalid-pch" ]; then
     remove=$parameter;
    elif [ "x$parameter" = "x-fPIC" ]; then
     remove=$parameter;
    elif [ "x$parameter" = "x-rose:UPC" ]; then
     remove=$parameter;
    elif [[ $parameter == *RuntimeSystem.cpp ]]; then
     runtimesystem=$parameter
    elif [[ $parameter == *.upc ]]; then
      filename=`basename $parameter .upc`
      inpfiles="$inpfiles $parameter"
      objfiles="$objfiles $filename.o"
    elif [[ $parameter == *.bin ]]; then
     executable=$parameter;
    else
      newOption=$newOption" "$parameter;
    fi
#    echo "$remove";
# --------- $parameter";
 done
#echo "REMOVED :: $remove"
#echo "KEPT :: $newOption"
#echo $newOption;

# compiling with C++ and RTED runtime?
if [ "$runtimesystem" != "" ]; then
  echo "g++ -c $runtimesystem"
  g++ -c $runtimesystem

  # find the libstdc++ that the C++ compiler would use
  stdlibfile=`g++ --print-file-name=libstdc++.so`
  stdlibdir=`dirname $stdlibfile`

  stdlib="-L$stdlibdir -lstdc++"
  rtedlib="RuntimeSystem.o -L./CppRuntimeSystem/.libs/ -lCppRuntimeSystem"
fi

echo "upc $newOption -c $inpfiles"
upc $newOption -c $inpfiles

echo "upc -o $executable $objfiles $rtedlib $stdlib"
exec upc -o $executable $objfiles $rtedlib $stdlib

echo "$objfiles"
rm $objfiles
