#!/usr/bin/perl

use warnings;

# This script generates two lookup tables, one for sin and the other for cos.
# The sin and cos values returned by the library functions are bound between
# -1.0 to 1.0. Since we can do floating point on the PPC 405, I multiply
# each value by a constant given by 2^table_width (input parameter) which 
# represents the number of bits dedicated for each lookup table value. The
# multiplication simply scales the sin/cos values to integers to meet the
# requirements for processing on the PPC. Note that this table ONLY works
# for 512 point wfms (2^9).

if ($#ARGV != 1)
   { die "ERROR: gen_sincos_table.pl MUST be called 'theta_width (9)' 'table_width (12)' \n"; }

$theta_width = $ARGV[0];
$table_width = $ARGV[1];

$num_pts = 2**$theta_width;
$mult = 2**$table_width;
$pi = 3.14159265358979323846;

for ($i = 0; $i < $num_pts; $i++)
   {
   $sintab[$i] = sin($i*2*$pi/$num_pts);
   $costab[$i] = cos($i*2*$pi/$num_pts);
#   print "sin/cos of $i is ", $sintab[$i], "\t", $costab[$i], "\n";
   $costab[$i] *= $mult;
   $sintab[$i] *= $mult;
#   print "  SCALED ", int($sintab[$i]), "\t", int($costab[$i]), "\n";
   }


$file_name = "SinCosLookup.c";
open(OUTFILE, ">$file_name") || die;

print OUTFILE "/* Sin/Cos function generated automatically by gen_sincos_table.pl */\n\n";
print OUTFILE "#include \"stdio.h\"\n\n";

print OUTFILE "short sintab[$num_pts] = {";
for ( $i = 0; $i < $num_pts; $i++ )
   {
   if ( $i % 10 == 0 )
      { print OUTFILE "\n"; }

   print OUTFILE "\t", int($sintab[$i]);
   if ( $i < $num_pts - 1 )
      { print OUTFILE ","; }
   }
print OUTFILE "};\n\n";

print OUTFILE "short costab[$num_pts] = {";
for ( $i = 0; $i < $num_pts; $i++ )
   {
   if ( $i % 10 == 0 )
      { print OUTFILE "\n"; }

   print OUTFILE "\t", int($costab[$i]);
   if ( $i < $num_pts - 1 )
      { print OUTFILE ","; }
   }
print OUTFILE "};\n\n";

print OUTFILE "short GetSin(index)\n";
print OUTFILE "   int index;\n";
print OUTFILE "   {\n";
print OUTFILE "   index = 0x01FF & index;\n";
print OUTFILE "   return sintab[index];\n";
print OUTFILE "   }\n\n";

print OUTFILE "short GetCos(index)\n";
print OUTFILE "   int index;\n";
print OUTFILE "   {\n";
print OUTFILE "   index = 0x01FF & index;\n";
print OUTFILE "   return costab[index];\n";
print OUTFILE "   }\n\n";

print OUTFILE "int main()\n";
print OUTFILE "   {\n";
print OUTFILE "   printf(\"%d\\n\", GetSin(0));\n";
print OUTFILE "   printf(\"%d\\n\", GetCos(0));\n";
print OUTFILE "   }\n";

close OUTFILE;

