#!/bin/sh

usage() {
    echo "USAGE:  $0 -h|--help"
    echo "USAGE:  $0 [-z NUMBER] [-a NUMBER] [-n NUMBER] [-f FILE]"
    echo ""
    echo "Options:"
    echo "  -z  Sine Zero value in decimal (sin(0))"
    echo "  -a  Sine Amplitude value in decimal (sin(pi))"
    echo "  -n  Number of Period Samples"
    echo "  -f  Output VHDL File"
}


#**********MAIN**********

FILE="test_sine.vhd"
amp=1024
zero=512
num=1024

while [ $# -gt 0 ]; do
    case "$1" in
        -a)
            shift
            amp=$1
            shift
            case $amp in
                ''|*[!0-9]*) 
                    echo "ERROR: -a Option needs a Decimal Number."
                    usage
                    exit 1
                    ;;
                *);;
            esac
            ;;
        -z)
            shift
            zero=$1
            shift
            case $zero in
                ''|*[!0-9]*) 
                    echo "ERROR: -z Option needs a Decimal Number."
                    usage
                    exit 1
                    ;;
                *);;
            esac
            ;;
        -n)
            shift
            num=$1
            shift
            case $num in
                ''|*[!0-9]*) 
                    echo "ERROR: -n Option needs a Decimal Number."
                    usage
                    exit 1
                    ;;
                *);;
            esac
            ;;
        -f)
            shift
            FILE=$1
            shift
            ;;
        -h|--help)
            usage
            exit
            ;;
        *)
            echo "ERROR: Unknown Option"
            usage
            exit 1
            ;;
    esac
done

#SANITY CHECK
if [ $amp -gt $zero ] 
then
    echo "ERROR: The Sine Amplitude has to be smaller than the Zero point."
    usage
    exit 1
fi
if [ $(echo "$amp+$zero" | bc -l) -gt 4095 ] 
then
    echo "ERROR: The requested Sine exceeds the 12 Bits representation (2^12=4096)"
    usage
    exit 1
fi

#Calculate Stepping
step=$(echo "(2*(4*a(1)))/$num" | bc -l)
num=$(echo "$num-1" | bc -l)

cat <<EOF >$FILE
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

package sine_package is
EOF

echo "    type SINE_ARRAY_TYPE is array (0 to $num) of std_logic_vector(11 downto 0);" >>$FILE
array="    constant sine : SINE_ARRAY_TYPE := ("

for i in $(seq 0 $num)
do
    #Calculate Value
    val=$(echo "($amp * s($i*$step))+$zero" | bc -l)
    #Round
    val=$(printf '%.0f' $val)
    array=$array$(printf 'x"%03X"' $val)
    
    if [ $i -eq $num ]
    then
        array=$array$(printf ');\n')
    else
        array=$array", "
    fi
done
echo $array >>$FILE
echo "end package;" >>$FILE
