#!/bin/bash

# The purpose of this wrapper script is to use the C preprocessor for
# QNICE assembler. Assembling QNICE sources is done invoking this script
# with the source file name as its only parameter.

ASM_SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

source $ASM_SCRIPT_DIR/../tools/detect.include

temp_file=__temp__.asm

if [ $# -ne 1 ]
then
  echo "Usage: asm <source.asm>"
  exit
fi

assembler=`dirname $0`/qasm
makerom=`dirname $0`/qasm2rom

destination=${1/.asm/}.out
romfile=${1/.asm/}.rom

rm $destination 2> /dev/null
rm $romfile 2> /dev/null

#
# We use the standard C-preprocessor to perform the necessary 
# preprocessor steps for the QNICE-assembler. Since the preprocessor
# inserts lines starting with a '#' which the assembler does
# not like, these are subsequently removed with sed.
#
$COMPILER -xc -E $1 | sed '/^#.*/d' > $temp_file

$assembler $temp_file $destination
if [ $? -ne 0 ]
then
  echo "An unrevoverable error occured!"
  rm $temp_file
  exit -1
fi

rm $temp_file

if [ "$QNICE_ASM_NO_ROM" != "1" ]
then
    $makerom $destination $romfile
fi

if [ $OSTP = "LINUX" ]; then
    if hash xclip 2>/dev/null; then
        cat $destination | xclip -selection clipboard
    fi;
elif [ $OSTP = "OSX" ]; then
    cat $destination | pbcopy
fi;
