#!/bin/bash
#Compile and Assemble C02 Program

#Split Script Name Into Directory and File Name
SDIR=${0%/*}; #Script Path
SNAM=${0##*/};   #Script Name 

#Check for Command Line Argument
if [[ "$1" = "" ]]; then
  echo "Usage: $SNAM file[.c02]"
  exit
fi

#Get Working Directory Name
WPTH=`pwd`;       #Get Path
WDIR=${WPTH##*/}; #Extract Directory

#Split File Name Parts
FSPC=$1;          #File Spec
FNAM=${FSPC%.*};  #File Name without Extension
FEXT=${FSPC##*.}; #File Extension

#Generate Output File Names
ASPC=$1.asm       #Assembly Language generated by Compiler
BSPC=$FNAM.bin		  #Binary File created by DASM
OSPC=$1.out		  #Output File

#Set Default DASM Parameters
OFMT=3            #Raw Binary File

if [[ "$WDIR" == "vic20" ]]; then
  BSPC=$FNAM.prg
  OFMT=1          #Binary with Load Address
fi

#Compile C02 FILE
$SDIR/c02 $FSPC
ESTS=$?; #Exit Status

if [[ $ESTS -ne 0 ]]; then
  echo "Error compiling file $FSPC"
  exit $ESTS
fi 

#Assemble ASM File
echo "Assembling file $FNAM.asm"
dasm $FNAM.asm -f$OFMT -o$BSPC -l$FNAM.lst -s$FNAM.sym
ESTS=$?; #Exit Status
if [[ $ESTS -ne 0 ]]; then
  echo "Error Assembling file $FNAM.asm"
  exit $ESTS
fi


if [[ "$WDIR" == "vcs" ]]; then
  echo "Converting file $FNAM.bin to WAV"
  makewav -ts -k2 -d3 $FNAM.bin >$OSPC
fi

#Report Successful Completion
echo "Successfully compiled and assembled file $FSPC"

