#!/bin/bash

# Build script for Xilinx FPGAs, adapted by teknohog from a script in
# the nexys2prog project

# Find and use the latest version
BASEDIR=/space/Xilinx
VERSION=`ls $BASEDIR | grep "[0-9]" | tail -n1`
export PATH=$PATH:$BASEDIR/$VERSION/ISE_DS/ISE/bin/lin64

NICE="nice -n 10"
IONICE="ionice -c 3"

# Nexys2 500 K
PART=xc3s500e-fg320-5

# J-board
#PART=xc3s1600e-fg320-4

# Spartan 6 in Atlys 2
#PART=xc6slx45-csg324-3

# Spartan 6 in Nexys 3
#PART=xc6slx16-csg324-3

# Zynq in Zedboard (speed grade?)
#PART=xc7z020-clg484-1

# You may need to comment in the following if the Xilinx variables are not
# yet set in your environment
#source /opt/Xilinx/11.1/settings32.sh

# Area/_Speed_, 0/_1_/2 (defaults underlined)
#XSTOPTIONS="-opt_mode Area -opt_level 2"
#XSTOPTIONS="-opt_mode Speed -opt_level 2"
XSTOPTIONS="-opt_mode Area -opt_level 0"

# Multithread only for virtex5, virtex6, spartan6 and higher, zynq
PAROPTIONS="-ol std -pl std -rl std"
#PAROPTIONS="-ol high -pl high -rl high"
#PAROPTIONS="-ol std -pl std -rl std -mt 4"
#PAROPTIONS="-ol high -pl high -rl high -mt 4"

# The command line option -ol can only be used when running in timing
# mode (-timing option).
# off|power|speed|area, no area/speed for spartan3
#MAPOPTIONS="-global_opt area -mt 4"
#MAPOPTIONS="-global_opt area"
#MAPOPTIONS="-global_opt off -mt 4"
MAPOPTIONS="-global_opt off"

function bitgenerate () {
    # ok, how do I actually make clean?-)
    rm -r $DELETES
    
    # A backup might turn out useful
    mv -f $PROJ.bit $PROJ.old.bit
    
    echo run -ifn $PROJ.v -ifmt verilog -ofn $PROJ.ngc -p $PART -top $PROJ $XSTOPTIONS -define {$DEFINE} | $NICE $IONICE xst
    $NICE $IONICE ngdbuild -p $PART -uc $PROJ.ucf $PROJ.ngc
    $NICE $IONICE map $MAPOPTIONS -p $PART $PROJ.ngd
    $NICE $IONICE par $PAROPTIONS $PROJ.ncd ${PROJ}_par.ncd $PROJ.pcf
    $NICE $IONICE bitgen ${PROJ}_par.ncd $PROJ.bit $PROJ.pcf
}

DEFINE=""
while getopts b:d: opt; do
    case "$opt" in
	b) PROJ="$OPTARG" ;;
	d) DEFINE="$OPTARG" ;;
    esac
done

DELETES="${PROJ}.bgn
${PROJ}_bitgen.xwbt
${PROJ}.bld
${PROJ}.drc
${PROJ}.map
${PROJ}_map.xrpt
${PROJ}.mrp
${PROJ}.ncd
${PROJ}.ngc
${PROJ}.ngc_xst.xrpt
${PROJ}.ngd
${PROJ}_ngdbuild.xrpt
${PROJ}.ngm
${PROJ}_par.ncd
${PROJ}_par.pad
${PROJ}_par_pad.csv
${PROJ}_par.par
${PROJ}_par.ptwx
${PROJ}_par.unroutes
${PROJ}_par.xpi
${PROJ}_par.xrpt
${PROJ}.pcf
${PROJ}_summary.xml
${PROJ}_usage.xml
netlist.lst
usage_statistics_webtalk.html
webtalk.log
xlnx_auto_0_xdb
_xmsgs
xst"

bitgenerate
