#!/usr/bin/perl -w
###############################################################################################
# Copyright 2004, All Rights Reserved, Texas Instruments Incorporate#
# vRegsTk.pl
#
# This script is a Perl Tk GUI for editing DUT card registers. It recognizes registers
# defined by the DCA module.
#
# 2005-Mar-01
# - Created
# 2005-Nov-01
# - Fixed bug in SDRAM default configuration values
# - Changed SDRAM configuration so user inputs actual cycles needed
#   The utility subtracts 1 from this value to get actual register field
#   value.
# - This same change was done for ASYNC RAM configuration
#
# 2006-Nov-15
# - Fixed bug in saing of the pincount to the .cfg file. We were writing a decimal
#   format instead of the require hexadecimal for genAIS use.
# 2007-Jun-14
# - Fixed register set/clr prblem in BuildCfgList.pm
# - Fixed problem in output of pin configuration
# 2007-Jul-11 V1.00.40
# - Fixed problem with PLL initialization (PLL was placed in PLLEN mode rahter than BYPASS)
# - Fixed problem with SD Ram control writing to incorrect bit for 
#   SDRAM refresh
# - Fixed global initialization for numEmifPins
# - Fixed problem where attempt was made to save config file even if action was
#   cancelled by select CANCEL as button option on "Save As" file menu option
###############################################################################################
use strict qw(subs refs);
use warnings qw(all);
use FindBin;
use lib "$FindBin::Bin/../lib";
use Tk;
use Tk::Balloon;
use Tk::Checkbutton;
use Tk::FileSelect;
use Tk::Pane;
use Tk::Tiler;
use Tk::Listbox;
use Tk::Optionmenu;
use Tk::Canvas;
use BuildPinCfgList;
use PinCfg;
use PLL;
use File::Basename;

our $VERSION = "1.00.40";

#----------------------------------------------------------------------------------------------
# helpText - Displayed when user uses the -h or -hh command line options
#----------------------------------------------------------------------------------------------
my $helpText = qq{
    genBootCfg.pl v$VERSION:  Enables Configuration of PLL, and EMIF for SDRAM,
                              ASYNC Ram, and GPIO Pins (mapped as address pins)
  Example(s)...
    genBootCfg
};

my %maskMode = (
                   "OR" => 1,
                   "AND" => 2,
                   "XOR" => 3,
                   "WRITE" => 4,
);

my %periphs = ( 
       "HPI"    => 0,
       "I2C0"   => 1,
       "I2C1"   => 2,
       "MCASP0" => 3,
       "MCASP1" => 4,
       "MCASP2" => 5,
       "SPI0"   => 6,
       "SPI1"   => 7,
);

my %pins = (
	'/HCS'   => 1,
	'/HDS1'  => 2,
	'/HDS2'  => 3,
	'HR/W'   => 4,
	'HCNTL1' => 5,
	'HCNTL0' => 6,
	'/HAS'   => 7,
	'HBE0'   => 8,
	'HBE1'   => 9,
	'HBE2'   => 10,
	'HBE3'   => 11,
	'HHWIL'  => 12,
	'HRDY'   => 13,
	'/HRDY'  => 14,
	'/HINT'  => 15,
	'HD[0]'     => 16, 'HD[1]'     => 17, 'HD[2]'     => 18, 'HD[3]'     => 19, 'HD[4]'     => 20,
	'HD[5]'     => 21, 'HD[6]'     => 22, 'HD[7]'     => 23, 'HD[8]'     => 24, 'HD[9]'     => 25,
	'HD[10]'    => 26, 'HD[11]'    => 27, 'HD[12]'    => 28, 'HD[13]'    => 29, 'HD[14]'    => 30,
	'HD[15]'    => 31, 'HD[16]'    => 32, 'HD[17]'    => 33, 'HD[18]'    => 34, 'HD[19]'    => 35,
	'HD[20]'    => 36, 'HD[21]'    => 37, 'HD[22]'    => 38, 'HD[23]'    => 39, 'HD[24]'    => 40,
	'HD[25]'    => 41, 'HD[26]'    => 42, 'HD[27]'    => 43, 'HD[28]'    => 44, 'HD[29]'    => 45,
	'HD[30]'    => 46, 'HD[31]'    => 47,
	
	'AXR0[0]'  => 51, 'AXR0[1]'  => 52, 'AXR0[2]'  => 53, 'AXR0[3]'  => 54, 'AXR0[4]'  => 55,
	'AXR0[5]'  => 56, 'AXR0[6]'  => 57, 'AXR0[7]'  => 58, 'AXR0[8]'  => 59, 'AXR0[9]'  => 60,
	'AXR0[10]' => 61, 'AXR0[11]' => 62, 'AXR0[12]' => 63, 'AXR0[13]' => 64, 'AXR0[14]' => 65,
	'AXR0[15]' => 66, 'AMUTE0'  => 67, 'ACLKX0'  => 68, 'AHCLKX0' => 69, 'AFSX0'   => 70,
	'ACLKR0'  => 71, 'AHCLKR0' => 72, 'AFSR0'   => 73,
	 
	'AXR1[0]'  => 64, 'AXR1[1]'  => 63, 'AXR1[2]'  => 62, 'AXR1[3]'  => 61, 'AXR1[4]'  => 60,
	'AXR1[5]'  => 59, 
	'AMUTE1'  => 74, 'ACLKX1'  => 75, 'AHCLKX1' => 76, 'AFSX1'   => 77,
	'ACLKR1'  => 78, 'AHCLKR1' => 79, 'AFSR1'   => 80,
		
	'AXR2[0]'  => 66, 'AXR2[1]'  => 65, 
	'AMUTE2'  => 81, 'ACLKX2'  => 82, 'AHCLKX2' => 83, 'AFSX2'   => 84,
	'ACLKR2'  => 85, 'AHCLKR2' => 86, 'AFSR2'   => 87,
		
	'SPI0_SIMO' => 89, 'SPI0_SOMI' => 90, 'SPI0_CLK' => 91, '/SPI0_ENA'  => 92,
    '/SPI0_SCS' => 93,
	
	'SPI1_SIMO' => 60, 'SPI1_SOMI' => 59, 'SPI1_CLK' => 58, '/SPI1_ENA'  => 57,	
    '/SPI1_SCS' => 56,
    
    'I2C0_SDA'  => 90, 'I2C0_SCL' => 91,
    
    'I2C1_SDA'  => 92, 'I2C1_SCL' => 93
);

my @bgaPinList = (
    'Not Mapped', 
    '/HCS' ,
    '/HDS1',	
    '/HDS2', 
	'HR/W' ,
	'HCNTL1',
	'HCNTL0',
	'/HAS',
	'HBE0',
	'HBE1',
	'HBE2',
	'HBE3',
	'HHWIL',
	'HRDY',
	'/HRDY',
	'/HINT',
	'HD[0]', 'HD[1]', 'HD[2]', 'HD[3]', 'HD[4]',
	'HD[5]', 'HD[6]', 'HD[7]', 'HD[8]', 'HD[9]',
	'HD[10]', 'HD[11]', 'HD[12]', 'HD[13]', 'HD[14]',
	'HD[15]', 'HD[16]', 'HD[17]', 'HD[18]', 'HD[19]',
	'HD[20]', 'HD[21]', 'HD[22]', 'HD[23]', 'HD[24]',
	'HD[25]', 'HD[26]', 'HD[27]', 'HD[28]', 'HD[29]',
	'HD[30]', 'HD[31]',
	
	'AXR0[0]', 'AXR0[1]', 'AXR0[2]', 'AXR0[3]', 'AXR0[4]',
	'AXR0[5]', 'AXR0[6]', 'AXR0[7]', 'AXR0[8]', 'AXR0[9]',
	'AXR0[10]', 'AXR0[11]', 'AXR0[12]' , 'AXR0[13]' , 'AXR0[14]',
	'AXR0[15]' ,'AMUTE0', 'ACLKX0', 'AHCLKX0', 'AFSX0',
	'ACLKR0', 'AHCLKR0', 'AFSR0',
	 
	'AXR1[0]', 'AXR1[1]', 'AXR1[2]', 'AXR1[3]', 'AXR1[4]',
	'AXR1[5]', 
	'AMUTE1', 'ACLKX1', 'AHCLKX1', 'AFSX1',
	'ACLKR1', 'AHCLKR1', 'AFSR1',
		
	'AXR2[0]', 'AXR2[1]', 
	'AMUTE2', 'ACLKX2', 'AHCLKX2', 'AFSX2',
	'ACLKR2', 'AHCLKR2', 'AFSR2',
		
	'SPI0_SIMO', 'SPI0_SOMI', 'SPI0_CLK', '/SPI0_ENA',
    '/SPI0_SCS',
	
	'SPI1_SIMO', 'SPI1_SOMI', 'SPI1_CLK', '/SPI1_ENA',	
    '/SPI1_SCS',
    
    'I2C0_SDA', 'I2C0_SCL',
    
    'I2C1_SDA' , 'I2C1_SCL'
);




my @tqfpPinList = (
    'Not Mapped', 
	'AXR0[0]', 'AXR0[1]', 'AXR0[2]', 'AXR0[3]', 'AXR0[4]',
	'AXR0[5]', 'AXR0[6]', 'AXR0[7]', 'AXR0[8]', 'AXR0[9]',
	'AXR0[10]', 'AXR0[11]', 'AXR0[12]' , 'AXR0[13]' , 'AXR0[14]',
	'AXR0[15]' ,'AMUTE0', 'ACLKX0', 'AHCLKX0', 'AFSX0',
	'ACLKR0', 'AHCLKR0', 'AFSR0',
	 
	'AXR1[0]', 'AXR1[1]', 'AXR1[2]', 'AXR1[3]', 'AXR1[4]',
	'AXR1[5]', 
	'AMUTE1', 'ACLKX1', 'AHCLKX1', 'AFSX1',
	'ACLKR1', 'AHCLKR1', 'AFSR1',
		
	'AXR2[0]', 'AXR2[1]', 
		
	'SPI0_SIMO', 'SPI0_SOMI', 'SPI0_CLK', '/SPI0_ENA',
    '/SPI0_SCS',
	
	'SPI1_SIMO', 'SPI1_SOMI', 'SPI1_CLK', '/SPI1_ENA',	
    '/SPI1_SCS',
    
    'I2C0_SDA', 'I2C0_SCL',
    
    'I2C1_SDA' , 'I2C1_SCL'
);
               
my @tmpPinCfg = ('Not Mapped','Not Mapped','Not Mapped','Not Mapped','Not Mapped',
                 'Not Mapped','Not Mapped','Not Mapped','Not Mapped','Not Mapped',
                 'Not Mapped','Not Mapped','Not Mapped','Not Mapped','Not Mapped');

my @pinCfg = ( 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF,
               0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF,
               0xFFFF, 0xFFFF );

my @pinsUsed = ( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
#----------------------------------------------------------------------------------------------
# Start of Code
#----------------------------------------------------------------------------------------------
my ($pkg);
my ($outFile);
my ($args);
my ($pinsUsed);
my ($PIN_IN_USE) = 1;
my ($periphWInOpen) = 0;
my ($hpiCfg) = 1;
my ($hpiPin);
my ($tmpPinCfg) = [];
my ($hFramePinSelect);
my ($hAddressPins) = [];
my ($status) = 1; # used to be delared as 0 earlier and masked
my ($cfgFile) = '';
my ($currentAddressPin) = 0;
my ($activePinList);
my ($addressPinCfg) = [];
my ($pinsConfigured) = 0;
my ($pllConfigured) = 0;
my ($sdramConfigured) = 0;
my ($asyncRamConfigured) = 0;
my ($i2cClkConfigured) = 0;
my ($configVar) = 'Configuration Output File, boot.cfg';
my ($clkIn) = 25;
my ($cpuClk) = 300;
my ($plldiv0) = 0;
my ($sysclk1) = 0;
my ($sysclk2) = 0;
my ($sysclk3) = 0;
my ($pllCfg)  = {};
my ($i2cCflkCfg) = {};
my ($pllResults);
my ($numPllCfgs) = 0;
my ($useAddressLatch) = 0;
my ($importData) = 0;
my ($sysclk) = 0;
my ($numEmifPins) = 13;

my ($sdramConfig);
my ($asyncRamConfig);
my ($cOutFile);

$addressPinCfg[0] = 'Not Mapped'; 
$addressPinCfg[1] = 'Not Mapped'; 
$addressPinCfg[2] = 'Not Mapped'; 
$addressPinCfg[3] = 'Not Mapped'; 
$addressPinCfg[4] = 'Not Mapped'; 
$addressPinCfg[5] = 'Not Mapped'; 
$addressPinCfg[6] = 'Not Mapped'; 
$addressPinCfg[7] = 'Not Mapped'; 
$addressPinCfg[8] = 'Not Mapped'; 
$addressPinCfg[9] = 'Not Mapped'; 
$addressPinCfg[10] = 'Not Mapped'; 
$addressPinCfg[11] = 'Not Mapped'; 
$addressPinCfg[12] = 'Not Mapped'; 
$addressPinCfg[13] = 'Not Mapped'; 
$addressPinCfg[14] = 'Not Mapped'; 
$addressPinCfg[15] = 'Not Mapped'; 
$addressPinCfg[16] = 'Not Mapped'; 
$addressPinCfg[17] = 'Not Mapped'; 
$addressPinCfg[18] = 'Not Mapped'; 
$addressPinCfg[19] = 'Not Mapped'; 
    
$pllCfg{'osc'}{'default'} = 0;
$pllCfg{'osc'}{'val'} = 0;
$pllCfg{'int_osc'}{'default'} = 0;
$pllCfg{'int_osc'}{'val'} = 0;
$pllCfg{'cpu'}{'default'} = 0;
$pllCfg{'cpu'}{'val'} = 0;
$pllCfg{'weight'}{'default'} = 3;
$pllCfg{'weight'}{'val'} = 3;

$pllCfg{'pllm'}{'default'} = 0;
$pllCfg{'pllm'}{'val'} = 0;
$pllCfg{'div0'}{'default'} = 0;
$pllCfg{'div0'}{'val'} = 0;
$pllCfg{'div1'}{'default'} = 0;
$pllCfg{'div1'}{'val'} = 0;
$pllCfg{'div2'}{'default'} = 0;
$pllCfg{'div2'}{'val'} = 0;
$pllCfg{'div3'}{'default'} = 0;
$pllCfg{'div3'}{'val'} = 0;

$sdramConfig{'sdcr'}{'val'} = (3 << 9)|(2 << 4);
$sdramConfig{'sdcr'}{'default'} = 0;
$sdramConfig{'sdcr'}{'addr'} = 0x08;


$sdramConfig{'sdcr'}{'nm'}{'val'} = 0;
$sdramConfig{'sdcr'}{'nm'}{'default'} = 0;
$sdramConfig{'sdcr'}{'nm'}{'mask'} = (0x1 << 14);
$sdramConfig{'sdcr'}{'nm'}{'shift'} = 14; 

$sdramConfig{'sdcr'}{'cl'}{'val'} = 3;
$sdramConfig{'sdcr'}{'cl'}{'default'} = 3;
$sdramConfig{'sdcr'}{'cl'}{'mask'} = (0x7 << 9);
$sdramConfig{'sdcr'}{'cl'}{'shift'} = 9;

$sdramConfig{'sdcr'}{'bit11_9lock'}{'val'} = 0;
$sdramConfig{'sdcr'}{'bit11_9lock'}{'default'} = 0;
$sdramConfig{'sdcr'}{'bit11_9lock'}{'mask'} = (0x1 << 8);
$sdramConfig{'sdcr'}{'bit11_9lock'}{'shift'} = 8;

$sdramConfig{'sdcr'}{'ibank'}{'val'} = 2;
$sdramConfig{'sdcr'}{'ibank'}{'default'} = 2;
$sdramConfig{'sdcr'}{'ibank'}{'mask'} = (0x7 << 4);
$sdramConfig{'sdcr'}{'ibank'}{'shift'} = 4;

$sdramConfig{'sdcr'}{'pagesize'}{'val'} = 0;
$sdramConfig{'sdcr'}{'pagesize'}{'default'} = 0;
$sdramConfig{'sdcr'}{'pagesize'}{'mask'} = (3 << 0);
$sdramConfig{'sdcr'}{'pagesize'}{'shift'} = 0;

$sdramConfig{'sdrcr'}{'val'} = 0x190;
$sdramConfig{'sdrcr'}{'default'} = 0x190;
$sdramConfig{'sdrcr'}{'addr'} = 0x0C;

$sdramConfig{'sdrcr'}{'rr'}{'val'} = 0;
$sdramConfig{'sdrcr'}{'rr'}{'default'} = 0x190;
$sdramConfig{'sdrcr'}{'rr'}{'mask'} = 0x1FFF;
$sdramConfig{'sdrcr'}{'rr'}{'shift'} = 0;

$sdramConfig{'sdtimr'}{'val'} = ((0x2<<20)|(1<<16)|(0xC<<12)|(0xF << 8));
$sdramConfig{'sdtimr'}{'default'} = (0x190 << 27)|(0x2<<20)|(1<<16)|(0xC<<12);
$sdramConfig{'sdtimr'}{'addr'} = 0x20;

$sdramConfig{'sdtimr'}{'t_rfc'}{'val'} = 0;
$sdramConfig{'sdtimr'}{'t_rfc'}{'default'} = 0;
$sdramConfig{'sdtimr'}{'t_rfc'}{'mask'} = (0x1F << 27);
$sdramConfig{'sdtimr'}{'t_rfc'}{'shift'} = 27;

$sdramConfig{'sdtimr'}{'t_rp'}{'val'} = 0;
$sdramConfig{'sdtimr'}{'t_rp'}{'default'} = 0;
$sdramConfig{'sdtimr'}{'t_rp'}{'mask'} = (0x7 << 24);
$sdramConfig{'sdtimr'}{'t_rp'}{'shift'} = 24;

$sdramConfig{'sdtimr'}{'t_rcd'}{'val'} = 2;
$sdramConfig{'sdtimr'}{'t_rcd'}{'default'} = 2;
$sdramConfig{'sdtimr'}{'t_rcd'}{'mask'} = (0x7 << 20);
$sdramConfig{'sdtimr'}{'t_rcd'}{'shift'} = 20;

$sdramConfig{'sdtimr'}{'t_wr'}{'val'} = 1;
$sdramConfig{'sdtimr'}{'t_wr'}{'default'} = 1;
$sdramConfig{'sdtimr'}{'t_wr'}{'mask'} = (0x7 << 16);
$sdramConfig{'sdtimr'}{'t_wr'}{'shift'} = 16;

$sdramConfig{'sdtimr'}{'t_ras'}{'val'} = 0xC;
$sdramConfig{'sdtimr'}{'t_ras'}{'default'} = 0xC;
$sdramConfig{'sdtimr'}{'t_ras'}{'mask'} = (0xF << 12);
$sdramConfig{'sdtimr'}{'t_ras'}{'shift'} = 12;

$sdramConfig{'sdtimr'}{'t_rc'}{'val'} = 0;
$sdramConfig{'sdtimr'}{'t_rc'}{'default'} = 0;
$sdramConfig{'sdtimr'}{'t_rc'}{'mask'} = (0xF << 8);
$sdramConfig{'sdtimr'}{'t_rc'}{'shift'} = 8;

$sdramConfig{'sdtimr'}{'t_rrd'}{'val'} = 0;
$sdramConfig{'sdtimr'}{'t_rrd'}{'default'} = 0;
$sdramConfig{'sdtimr'}{'t_rrd'}{'mask'} = (0x7 << 4);
$sdramConfig{'sdtimr'}{'t_rrd'}{'shift'} = 4;

$sdramConfig{'sdsretr'}{'val'} = 0x19;
$sdramConfig{'sdsretr'}{'default'} = 0x19;
$sdramConfig{'sdsretr'}{'addr'} = 0x3C;

$sdramConfig{'sdsretr'}{'t_xs'}{'val'} = 0;
$sdramConfig{'sdsretr'}{'t_xs'}{'default'} = 0x19;
$sdramConfig{'sdsretr'}{'t_xs'}{'mask'} = 0x1F;
$sdramConfig{'sdsretr'}{'t_xs'}{'shift'} = 0;

$asyncRamConfig{'awccr'}{'wp0'}{'shift'} = 28;
$asyncRamConfig{'awccr'}{'wp0'}{'mask'} = (0x1 << 28);
$asyncRamConfig{'awccr'}{'wp0'}{'default'} = 1;
$asyncRamConfig{'awccr'}{'wp0'}{'val'} = 1;


$asyncRamConfig{'awccr'}{'mewc'}{'shift'} = 0;
$asyncRamConfig{'awccr'}{'mewc'}{'mask'} = (0xFF << 0);
$asyncRamConfig{'awccr'}{'mewc'}{'default'} = 0x80;                                         
$asyncRamConfig{'awccr'}{'mewc'}{'val'} = 0x80; 
                                        
$asyncRamConfig{'awccr'}{'default'} = ((1 << 28) | (0x80));                                         
$asyncRamConfig{'awccr'}{'val'}     = ((1 << 28) | (0x80));                                         
                                        
$asyncRamConfig{'a1cr'}{'ss'}{'shift'}   = 31;
$asyncRamConfig{'a1cr'}{'ss'}{'mask'}    = (0x1 << 31);
$asyncRamConfig{'a1cr'}{'ss'}{'default'} = 0;
$asyncRamConfig{'a1cr'}{'ss'}{'val'} = 0;

$asyncRamConfig{'a1cr'}{'ew'}{'shift'}   = 30;
$asyncRamConfig{'a1cr'}{'ew'}{'mask'}    = (0x1 << 30);
$asyncRamConfig{'a1cr'}{'ew'}{'default'} = 0;
$asyncRamConfig{'a1cr'}{'ew'}{'val'} = 0;

$asyncRamConfig{'a1cr'}{'w_setup'}{'shift'}   = 26;
$asyncRamConfig{'a1cr'}{'w_setup'}{'mask'}    = (0xF << 26);
$asyncRamConfig{'a1cr'}{'w_setup'}{'default'} = 0xF;
$asyncRamConfig{'a1cr'}{'w_setup'}{'val'} = 0xF;

$asyncRamConfig{'a1cr'}{'w_strobe'}{'shift'}   = 20;
$asyncRamConfig{'a1cr'}{'w_strobe'}{'mask'}    = (0x3F << 20);
$asyncRamConfig{'a1cr'}{'w_strobe'}{'default'} = 0x3F;
$asyncRamConfig{'a1cr'}{'w_strobe'}{'val'}     = 0x3F;

$asyncRamConfig{'a1cr'}{'w_hold'}{'shift'}   = 17;
$asyncRamConfig{'a1cr'}{'w_hold'}{'mask'}    = (0x7 << 17);
$asyncRamConfig{'a1cr'}{'w_hold'}{'default'} = 0x7;
$asyncRamConfig{'a1cr'}{'w_hold'}{'val'}     = 0x7;

$asyncRamConfig{'a1cr'}{'r_setup'}{'shift'}   = 13;
$asyncRamConfig{'a1cr'}{'r_setup'}{'mask'}    = (0xF << 13);
$asyncRamConfig{'a1cr'}{'r_setup'}{'default'} = 0xF;
$asyncRamConfig{'a1cr'}{'r_setup'}{'val'}     = 0xF;

$asyncRamConfig{'a1cr'}{'r_strobe'}{'shift'}   = 7;
$asyncRamConfig{'a1cr'}{'r_strobe'}{'mask'}    = (0x3F << 7);
$asyncRamConfig{'a1cr'}{'r_strobe'}{'default'} = 0x3F;
$asyncRamConfig{'a1cr'}{'r_strobe'}{'val'} = 0x3F;

$asyncRamConfig{'a1cr'}{'r_hold'}{'shift'}   = 4;   
$asyncRamConfig{'a1cr'}{'r_hold'}{'mask'}    = (0x7 << 4);   
$asyncRamConfig{'a1cr'}{'r_hold'}{'default'} = 0x7;  
$asyncRamConfig{'a1cr'}{'r_hold'}{'val'}     = 0x7;  

$asyncRamConfig{'a1cr'}{'ta'}{'shift'}   = 2;
$asyncRamConfig{'a1cr'}{'ta'}{'mask'}    = (0x3 << 2);
$asyncRamConfig{'a1cr'}{'ta'}{'default'} = 0x3; 
$asyncRamConfig{'a1cr'}{'ta'}{'val'}     = 0x3; 

$asyncRamConfig{'a1cr'}{'asize'}{'shift'}   = 0;
$asyncRamConfig{'a1cr'}{'asize'}{'mask'}    = (0x3 << 0);
$asyncRamConfig{'a1cr'}{'asize'}{'default'} = 0;
$asyncRamConfig{'a1cr'}{'asize'}{'val'} = 0;

$asyncRamConfig{'a1cr'}{'default'} = 0x3FFFFFFC; 
$asyncRamConfig{'a1cr'}{'val'}     = 0x3FFFFFFC;  

$i2cClkCfg{'clkh'}{'val'} = 0;
$i2cClkCfg{'clkl'}{'val'} = 0;
$i2cClkCfg{'psc'}{'val'} = 0;
$i2cClkCfg{'highClock'}{'val'} = 0;
$i2cClkCfg{'lowClock'}{'val'} = 0;
$i2cClkCfg{'weight'}{'val'} = 3;


$i2cClkCfg{'clkh'}{'default'} = 0;
$i2cClkCfg{'clkl'}{'default'} = 0;
$i2cClkCfg{'psc'}{'default'} = 0;
$i2cClkCfg{'highClock'}{'default'} = '';
$i2cClkCfg{'lowClock'}{'default'} = '';
$i2cClkCfg{'weight'}{'default'} = 3;


# Parse command line arguments using standard built-in parser
$args = parseArguments(\@ARGV,
  -pkg => 'BGA',
  -o => 'boot',
);

$baseOutFileName = $args->{'-o'};
$outFile = $baseOutFileName.".cfg";
$cOutFile = $baseOutFileName.".c";

# Display help screen if denoted
#doHelp($args->{-h}, $helpText);


# Do main processing
doMain($args);
 
MainLoop();

exit();

# All done

#----------------------------------------------------------------------------------------------
# doMain() - Do all of the main processing here
#----------------------------------------------------------------------------------------------
sub doMain {

  my ($args)     = shift(@_);
  my ($i);
  my ($status)   = 0;

  $pkg = uc($args->{-pkg});
  


  $hWindowMain = MainWindow->new(
    -width => "36p",
    -title => "TMS320C672x Boot Configuration Tool v$VERSION",
  );

  $hWindowMain->minsize(qw(400 300));
  
  $hFrameButtons = $hWindowMain->Frame(
  )->pack(
    -side   => 'top',
    -anchor => 'nw',
    -pady   => 12,
    -fill => 'x',
  );
  
  my ($fileMenu) = 'File';
  $hFileOptions = $hFrameButtons->Menubutton(
    -text => 'File',
    -font => 'bold 12',
    -relief => 'groove',
  )->pack(
    -padx   => 8,
    -pady   => 4,
    -side  => 'left',
    -fill => 'x',
  );

  $hFileOptions->command(
               -label => 'New',
               -command => [\&fileOptions, 1, $hWindowMain],
               -activebackground => 'magenta',
             ); 
             
  $hFileOptions->command(
               -label => 'Open',
               -command => [\&fileOptions, 2, $hWindowMain],
               -activebackground => 'magenta',
             ); 
             
  $hFileOptions->command(
               -label => 'Save',
               -command => [\&fileOptions, 3, $hWindowMain],
               -activebackground => 'magenta',
             ); 
             
  $hFileOptions->command(
               -label => 'Save as ...',
               -command => [\&fileOptions, 4, $hWindowMain],
               -activebackground => 'magenta',
             ); 
             
  $hFileOptions->command(
               -label => 'Exit',
               -command => [\&fileOptions, 5, $hWindowMain],
               -activebackground => 'magenta',
             );              
                                                                             
             
  my($hLabelMain) = $hFrameButtons->Label(
    -fg => 'blue',
    -relief => 'sunken',
    -font => 'bold 12',
    -textvar => \$configVar,
  )->pack(
    -padx   => 8,
    -pady   => 8,
    -side => 'top',
    -fill => 'x',
  );

  displayConfigMenu($hWindowMain);
        
  my($balloon) = $hWindowMain->Balloon(
    -balloonposition => 'mouse',
  );


  return $status;
}


#----------------------------------------------------------------------------------------------
# Implement Actions from File Options PullDown Menu
#----------------------------------------------------------------------------------------------
sub fileOptions{
  my($opt) = shift(@_);
  my($win) = shift(@_);
  
  my($types) = [ ['Config Files', ['.cfg', '']],
                 ['Text Files',   ['.txt', '']],
               ];
  
  $start_dir = '.';
  if ($opt == 1) {
     $hFileSelect = $win->FileSelect(-directory => $start_dir,
                                    -create => 1,
                                    -filelabel => 'Enter File Name Below or Choose from List Above',
                                    -defaultextension=> '.cfg',
#                                    -background => 'cyan',
                                    -height => 10,
                                    -font => 'bold 20',
                                    -width => 25);
     $cfgFile = $hFileSelect->Show();
   }

   if ($opt == 2) {
   
       $cfgFile = $win->getOpenFile(-parent => $win, 
                                 -initialdir => $start_dir,
                                 -filetypes => $types,
                                ) if ($opt == 2);
	   importCfg($cfgFile);
   }                                
   
   $cfgFile = 'boot.cfg' if ($cfgFile  eq '');
   $configVar = 'Generate configration file ,' . $cfgFile;
          
  
   if ($opt == 3) 
   { 
	  genConfig($cfgFile);
   }	  
 
   if ($opt == 4) {
	  $hSaveFile= $win->getSaveFile(-parent => $win,
	                                -initialdir => $start_dir ,
	                                -filetypes => $types, 
	                                -defaultextension=> 'cfg');
	  if ($hSaveFile) {
         $configVar = 'Generate configration file ,' . $hSaveFile;	                                
	     genConfig($hSaveFile);
      }
   }
  
   if ($opt == 5) {
	   killWindow($win);
   }
  return;
}



#----------------------------------------------------------------------------------------------
# Import Data from a Previously Saved Configuration File *.cfg
#----------------------------------------------------------------------------------------------
sub importCfg {
	my($importFile) = shift(@_);
	my($iline);
	my($tlArgs);
	my($i);
	my($tmpLine);
	my(%args);
		
	 open(ICFG, "<$importFile") or die("Could not open file $importFile");
	 
	while ($iline = <ICFG>) {
	    # skip line if it begins with a comment
	    next if ($iline =~ m/^\s*\#/);
	    
	    # skip if blank line
	    $tmpLine = $iline;
	    $tmpLine =~ s/[\n\r\f]//g;
	    
	    next if ($tmpLine eq '');
	    
	    # Check for end of data marker
	    last if ($iline =~ m/^\s*<END>/);
	    # Remove trailing comment
	    $iline =~ s/\#.*//;
	    
	    # get test case name and options, skip line if it doesn't contain one	    
	    next if ($iline !~ m/^(\s*\-\s*\w*)*/);
	    $tlOptions = $iline;
	    # Merge options from tl file into args hash
	    $tlArgs = parseOptionsString($tlOptions,%$args);
	    %$args = (%$args, %$tlArgs);

    }
    
    # Check For All Imported Data, If Found set the value from Imported File
    # Otherwise set value to default
 
    $pllCfg{'int_osc'}{'val'} = ($tlArgs->{-pllcfgintosc}) ? oct($tlArgs->{-pllcfgintosc}) : $pllCfg{'int_osc'}{'default'};    
    $pllCfg{'osc'}{'val'} = ($tlArgs->{-pllcfgosc}) ? ($tlArgs->{-pllcfgosc}) : $pllCfg{'osc'}{'default'};
    $pllCfg{'cpu'}{'val'} = ($tlArgs->{-pllcfgcpu}) ? oct($tlArgs->{-pllcfgcpu}) : $pllCfg{'cpu'}{'default'};
    $pllCfg{'emif'}{'val'} = ($tlArgs->{-pllcfgemif}) ? oct($tlArgs->{-pllcfgemif}) : $pllCfg{'emif'}{'default'};
    $pllCfg{'weight'}{'val'} = ($tlArgs->{-pllcfgweight}) ? oct($tlArgs->{-pllcfgweight}) : $pllCfg{'weight'}{'default'};
    $pllCfg{'pllm'}{'val'} = ($tlArgs->{-pllcfgpllm}) ? oct($tlArgs->{-pllcfgpllm}) : $pllCfg{'pllm'}{'default'};
    $pllCfg{'div0'}{'val'} = ($tlArgs->{-pllcfgdiv0}) ? oct($tlArgs->{-pllcfgdiv0}) : $pllCfg{'div0'}{'default'};
    $pllCfg{'div1'}{'val'} = ($tlArgs->{-pllcfgdiv1}) ? oct($tlArgs->{-pllcfgdiv1}) : $pllCfg{'div1'}{'default'};
    $pllCfg{'div2'}{'val'} = ($tlArgs->{-pllcfgdiv2}) ? oct($tlArgs->{-pllcfgdiv2}) : $pllCfg{'div2'}{'default'};
    $pllCfg{'div3'}{'val'} = ($tlArgs->{-pllcfgdiv3}) ? oct($tlArgs->{-pllcfgdiv3}) : $pllCfg{'div3'}{'default'};
        

    $i2cClkCfg{'clkl'}{'val'} = ($tlArgs->{-i2cclkcfgclkl}) ? oct($tlArgs->{-i2cclkcfgclkl}) : $i2cClkCfg{'clkl'}{'default'};
    $i2cClkCfg{'clkh'}{'val'} = ($tlArgs->{-i2cclkcfgclkl}) ? oct($tlArgs->{-i2cclkcfgclkh}) : $i2cClkCfg{'clkh'}{'default'};
    $i2cClkCfg{'psc'}{'val'} = ($tlArgs->{-i2cclkcfgpsc}) ? oct($tlArgs->{-i2cclkcfgpsc}) : $i2cClkCfg{'psc'}{'default'};
    $i2cClkCfg{'lowClock'}{'val'} = ($tlArgs->{-i2cclkcfglowclock}) ? oct($tlArgs->{-i2cclkcfglowclock}) : $i2cClkCfg{'lowClock'}{'default'};
    $i2cClkCfg{'highClock'}{'val'} = ($tlArgs->{-i2cclkcfghighclock}) ? oct($tlArgs->{-i2cclkcfghighclock}) : $i2cClkCfg{'highClock'}{'default'};
    $i2cClkCfg{'weight'}{'val'} = ($tlArgs->{-i2cclkcfgweight}) ? oct($tlArgs->{-i2cclkcfgweight}) : $i2cClkCfg{'weight'}{'default'};
   
    $sdramConfig{'sdcr'}{'val'} =($tlArgs->{-sdramSDCR}) ? oct(($tlArgs->{-sdramSDCR})) : $sdramConfig{'sdcr'}{'default'};
    $sdramConfig{'sdrcr'}{'val'} = ($tlArgs->{-sdramSDRCR}) ? oct(($tlArgs->{-sdramSDRCR})) : $sdramConfig{'sdrcr'}{'default'};
    $sdramConfig{'sdtimr'}{'val'} = ($tlArgs->{-sdramSDTIMR}) ? oct(($tlArgs->{-sdramSDTIMR})) : $sdramConfig{'sdtimr'}{'default'};
    $sdramConfig{'sdsretr'}{'val'} = ($tlArgs->{-sdramSDSRETR}) ? oct(($tlArgs->{-sdramSDSRETR})) : $sdramConfig{'sdsretr'}{'default'};
       
	$asyncRamConfig{'a1cr'}{'val'} = 
	        ($tlArgs->{-asyncRamA1CR}) ? oct(($tlArgs->{-asyncRamA1CR})) : $asyncRamConfig{'a1cr'}{'default'}; 
	$asyncRamConfig{'awccr'}{'val'} =    
 	        ($tlArgs->{-asyncRamAWCCR}) ? oct(($tlArgs->{-asyncRamAWCCR})) : $asyncRamConfig{'awccr'}{'default'}; 
   
 	        
 	$addressPinCfg[0] =  ($tlArgs->{-pin0}) ? ($tlArgs->{-pin0}) : 'Not Mapped'; 
 	$addressPinCfg[1] =  ($tlArgs->{-pin1}) ? ($tlArgs->{-pin1}) : 'Not Mapped'; 
 	$addressPinCfg[2] =  ($tlArgs->{-pin2}) ? ($tlArgs->{-pin2}) : 'Not Mapped'; 
 	$addressPinCfg[3] =  ($tlArgs->{-pin3}) ? ($tlArgs->{-pin3}) : 'Not Mapped'; 
 	$addressPinCfg[4] =  ($tlArgs->{-pin4}) ? ($tlArgs->{-pin4}) : 'Not Mapped'; 
 	$addressPinCfg[5] =  ($tlArgs->{-pin5}) ? ($tlArgs->{-pin5}) : 'Not Mapped'; 
 	$addressPinCfg[6] =  ($tlArgs->{-pin6}) ? ($tlArgs->{-pin6}) : 'Not Mapped'; 
 	$addressPinCfg[7] =  ($tlArgs->{-pin7}) ? ($tlArgs->{-pin7}) : 'Not Mapped'; 
 	$addressPinCfg[8] =  ($tlArgs->{-pin8}) ? ($tlArgs->{-pin8}) : 'Not Mapped'; 
 	$addressPinCfg[9] =  ($tlArgs->{-pin9}) ? ($tlArgs->{-pin9}) : 'Not Mapped'; 
 	$addressPinCfg[10] =  ($tlArgs->{-pin10}) ? ($tlArgs->{-pin10}) : 'Not Mapped'; 
 	$addressPinCfg[11] =  ($tlArgs->{-pin11}) ? ($tlArgs->{-pin11}) : 'Not Mapped'; 
 	$addressPinCfg[12] =  ($tlArgs->{-pin12}) ? ($tlArgs->{-pin12}) : 'Not Mapped'; 
 	$addressPinCfg[13] =  ($tlArgs->{-pin13}) ? ($tlArgs->{-pin13}) : 'Not Mapped'; 
 	$addressPinCfg[14] =  ($tlArgs->{-pin14}) ? ($tlArgs->{-pin14}) : 'Not Mapped'; 
 	$addressPinCfg[15] =  ($tlArgs->{-pin15}) ? ($tlArgs->{-pin15}) : 'Not Mapped'; 
 	$addressPinCfg[16] =  ($tlArgs->{-pin16}) ? ($tlArgs->{-pin16}) : 'Not Mapped'; 
 	$addressPinCfg[17] =  ($tlArgs->{-pin17}) ? ($tlArgs->{-pin17}) : 'Not Mapped'; 
 	$addressPinCfg[18] =  ($tlArgs->{-pin18}) ? ($tlArgs->{-pin18}) : 'Not Mapped'; 
 	$addressPinCfg[19] =  ($tlArgs->{-pin19}) ? ($tlArgs->{-pin19}) : 'Not Mapped'; 
    
 	
    for($i=0;$i<20;$i++) 
    {
	    $tmpPinCfg[$i] = $addressPinCfg[$i];
    }  
    
    $importData  = 1;
    printf "Importing data \n";
    $useAddressLatch = ($tlArgs->{-useAddressLatch}) ? oct($tlArgs->{-useAddressLatch}) : 0;
    $pinsConfigured = ($tlArgs->{-pinCfg}) ? oct($tlArgs->{-pinCfg}) : 0;
    $pllConfigured = ($tlArgs->{-pllCfg}) ? oct($tlArgs->{-pllCfg}) : 0;
    $i2cClkConfigured = ($tlArgs->{-i2cClkCfg}) ? oct($tlArgs->{-i2cClkCfg}) : 0;
    $sdramConfigured = ($tlArgs->{-sdramCfg}) ? oct($tlArgs->{-sdramCfg}) : 0;
    $asyncRamConfigured = ($tlArgs->{-asyncRamCfg}) ? oct($tlArgs->{-asyncRamCfg}) : 0;
    
    
    return;	 
}

#----------------------------------------------------------------------------------------------
# Generate Configuration Files, *.cfg and *cfg.c
#----------------------------------------------------------------------------------------------
sub genConfig{
   my($outFile) = shift(@_);
   my($cOutFile) = $outFile;
   my($pinMaster);
   my($pinCount) = 0;

   
   $cOutFile =~ s/(\.cfg)//;
   $cOutFile = $cOutFile."cfg.c";
   
     open($CFG, ">$outFile") || die ("Could not open file, $outFile, for writing");
     open($CFGC, ">$cOutFile") || die("Could not open file, $cOutFile for writing");
     
     genHeaders($CFGC,$cOutFile,$CFG,$outFile);
 
	 genBootSetupFunc($CFGC);
	    
     genPllCfg($CFG,$pllConfigured);
     genPllSetupFunc($CFGC,$pllConfigured);
	     
     genI2cClkCfg($CFG,$i2cClkConfigured);
     genI2cClkSetupFunc($CFGC,$i2cClkConfigured);
     	    	     
	 genSdramSetupFunc($CFGC,$sdramConfigured);
	 genSdramCfg($CFG,$sdramConfigured);
	    
	 genAsyncRamSetupFunc($CFGC,$asyncRamConfigured);
	 genAsyncRamCfg($CFG,$asyncRamConfigured);
	 
     if ($pinsConfigured == 1) {
	     $pinMaster = BuildPinCfgList->new(); 
	     $pinCount = genPinCfg($CFG,$pinsConfigured,$pinMaster);
         BuildPinCfgList->delete($pinMaster);
	 } 

	 close($CFG);
	 
	 printf $CFGC "\n";   # make sure we have at least one new line for CCS
	 
	 close($CFGC);
     
  return;
}

#----------------------------------------------------------------------------------------------
# Gen Boot Setup Func for cfg.c file
#----------------------------------------------------------------------------------------------
sub genBootSetupFunc{
	my($CFGC) = shift(@_);
    my($i);
    
	     printf $CFGC "//===================================================================//\n";
	     printf $CFGC "// Function Prototypes                                               //\n";
	     printf $CFGC "//===================================================================//\n";
	     
         printf $CFGC "far void TIBootPllCfg(void);\n" if ($pllConfigured);
         printf $CFGC "far void TIBootI2cClkCfg(void);\n" if ($i2cClkConfigured);
         printf $CFGC "far void TIBootAsyncRamCfg(void);\n" if ($asyncRamConfigured);
         printf $CFGC "far void TIBootSdramCfg(void);\n" if ($sdramConfigured);
         printf $CFGC "\n\n";
    
	     printf $CFGC "//===================================================================//\n";
	     printf $CFGC "// Boot Confguration Setup Function                                  //\n";
	     printf $CFGC "//    This code along with PLL Configuration, SDRAM Configuration    //\n";
	     printf $CFGC "//    ASYC RAM Configuration, I2C Clock Configuration, will be       //\n";
	     printf $CFGC "//    loaded first. A branch wil then be executed after load of      //\n";
	     printf $CFGC "//     all boot configuration code to the bootSetup function.        //\n";
	     printf $CFGC "//     After the boot setup has been performed, normal AIS           //\n";
	     printf $CFGC "//     processing will continue at that point.                       //\n";
	     printf $CFGC "//===================================================================//\n";
	     printf $CFGC "                                                                       \n";
	     printf $CFGC "#pragma CODE_SECTION(TIBootSetup,\".TIBoot\")\n";
	     printf $CFGC "void TIBootSetup(void) {\n";
	     printf $CFGC "\n";
	     
		 printf $CFGC "   TIBootPllCfg();\n" if ($pllConfigured);
	     printf $CFGC "   TIBootI2cClkCfg();\n" if ($i2cClkConfigured);
	     printf $CFGC "   TIBootSdramCfg();\n" if ($sdramConfigured);
	     printf $CFGC "   TIBootAsyncRamCfg();\n" if ($asyncRamConfigured);
	     
         printf $CFGC "}\n\n";
         

	return;
}
		
#----------------------------------------------------------------------------------------------
# Gen Pin Configuration for .cfg file
#----------------------------------------------------------------------------------------------
sub genPinCfg{
	my($CFG) = shift(@_);
	my($flag) = shift(@_);
	my($pinMaster) = shift(@_);
    my($pinCount) = 0;
    my($i,$j);
    my($numSets) = 0;
    my($pinName);
    	
	if ($flag == 1) {
		
	     printf $CFG  "#====================================================================\n";
	     printf $CFG  "# Address Pin Configuration\n";
	     printf $CFG  "#====================================================================\n";
	     
	     printf $CFG " -pinCfg 0x1\n";
		 printf $CFG " -useAddressLatch 0x%08X\n", $useAddressLatch;
	 
	     for($i=0;$i <= 24 - $numEmifPins;++$i) {
		     printf $CFG "# Configuring pin #%d, name :%s:\n",$i, $tmpPinCfg[$i];
		     if (($tmpPinCfg[$i] ne 'Not Mapped') && ($tmpPinCfg[$i] ne '')) {
			     printf $CFG " -pin%-2d %-10s\n", $i, $tmpPinCfg[$i];
			     ++$pinCount;                  	
	         }
	     }
         printf $CFG " -pincount 0x%x\n",$pinCount;
         
		 for($i=0; $i < $pinCount; ++$i) {
		    if ($tmpPinCfg[$i] ne 'Not Mapped') {
			     $pinName = sprintf("%s",$tmpPinCfg[$i]);
			     printf $CFG " -pinEnableReg%-2d          0x%08X\n", $i, $pinMaster->{'pins'}{$pinName}{'pinEnableRegister'};
			     printf $CFG " -pinEnableMask%-2d         0x%08X\n", $i, $pinMaster->{'pins'}{$pinName}{'pinEnableMask'};
			     printf $CFG " -pinEnableMaskMode%-2d     0x%08X\n", $i, $pinMaster->{'pins'}{$pinName}{'enableMaskMode'};
			     printf $CFG " -pinDirectionReg%-2d       0x%08X\n", $i, $pinMaster->{'pins'}{$pinName}{'pinDirectionRegister'};
			     printf $CFG " -pinDirectionMask%-2d      0x%08X\n", $i, $pinMaster->{'pins'}{$pinName}{'pinDirectionMask'};
			     printf $CFG " -pinDirectionMaskMode%-2d  0x%08X\n", $i, $pinMaster->{'pins'}{$pinName}{'directionMaskMode'};			    
			     printf $CFG " -pinSetReg%-2d             0x%08X\n", $i, $pinMaster->{'pins'}{$pinName}{'pinSetRegister'};
			     printf $CFG " -pinSetMask%-2d            0x%08X\n", $i, $pinMaster->{'pins'}{$pinName}{'pinSetMask'};
			     printf $CFG " -pinSetMode%-2d            0x%08X\n", $i, $pinMaster->{'pins'}{$pinName}{'setMaskMode'};			     
				 printf $CFG " -pinClearReg%-2d           0x%08X\n", $i, $pinMaster->{'pins'}{$pinName}{'pinClearRegister'};
			     printf $CFG " -pinClearMask%-2d          0x%08X\n", $i, $pinMaster->{'pins'}{$pinName}{'pinClearMask'};
			     printf $CFG " -pinClearMode%-2d          0x%08X\n", $i, $pinMaster->{'pins'}{$pinName}{'clearMaskMode'};
			     printf $CFG " -pinDisableReg%-2d         0x%08X\n", $i, $pinMaster->{'pins'}{$pinName}{'pinDisableRegister'};
			     printf $CFG " -pinDisableMask%-2d        0x%08X\n", $i, $pinMaster->{'pins'}{$pinName}{'pinDisableMask'};
			     printf $CFG " -pinDisableMaskMode%-2d    0x%08X\n", $i, $pinMaster->{'pins'}{$pinName}{'disableMaskMode'};
				 $numSets = $pinMaster->{'pins'}{$pinName}{'globalSetupFlag'};
			     printf $CFG " -pinGlobalSetupFlag%-2d    0x%08X\n", $i, $numSets;
				 for($j=0; $j < $numSets ; ++$j) {
			        printf $CFG " -pinRegAddr%d_%-2d      0x%08X\n", $i, $j,
			        $pinMaster->{'pins'}{$pinName}{'globalSetup'}[$j]{'regAddr'};
			        printf $CFG " -pinRegVal%d_%-2d       0x%08X\n", $i, $j,
			        $pinMaster->{'pins'}{$pinName}{'globalSetup'}[$j]{'regVal'};			                
			        printf $CFG " -pinRegSetMode%d_%-2d   0x%08X\n", $i, $j,
			        $pinMaster->{'pins'}{$pinName}{'globalSetup'}[$j]{'regSetMode'};
		         }
		     }	
		 }		 
         printf $CFG "\n";
         	
	}else{
	     printf $CFG  "#====================================================================\n";
	     printf $CFG  "# Address Pin Configuration\n";
	     printf $CFG  "#====================================================================\n";
	     
	     printf $CFG " -pinCfg 0x0\n";
		 printf $CFG " -useAddressLatch 0x0\n";
		 printf $CFG "\n";		
	}
	
 	printf $CFG  "#====================================================================\n";
	printf $CFG  "# Address Pin Configuration\n";
	printf $CFG  "#====================================================================\n";  
	printf $CFG  " -pkgType %-6s\n",$pkg;
	printf $CFG  "\n";
  
	
	return $pinCount;
}	
	
#----------------------------------------------------------------------------------------------
# Gen ASYNC RAM Configuration for .cfg file
#----------------------------------------------------------------------------------------------
sub genAsyncRamCfg{
	
	my($CFG) = shift(@_);
	my($flag) = shift(@_);
	
	if ($flag == 1) {
	   printf $CFG  "#====================================================================\n";
	   printf $CFG  "# ASYNC Ram Configuration\n";
	   printf $CFG  "#====================================================================\n";
	   printf $CFG  " -asyncRamCfg 0x1\n";
	   printf $CFG  " -asyncRamA1CR  0x%08X\n", $asyncRamConfig{'a1cr'}{'val'};
 	   printf $CFG  " -asyncRamAWCCR 0x%08X\n", $asyncRamConfig{'awccr'}{'val'};	
 	   printf $CFG "\n";
	}else{
	   printf $CFG  "#====================================================================\n";
	   printf $CFG  "# ASYNC Ram Configuration\n";
	   printf $CFG  "#====================================================================\n";
	   printf $CFG  " -asyncRamCfg 0x0\n";	
	   printf $CFG "\n";
    }	
}


#----------------------------------------------------------------------------------------------
# Gen ASYNC RAM Setup Function for cfg.c file
#----------------------------------------------------------------------------------------------
sub genAsyncRamSetupFunc{
    my($CFGC) = shift(@_);
	my($flag) = shift(@_);
	
	if ($flag == 1) {
	     printf $CFGC "//===================================================================//\n";
	     printf $CFGC "// ASYNC Ram Configuration                                           //\n";
	     printf $CFGC "//    Asynchrounous 1 Configuration Register:                        //\n";
	     printf $CFGC "//        register mask: 0x%08X                                  //\n",$asyncRamConfig{'a1cr'}{'val'};
	     printf $CFGC "//                   SS: %-10d                                  //\n", $asyncRamConfig{'a1cr'}{'ss'}{'val'};
	     printf $CFGC "//                   EW: %-10d                                  //\n", $asyncRamConfig{'a1cr'}{'ew'}{'val'};
	     printf $CFGC "//              W_SETUP: %-10d                                  //\n", $asyncRamConfig{'a1cr'}{'w_setup'}{'val'};
	     printf $CFGC "//             W_STROBE: %-10d                                  //\n", $asyncRamConfig{'a1cr'}{'w_strobe'}{'val'};
	     printf $CFGC "//               W_HOLD: %-10d                                  //\n", $asyncRamConfig{'a1cr'}{'w_hold'}{'val'};
	     printf $CFGC "//              R_SETUP: %-10d                                  //\n", $asyncRamConfig{'a1cr'}{'r_setup'}{'val'};
	     printf $CFGC "//             R_STROBE: %-10d                                  //\n", $asyncRamConfig{'a1cr'}{'r_strobe'}{'val'};
	     printf $CFGC "//               R_HOLD: %-10d                                  //\n", $asyncRamConfig{'a1cr'}{'r_hold'}{'val'};
	     printf $CFGC "//                   TA: %-10d                                  //\n", $asyncRamConfig{'a1cr'}{'ta'}{'val'};
	     printf $CFGC "//                ASIZE: %-10d                                  //\n", $asyncRamConfig{'a1cr'}{'asize'}{'val'};
         printf $CFGC "//                                                                   //\n";
         printf $CFGC "//    Asynchronous Wait Cycle Configuration Register                 //\n";
         printf $CFGC "//        register mask: 0x%08X                                  //\n", $asyncRamConfig{'awccr'}{'val'};
         printf $CFGC "//                  WP0: %-10d                                  //\n", $asyncRamConfig{'awccr'}{'wp0'}{'val'};
         printf $CFGC "//                 MEWC: %-10d                                  //\n", $asyncRamConfig{'awccr'}{'mewc'}{'val'};
	     printf $CFGC "//===================================================================//\n";
         printf $CFGC "\n";
         printf $CFGC "#pragma CODE_SECTION(TIBootAsyncRamCfg,\".TIBoot\")\n";
         printf $CFGC "void TIBootAsyncRamCfg()\n";
         printf $CFGC "{\n";
	     printf $CFGC "   *(volatile unsigned int *)TIBOOT_EMIF_AWCCR = 0x%08Xu;\n",$asyncRamConfig{'awccr'}{'val'};
	     printf $CFGC "   *(volatile unsigned int *)TIBOOT_EMIF_A1CR = 0x%08Xu;\n",$asyncRamConfig{'a1cr'}{'val'};
         printf $CFGC "}\n";	     	     
	     printf $CFGC "\n\n\n";	
	}
	
	return;
}



#----------------------------------------------------------------------------------------------
# Gen SDRAM Setup Function for cfg.c file
#----------------------------------------------------------------------------------------------
sub genSdramCfg{
	
	my($CFG) = shift(@_);
	my($flag) = shift(@_);
	
	if ($flag == 1) {
	   printf $CFG  "#====================================================================\n";
	   printf $CFG  "# SDRAM Configuration\n";
	   printf $CFG  "#====================================================================\n";
       printf $CFG  " -sdramCfg 1\n";
	   printf $CFG  " -sdramSDCR     0x%08X\n",$sdramConfig{'sdcr'}{'val'};
       printf $CFG  " -sdramSDRCR    0x%08X\n",$sdramConfig{'sdrcr'}{'val'};
       printf $CFG  " -sdramSDTIMR   0x%08X\n",$sdramConfig{'sdtimr'}{'val'};
       printf $CFG  " -sdramSDSRETR  0x%08X\n",$sdramConfig{'sdsretr'}{'val'};
       printf $CFG  "\n";
   } else {
	   printf $CFG  "#====================================================================\n";
	   printf $CFG  "# SDRAM Configuration\n";
	   printf $CFG  "#====================================================================\n";
       printf $CFG  " -sdramCfg 0\n";	
       printf $CFG  "\n";
   }    		
	
   return;
}





#----------------------------------------------------------------------------------------------
# Gen SDRAM Setup Function for cfg.c file
#----------------------------------------------------------------------------------------------
sub genSdramSetupFunc{
	
	my($CFGC) = shift(@_);
	my($flag) = shift(@_);
	
	if ($flag == 1) {
	    printf $CFGC "//===================================================================//\n";
	    printf $CFGC "// SDRAM Configuration:                                              //\n";
	    printf $CFGC "//    SDRAM Control Register:                                        //\n";
	    printf $CFGC "//       register mask: 0x%08X                                   //\n", $sdramConfig{'sdcr'}{'val'};
	    printf $CFGC "//          Narrow Mode : %-10d                                 //\n", $sdramConfig{'sdcr'}{'nm'}{'val'};
	    printf $CFGC "//          CAS latency : %-10d                                 //\n", $sdramConfig{'sdcr'}{'cl'}{'val'} ;
	    printf $CFGC "//          CAS latency write enable : %-10d                    //\n", $sdramConfig{'sdcr'}{'bit11_9lock'}{'val'};
	    printf $CFGC "//          Internal Bank Size: %-10d                           //\n", $sdramConfig{'sdcr'}{'ibank'}{'val'};
	    printf $CFGC "//          Page Size: %-10d                                    //\n", $sdramConfig{'sdcr'}{'pagesize'}{'val'};           
	    printf $CFGC "//                                                                   //\n";
	    printf $CFGC "//    SDRAM Refresh Control Register                                 //\n";
	    printf $CFGC "//        register mask: 0x%08X                                  //\n", $sdramConfig{'sdrcr'}{'val'};
	    printf $CFGC "//           Refresh Rate : %-10d                               //\n", $sdramConfig{'sdrcr'}{'rr'}{'val'};
	    printf $CFGC "//                                                                   //\n";
	    printf $CFGC "//    SDRAM Timing Register                                          //\n";
	    printf $CFGC "//        register mask: 0x%08X                                  //\n", $sdramConfig{'sdtimr'}{'val'};
	    printf $CFGC "//           T_RFC : %-10d                                      //\n", $sdramConfig{'sdtimr'}{'t_rfc'}{'val'};
	    printf $CFGC "//           T_RP  : %-10d                                      //\n", $sdramConfig{'sdtimr'}{'t_rp'}{'val'};
	    printf $CFGC "//           T_RCD : %-10d                                      //\n", $sdramConfig{'sdtimr'}{'t_rcd'}{'val'};
	    printf $CFGC "//           T_RAS : %-10d                                      //\n", $sdramConfig{'sdtimr'}{'t_ras'}{'val'};
	    printf $CFGC "//           T_RC  : %-10d                                      //\n", $sdramConfig{'sdtimr'}{'t_rc'}{'val'};
	    printf $CFGC "//           T_RRD : %-10d                                      //\n", $sdramConfig{'sdtimr'}{'t_rrd'}{'val'};
        printf $CFGC "//                                                                   //\n";
        printf $CFGC "//    SDRAM Self-refresh Exit Timing Register                        //\n";
        printf $CFGC "//        register mask: 0x%08X                                  //\n",$sdramConfig{'sdsretr'}{'val'};
        printf $CFGC "//           T_XS  : %-10d                                      //\n",$sdramConfig{'sdsretr'}{'t_xs'}{'val'};
	    printf $CFGC "//===================================================================//\n";
	    printf $CFGC "\n\n";
        printf $CFGC "\n";
        printf $CFGC "\n";
        printf $CFGC "\#pragma CODE_SECTION(TIBootSdramCfg, \".TIBoot\")\n";
        printf $CFGC "\n";
        printf $CFGC "void TIBootSdramCfg(void)\n";
        printf $CFGC "{\n"; 
        printf $CFGC "\n";
        printf $CFGC "   unsigned int i;\n";
	    printf $CFGC "   unsigned int x = 0;\n";
	    printf $CFGC "\n";
	    printf $CFGC "/* 1. Set SR bit to 1 */\n";
	    printf $CFGC "   *(volatile unsigned int *)TIBOOT_EMIF_SDCR |= 0x80000000;\n";
	    printf $CFGC "\n";
        printf $CFGC "// Assume PLL has already been configured for proper EM_CLK cycles\n";
	    printf $CFGC "// 2. Set SDRAM Timing Register\n";                    
	    printf $CFGC "   *(volatile unsigned int *)TIBOOT_EMIF_SDTIMR = 0x%08X;\n",$sdramConfig{'sdtimr'}{'val'};
	    printf $CFGC "// 3. Set SDRAM Self-Refresh Exit Timing Register\n";
	    printf $CFGC "\n";
	    printf $CFGC "   *(volatile unsigned int *)TIBOOT_EMIF_SDSRETR = 0x%08X;\n",$sdramConfig{'sdsretr'}{'val'};
	    printf $CFGC "// 4.  Set SDRAM Refresh Control Register\n";
	    printf $CFGC "   *(volatile unsigned int *)TIBOOT_EMIF_SDRCR = 0x%08X;\n",$sdramConfig{'sdrcr'}{'val'};
	    printf $CFGC "\n";
	    printf $CFGC "// 5. Set SDRAM Control Register\n";
	    printf $CFGC "   *(volatile unsigned int *)TIBOOT_EMIF_SDCR = 0x%08X;\n",$sdramConfig{'sdcr'}{'val'};
	    printf $CFGC "\n";
	    printf $CFGC "// 6. Clear SR bit\n";
	    printf $CFGC "   *(volatile unsigned int *)TIBOOT_EMIF_SDCR &= 0xEFFFFFFF;\n";
	    printf $CFGC "\n";
	    printf $CFGC "// 7. Read one word of SDRAM to insure config is set\n";
	    printf $CFGC "\n";
	    printf $CFGC "    for(i=0; ((i<= 0x%08X)&&(x!=0xFEEDBABE)); ++i) {\n",$sdramConfig{'sdsretr'}{'val'};
		printf $CFGC "       *(volatile unsigned int *)(0x80000000) = 0xFEEDBABE;\n";
	    printf $CFGC "       x = *(volatile unsigned int *)(0x80000000);\n";
	    printf $CFGC "    }\n";
        printf $CFGC "\n";
        printf $CFGC "}\n";	 
        printf $CFGC "\n\n\n";     
     } 

    return;	   
}    
     
       
#----------------------------------------------------------------------------------------------
# Gen Pll Setup Function for cfg.c file
#----------------------------------------------------------------------------------------------
sub genPllSetupFunc{
	
	my($CFG) = shift(@_);
	my($flag) = shift(@_);
	
	if ($flag == 1) {
		my($wait_for_lock) = int($pllCfg{'osc'}{'val'} * 187.5) + 100;
	    my($wait_for_setup)= int($pllCfg{'osc'}{'val'} * 0.125) + 5;       

        printf $CFGC "//===================================================================//\n";
	    printf $CFGC "// PLL Configuration                                                 //\n";
	    printf $CFGC "//    Input Oscillator Frequency: %6.2f                             //\n",$pllCfg{'osc'}{'val'};
	    printf $CFGC "//    Cpu Clock Frequency       : %6.2f                             //\n",$pllCfg{'cpu'}{'val'};
	    printf $CFGC "//    Emif Clock Frequency      : %6.2f                             //\n",$pllCfg{'emif'}{'val'};
	    printf $CFGC "//                      PLLM    : %-3d                                //\n",$pllCfg{'pllm'}{'val'};
	    printf $CFGC "//                      DIV0    : %-3d                                //\n",$pllCfg{'div0'}{'val'};
	    printf $CFGC "//                      DIV1    : %-3d                                //\n",$pllCfg{'div1'}{'val'};
	    printf $CFGC "//                      DIV2    : %-3d                                //\n",$pllCfg{'div2'}{'val'};
	    printf $CFGC "//                      DIV3    : %-3d                                //\n",$pllCfg{'div3'}{'val'};
	    printf $CFGC "//===================================================================//\n";		
        printf $CFGC  "#pragma CODE_SECTION(TIBootPllCfg, \".TIBoot\")\n";
        printf $CFGC  "far void TIBootPllCfg(void)\n";
        printf $CFGC  "{\n";
        printf $CFGC  "   int i;\n";
        printf $CFGC  "// configure the PLL  //\n";
        printf $CFGC  "\n";
        printf $CFGC  "// Make sure SDRAM is in Self-Refresh mode before setting PLL //\n";
        printf $CFGC  "// By setting SR bit in EMIF SDCR register to 1               //\n";
        printf $CFGC  "\n";
        printf $CFGC  "   *(volatile unsigned int *)TIBOOT_EMIF_SDCR |= 0x80000000;\n";
	    printf $CFGC  "\n";     
	    printf $CFGC  "// 1. In PLLCSR, write PLLEN = 0 (bypass mode) //\n";
	    printf $CFGC  "*(volatile unsigned int *)TIBOOT_PLL_PLLCSR &= ~TIBOOT_PLLDISABLE;\n";
	    printf $CFGC  "\n";
	    printf $CFGC  "// 2. Wait 4 cycles of the slowest of PLLOUT or reference";
	    printf $CFGC  "// clock source (CLKIN or OSCIN)\n";
	    printf $CFGC  "   asm(\"\t nop 4\");\n";
	    printf $CFGC  "\n";
	    printf $CFGC  "// 3. In PLLCSR, write PLLRST = 1 (PLL is reset) \n";
	    printf $CFGC  "   *(volatile unsigned int *)TIBOOT_PLL_PLLCSR = TIBOOT_PLLDISABLE | TIBOOT_PLLRESET;\n";
	    printf $CFGC  "\n";
	    printf $CFGC  "// 4. If necessary, program PLLDIV0 and PLLM \n";
        printf $CFGC  "// DIV0 - Before PLL(set to/1)               \n";
	    printf $CFGC  "   *(volatile unsigned int *)TIBOOT_PLL_PLLDIV0 = TIBOOT_DIVENABLED | 0x%08X;\n",$pllCfg{'div0'}{'val'};
	    printf $CFGC  "   *(volatile unsigned int *)TIBOOT_PLL_PLLM = 0x%08X;\n",$pllCfg{'pllm'}{'val'};
	    printf $CFGC  "\n";
	    printf $CFGC  "// 5. If necessary, program PLLDIV1-n. Note that you must apply the GO operation to\n"; 
	    printf $CFGC  "//   change these dividers to new ratios. \n";
	    printf $CFGC  "//   DIV1 - After PLL- SYSCLK1 DSP Core\n";
	    printf $CFGC  "//   DIV2 - After PLL- SYSCLK2 PERIPHS (Always twice DIV3)\n";
	    printf $CFGC  "//   DIV3 - After PLL- SYSCLK3 EMIF CLOCK\n";
	    printf $CFGC  "   *(volatile unsigned int *)TIBOOT_PLL_PLLDIV1 = TIBOOT_DIVENABLED | 0x%08X;\n",
	                       $pllCfg{'div1'}{'val'};
	    printf $CFGC  "   asm(\"\t nop 4\");\n";
	    printf $CFGC  "   asm(\"\t nop 4\");\n";
	    printf $CFGC  "\n";
	    printf $CFGC  "   *(volatile unsigned int *)TIBOOT_PLL_PLLDIV2 = TIBOOT_DIVENABLED | 0x%08X;\n",$pllCfg{'div2'}{'val'};
	    printf $CFGC  "   asm(\"\t nop 4\");\n";
	    printf $CFGC  "   asm(\"\t nop 4\");\n";
	    printf $CFGC  "\n";                 
	    printf $CFGC  "   *(volatile unsigned int *)TIBOOT_PLL_PLLDIV3 = TIBOOT_DIVENABLED | 0x%08X;\n",$pllCfg{'div3'}{'val'};
	    printf $CFGC  "\n";
	    printf $CFGC  "// Enable PLL Align control.\n"; 
	    printf $CFGC  "   *(volatile unsigned int *)TIBOOT_PLL_PLLALNCTL = TIBOOT_PLLALN1 | TIBOOT_PLLALN2 | TIBOOT_PLLALN3;\n";
	    printf $CFGC  "   *(volatile unsigned int *)TIBOOT_PLL_PLLCMD = TIBOOT_PLLGOSET;\n";
	    printf $CFGC  "\n";
	    printf $CFGC  "   while (*(volatile unsigned int *)TIBOOT_PLL_PLLSTAT == TIBOOT_PLLGOWAIT){\n";
	    printf $CFGC  "      *(volatile unsigned int *)TIBOOT_PLL_PLLCMD = TIBOOT_PLLGOCLR;\n";
	    printf $CFGC  "   }\n\n";
        printf $CFGC  "	// 6. Wait for PLL to properly reset\n"; 
        printf $CFGC  " //    Reset wait time is 125 ns\n";
	    printf $CFGC  "     for(i=0; i< %d;++i) {};\n", $wait_for_setup;

	    printf $CFGC  "\n";
	    printf $CFGC  "// 7. In PLLCSR, write PLLRST = 0 to bring PLL out of reset\n";
	    printf $CFGC  "   *(volatile unsigned int *)TIBOOT_PLL_PLLCSR = TIBOOT_PLLDISABLE | TIBOOT_PLLRESETRELEASE;\n";
	    printf $CFGC  "// 8. Wait for PLL to lock \n";
	    printf $CFGC  "    for(i=0; i< %d;++i) {};\n", $wait_for_lock;

	    printf $CFGC  "\n";
	    printf $CFGC  "// 9. In PLLCSR, write PLLEN = 1 to enable PLL mode \n";
	    printf $CFGC  "   *(volatile unsigned int *)TIBOOT_PLL_PLLCSR = TIBOOT_PLLENABLE | TIBOOT_PLLRESETRELEASE;\n";
	    printf $CFGC  "    for(i=0; i < %d; ++i) {};\n", $wait_for_lock;
	    printf $CFGC  "\n";
	    printf $CFGC  "// 10. Wait for Lock bit to become 1 \n";
	    printf $CFGC  "   while ( ((*(volatile unsigned int *)TIBOOT_PLL_PLLCSR) & TIBOOT_PLLLOCKED) == 0 )\n";
	    printf $CFGC  "   {\n";
	    printf $CFGC  "   }\n"; 
	    printf $CFGC  "\n";
	    printf $CFGC  "// ---- done PLL Programation ---- \n";
	    printf $CFGC  "\n";
	    printf $CFGC  "// take CFG bridge out of reset\n";
	    printf $CFGC  "   *(volatile unsigned int *)TIBOOT_CFGBRIDGE_REGISTER |= 1;\n";
	    printf $CFGC  "   asm(\"\tnop 9\");\n";
	    printf $CFGC  "   *(volatile unsigned int *)TIBOOT_CFGBRIDGE_REGISTER &= 0xFFFFFFFE;\n";
	    printf $CFGC  "\n";
	    printf $CFGC  "// Make sure SDRAM exits Self-Refesh Mode\n"; 
	    printf $CFGC  "// By setting SR bit in EMIF SDCR register to 0\n";
	    printf $CFGC  "\n";
	    printf $CFGC  "   *(volatile unsigned int *)TIBOOT_EMIF_SDCR &= 0xEFFFFFFFu;\n"; 
        printf $CFGC  "}\n"; 
        printf $CFGC "\n\n\n";
	     
     } 
     
     return; 
}


       
#----------------------------------------------------------------------------------------------
# Save PLL Configuration to .cfg file
#----------------------------------------------------------------------------------------------
sub genPllCfg{
	
	my($CFG) = shift(@_);
	my($flag) = shift(@_);
	
	if ($flag == 1) {		
	    printf $CFG  "#====================================================================\n";
		printf $CFG  "# PLL Configuration\n";
		printf $CFG  "#====================================================================\n";	 
		printf $CFG " -pllCfg 0x1\n";
		printf $CFG " -pllcfgosc    %f\n",$pllCfg{'osc'}{'val'};
		printf $CFG " -pllcfgcpu    0x%08X\n",$pllCfg{'cpu'}{'val'};
		printf $CFG " -pllcfgemif   0x%08X\n",$pllCfg{'emif'}{'val'};
		printf $CFG " -pllcfgintosc 0x%08X\n",$pllCfg{'int_osc'}{'val'};
		printf $CFG " -pllcfgweight 0x%08X\n",$pllCfg{'weight'}{'val'};	     
		printf $CFG " -pllcfgpllm   0x%08X\n",$pllCfg{'pllm'}{'val'};
		printf $CFG " -pllcfgdiv0   0x%08X\n",$pllCfg{'div0'}{'val'};
		printf $CFG " -pllcfgdiv1   0x%08X\n",$pllCfg{'div1'}{'val'};
		printf $CFG " -pllcfgdiv2   0x%08X\n",$pllCfg{'div2'}{'val'};
		printf $CFG " -pllcfgdiv3   0x%08X\n",$pllCfg{'div3'}{'val'};
		printf $CFG "\n";
   }else{
  	    printf $CFG  "#====================================================================\n";
		printf $CFG  "# PLL Configuration\n";
		printf $CFG  "#====================================================================\n";	 
		printf $CFG " -pllCfg 0x0\n";
		printf $CFG "\n"; 
   }
   
   return;
}



#----------------------------------------------------------------------------------------------
# Gen I2C Clock configuration settings
#----------------------------------------------------------------------------------------------
sub genI2cClkCfg{
	
	my($CFG) = shift(@_);
	my($flag) = shift(@_);
	
	if ($flag == 1) {
	   printf $CFG  "#====================================================================\n";
	   printf $CFG  "# I2C Clock Configuration\n";
	   printf $CFG  "#====================================================================\n";
       printf $CFG  " -i2cClkCfg 1\n";
	   printf $CFG  " -i2cclkcfgpsc       0x%08X\n",$i2cClkCfg{'psc'}{'val'};
       printf $CFG  " -i2cclkcfgclkl      0x%08X\n",$i2cClkCfg{'clkl'}{'val'};
       printf $CFG  " -i2cclkcfgclkh      0x%08X\n",$i2cClkCfg{'clkh'}{'val'};
#       printf $CFG  " -i2cclkcfglowclock  0x%08X\n",$i2cClkCfg{'lowClock'}{'val'};
#       printf $CFG  " -i2cclkcfghighclock 0x%08X\n",$i2cClkCfg{'highClock'}{'val'};
#       printf $CFG  " -i2cclkcfgweight    0x%08X\n",$i2cClkCfg{'weight'}{'val'};
       printf $CFG  "\n";
   } else {
	   printf $CFG  "#====================================================================\n";
	   printf $CFG  "# I2C Clock Configuration\n";
	   printf $CFG  "#====================================================================\n";
       printf $CFG  " -i2cClkCfg 0\n";	
       printf $CFG  "\n";
   }    		
	
   return;
}


#----------------------------------------------------------------------------------------------
# Gen I2C Clock Setup Function for cfg.c
#----------------------------------------------------------------------------------------------
sub genI2cClkSetupFunc{
    my($CFGC) = shift(@_);
	my($flag) = shift(@_);
	
	if ($flag == 1) {
	     printf $CFGC "//===================================================================//\n";
	     printf $CFGC "// I2c Clock Configuration                                           //\n";
	     printf $CFGC "//    I2c Clock Prescale Register:                                   //\n";
	     printf $CFGC "//        register mask: 0x%08X                                  //\n",$i2cClkCfg{'psc'}{'val'};
	     printf $CFGC "//                                                                   //\n";
	     printf $CFGC "//    I2C ICCLKH Register                                            //\n";
         printf $CFGC "//        register mask: 0x%08X                                  //\n", $i2cClkCfg{'clkh'}{'val'};
	     printf $CFGC "//                                                                   //\n";
	     printf $CFGC "//    I2C ICCLKL Register                                            //\n";
         printf $CFGC "//        register mask: 0x%08X                                  //\n", $i2cClkCfg{'clkl'}{'val'};         
	     printf $CFGC "//===================================================================//\n";
         printf $CFGC "\n";
         printf $CFGC "#pragma CODE_SECTION(TIBootI2cClkCfg,\".TIBoot\")\n";
         printf $CFGC "void TIBootI2cClkCfg()\n";
         printf $CFGC "{\n";
         printf $CFGC "   // Make sure I2C device is held in reset\n";
         printf $CFGC "   *(volatile unsigned int *)TIBOOT_I2C1_ICMDR &= ~(0x00000020);\n";
	     printf $CFGC "   *(volatile unsigned int *)TIBOOT_I2C1_ICPSC = 0x%08Xu;\n",$i2cClkCfg{'psc'}{'val'};
	     printf $CFGC "   *(volatile unsigned int *)TIBOOT_I2C1_ICCLKH = 0x%08Xu;\n",$i2cClkCfg{'clkh'}{'val'};
	     printf $CFGC "   *(volatile unsigned int *)TIBOOT_I2C1_ICCLKL = 0x%08Xu;\n",$i2cClkCfg{'clkl'}{'val'};
	     printf $CFGC "   // Now Release I2C from Reset\n";
         printf $CFGC "   *(volatile unsigned int *)TIBOOT_I2C1_ICMDR |= (0x00000020);\n";
         printf $CFGC "}\n";	     	     
	     printf $CFGC "\n\n\n";	
	}
	
	return;
}

#----------------------------------------------------------------------------------------------
# Generate Headers for Output Files *.cfg, *cfg.c
#----------------------------------------------------------------------------------------------
sub genHeaders{
	
	my($COUT) = shift(@_);
	my($cFileName) = shift(@_);
	my($CFGOUT) = shift(@_);
	my($cfgFileName) = shift(@_);
	
	my(@days) = ( "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", 
	              "Friday", "Saturday");
	          
	my(@months) = ( "January", "February", "March", "April" , "May",
	                "June", "July", "August", "September", "October",
	                "November", "December");

	            
	my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
	my($dateFormat) = "%".length($days[$wday])."s "."%".length($months[$mon]).
	              "s %-2d,%-4d  %2d:%2d:%2d";
	
	my($dateString) = sprintf($dateFormat,
	                          $days[$wday],$months[$mon],$mday,$year+1900,
	                          $hour,$min,$sec);
	                          
	my($cfgFilePath) = dirname($cfgFileName);
	my($cfgFileBase) = basename($cfgFileName);  
	my($cFileBase)   = basename($cFileName);                        
		          
	            	                      
	printf $COUT "//===================================================================//\n";
	printf $COUT "// Boot Configuration File :                                         //\n";
	printf $COUT "//    %-62s //\n",substr($cfgFilePath,0,62);
	printf $COUT "//    %-62s //\n",substr($cFileBase,0,62);	
	printf $COUT "// Date: %-59s //\n",$dateString;
	printf $COUT "//===================================================================//\n";
	printf $COUT "\n\n";
	printf $COUT "#include <TISecondaryBoot.h>\n";
	printf $COUT "\n\n";
			
	printf $CFGOUT "##===================================================================##\n";
	printf $CFGOUT "## Boot Configuration File :                                         ##\n";
	printf $CFGOUT "##    %-62s ##\n",substr($cfgFilePath,0,62);
	printf $CFGOUT "##    %-62s ##\n",substr($cfgFileBase,0,62);	
	printf $CFGOUT "## Date: %-59s ##\n",$dateString;
	printf $CFGOUT "##===================================================================##\n";
	printf $CFGOUT "\n\n";	
	
}


#--------------------------------------------------------------------------------------------
#  GPIO/Address Pin Configuration
#--------------------------------------------------------------------------------------------
sub addressPinCfg {
	
    my($i) = 0;
    my($pinLabel) = '';

    $numEmifPins = ($pkg eq "TQFP") ? 12:13;
   
    my($hAddressPinCfgWin) = MainWindow->new(
                   -title => "GPIO ==> Address Pin Configuration",
                 );
                 
    $hAddressPinCfgWin->minsize(qw(500 500));
 #   $hAddressPinCfgWin->configure(-background => 'cyan');
  
     my($hFrameButtons) = $hAddressPinCfgWin->Frame(
                           )->pack(
                            -side   => 'top',
                            -anchor => 'nw',
                            -pady   => 12,
                            -fill => 'x',
                            );
   
  #   $hFrameButtons->configure(-background => 'yellow');             
     my($hAddressPinCfgWinOkButton) = $hFrameButtons->Button(
                                       -text => "OK",
                                       -font => 'bold 11',
                                       -command => [\&savePinCfg, $hAddressPinCfgWin],                             
                                       )-> pack (
                                        -side => 'left',
                                        -fill => 'x',
                                       );
  
    my($hAddressPinCfgWinClearButton) = $hFrameButtons->Button(
                                        -text => "Clear",
                                        -font => 'bold 11',
                                        -command => [\&clearPinCfg],
                                        )-> pack (
                                            -side => 'left',
                                        );
                                        
                                                          
    my($hAddressPinCfgWinCancelButton) = $hFrameButtons->Button(
                                          -text => "Cancel",
                                          -font => 'bold 11',
                                          -command => [\&cancelPinCfg, $hAddressPinCfgWin],
                                          )-> pack (
                                           -side => 'left',
                                          );
                              
                              
    my($hFramePinSelect) = $hAddressPinCfgWin->Frame(
                           -relief => "groove",
#                           -bg => 'cyan',
                           -borderwidth => 2,
                           -height => 500,
                           -width => 500,
                           )->pack(
                            -fill => 'x'
                           );
	
    @activePinList = ($pkg eq 'BGA') ? @bgaPinList : @tqfpPinList;

                             
                              
                              
    $pinNdx = $numEmifPins;
    for($i = 0; $i <= (24 - $numEmifPins); ++$i, ++$pinNdx) {
	   $hAddressPins[$i] = $hFramePinSelect->Scrolled('Optionmenu',
	                       -scrollbars=>'oe',
	                       -relief => 'groove',
#	                       -background => 'cyan',
	                       -borderwidth => 6,
	                       -variable =>\$addressPinCfg[$i],
	                       -command => [\&saveTmpCfg,  $i, \$addressPinCfg[$i], \$hAddressPins[$i]],                             
	                       -label => "Address Pin #$pinNdx",
	                       -font => 'bold 10',
	                       -options =>[@activePinList],
	                        )                  
    }
        
                                   
                                                         
    $latchMsg = sprintf("Use Pin #%d, as latch for upper address bits",$numEmifPins);   
                        
                                                            
    my($hAddressLatchCheckBox) = $hAddressPinCfgWin->Checkbutton (
	                             -text=> $latchMsg,
	                             -font=> 'bold 11',
	                             -variable=>\$useAddressLatch,
	                             -command => [ sub {
			                                   if ($useAddressLatch == 1) {
		      
	                                              for($i = 1; $i <= (24 - $numEmifPins); ++$i, ++$pinNdx) 
	                                              {
		                                               $hAddressPins[$i]->configure(-state => 'disabled');
	                                              }
	                                           }
                                           }
                                           ],	     
	                             )-> pack (
	                             -side => 'left',
	                             -fill => 'x',
	                             );
	                                               


    $pinNdx = $numEmifPins;
    for($i = 0; $i <= (24 - $numEmifPins); ++$i, ++$pinNdx) 
    {
	    $hAddressPins[$i]->grid(
	                     -row => ($i/5),
	                     -column => ($i % 5),
	                     -padx => 5,
	                     -pady => 5,
        );                   
    }
        
     
  return;
}

#----------------------------------------------------------------------------------------------
# Save Snapshot of Current GPIO/Address Pin Configuration
#----------------------------------------------------------------------------------------------
sub saveTmpCfg{
   my($pin) = shift(@_);	
   my($periphPin) = shift(@_);
   my($window) = shift(@_);


     # If PIN was previousyl configured, clear current
     # status before setting new value  
     if ($tmpPinCfg[$pin] ne 'Not Mapped') {
		     $pinsUsed[$pins{$tmpPinCfg[$pin]}] = 0;
	 }
	     
     $tmpPinCfg[$pin] = $$periphPin;
#      printf("Saving Configuration Info for Pin #%d, :%s:\n", $pin, $$periphPin);
#      printf("\t GPIO Pin Mapped :%s:\n", $tmpPinCfg[$pin]);
     
     # Remove selected item from list 
     if ($tmpPinCfg[$pin] ne 'Not Mapped') {
# 	     printf("Pin State:%d:\n",$pinsUsed[$pins{$tmpPinCfg[$pin]}]);
	     if ($pinsUsed[$pins{$tmpPinCfg[$pin]}] eq $PIN_IN_USE) {
# 		     printf("Should be setting Not Mapped:%d:\n",$pinsUsed[$pins{$tmpPinCfg[$pin]}]);
		     $addressPinCfg[$pin] = 'Not Mapped';
		     $tmpPinCfg[$pin] = 'Not Mapped';
	     } else {
		     $pinsUsed[$pins{$tmpPinCfg[$pin]}] = $PIN_IN_USE;
	     }
     }
    
  return;
}

#----------------------------------------------------------------------------------------------
# Clear Current GPIO/Address Pin Configuration
#----------------------------------------------------------------------------------------------
sub clearPinCfg{
   my($window) = shift(@_);

   my($i);
   
   for($i=0;$i <= 24 - $numEmifPins; ++$i) {

     if ($tmpPinCfg[$pin] ne 'Not Mapped') {
	   $pinsUsed[$pins{$tmpPinCfg[$pin]}] = 0 ;
	 }
     
	 $tmpPinCfg[$i] = 'Not Mapped';
	 $addressPinCfg[$i]= 'Not Mapped';   
   }
    
   for($i=0;$i<225;++$i) {
	   $pinsUsed[$i] = 0;
   }
  
  return;
}
#----------------------------------------------------------------------------------------------
# Cancel current GPIO/Address PIN Configuration
#----------------------------------------------------------------------------------------------
sub cancelPinCfg{
   my($window) = shift(@_);

   my($i);
   
   for($i=0;$i <= 24 - $numEmifPins; ++$i) {
	   $tmpPinCfg[$i] = 'Not Mapped';
	   $addressPinCfg[$i]= 'Not Mapped';
   }
   
   $pinsConfigured = 0;

   killWindow($window);
  
   
  return;
}

#----------------------------------------------------------------------------------------------
# Save GPIO/Address Pin Confguration
#----------------------------------------------------------------------------------------------
sub savePinCfg{
   my($window) = shift(@_);

   
   $pinsConfigured = 1;
    killWindow($window);
  
  return;
}

#--------------------------------------------------------------------------------------------
# Display Peripheral Configuration Menu
#--------------------------------------------------------------------------------------------
sub displayConfigMenu {

  my($parentWin) = shift(@_);	
 

  
  my($hFrameCfgSelect) = $parentWin->Frame(
      -relief => "groove",
#       -bg => 'cyan',
       -borderwidth => 2
   )->pack(
     -fill => 'both'
   );
   
   
  $hFrameCfgSelect->configure(-height=> 700, -width => 400);
  
  my($hPackageOptions) = $hFrameCfgSelect->Scrolled(
                        'Optionmenu',
	                    -relief => 'groove',
	                    -borderwidth => 4,
	                    -variable =>\$pkg,
	                    -label => "Package Type",
	                    -font => 'bold 10',
	                    -options => [qw(BGA TQFP)],
	                    )        
	                    ->grid(
	                    -row     => 0,
	                    -pady    => 5,
	                    -column => 2,
	                    -sticky => 'w',
	                   );              
  
 
   
  my($hCheckPllCfg) = $hFrameCfgSelect->Checkbutton(
	  -text => "Configure PLL",
	  -font => 'bold 10',
	  -pady => 2,
	  -justify => 'left',
	  -variable => \$pllConfigured,
      -command => [\&pllCfg],
	        )->grid (
       -column => 2,
       -sticky => 'w',
      );
         

  my($hCheckI2cCfg) = $hFrameCfgSelect->Checkbutton(
	  -text => "Configure I2C Clock",
	  -font => 'bold 10',
	  -pady => 2,
	  -justify => 'left',
	  -variable => \$i2cClkConfigured,
      -command => [\&i2cClkCfg],
	        )->grid (
       -column => 2,
       -sticky => 'w',
      );
      
       
  my($hCheckSDRAMCfg) = $hFrameCfgSelect->Checkbutton(
	  -text => "Configure EMIF - SDRAM",
	  -font => 'bold 10',
	  -pady => 2,
	  -justify => 'left',
	  -variable => \$sdramConfigured,
	  -command => [\&sdramCfg],
	        )->grid (
       -column => 2,
       -sticky => 'w',
      );


   my($hCheckAsyncRamCfg) = $hFrameCfgSelect->Checkbutton(
	  -text => "Configure EMIF - ASYNC RAM",
	  -font => 'bold 10',
	  -pady => 2,
	  -justify => 'left',
	  -variable => \$asyncRamConfigured,
	  -command => [\&asyncRamCfg],
	        )->grid (
       -column => 2,
       -sticky => 'w',
      );
                  
 
   my($hCheckAddressPinCfg) = $hFrameCfgSelect->Checkbutton(
	  -text => "Configure GPIO as Address Pins",
	  -font => 'bold 10',
	  -pady => 2,
	  -justify => 'left',	
	  -variable => \$pinsConfigured,
      -command => [\&addressPinCfg],
	        )->grid (
       -column => 2,
       -sticky => 'w',
      );
                
  return;
}



#--------------------------------------------------------------------------------------------
sub killWindow {
	
	my ($window) = shift(@_);
	
	$window->DESTROY;
}

#--------------------------------------------------------------------------------------------
# Set Parameters for SDRAM Configuration
#--------------------------------------------------------------------------------------------
sub sdramCfg {

    @SdcrNmOptions = ("32 bit",  "16 bit");
      
    @SdcrClOptions = ("2 EM CLK Cycles",  "3 EM CLK Cycles");
    
    @SdcrBit11_9LockOptions = ("CL cannot be written",  "CL can be written");
    %SdcrBit11_9LockValues = ("CL cannot be written" =>0,
                              "CL can be written" => 1);
                              
    @SdcrIbankOptions = ('1 Bank',  '2 Banks', '4 Banks');   
     
    @SdcrPagesizeOptions = (' 8 column address bits (256 elements per row)', 
                            ' 9 column address bits (512 elements per row)', 
                            '10 column address bits (1024 elements per row)');
                            
                                                       	
	my($sdcr_NM)         = $SdcrNmOptions[($sdramConfig{'sdcr'}{'val'} & $sdramConfig{'sdcr'}{'nm'}{'mask'}) 
	                         >> $sdramConfig{'sdcr'}{'nm'}{'shift'}];
	                         
	my($sdcr_CL);
	                         
	if ((($sdramConfig{'sdcr'}{'val'} & $sdramConfig{'sdcr'}{'cl'}{'mask'}) 
	                         >> $sdramConfig{'sdcr'}{'cl'}{'shift'}) == 2) {
		                         $sdcr_CL = '2 EM CLK Cycles';
	                         } else {
		                         $sdcr_CL = '3 EM CLK Cycles';
	                         } 
		                     
	                         
	my($sdcr_BIT11_9LOCK)= $SdcrBit11_9LockOptions[($sdramConfig{'sdcr'}{'val'} & $sdramConfig{'sdcr'}{'bit11_9lock'}{'mask'}) 
	                         >> $sdramConfig{'sdcr'}{'bit11_9lock'}{'shift'}];
	                         	                         
	my($sdcr_IBANK)      = $SdcrIbankOptions[($sdramConfig{'sdcr'}{'val'} & $sdramConfig{'sdcr'}{'ibank'}{'mask'}) 
	                         >> $sdramConfig{'sdcr'}{'ibank'}{'shift'}];
	                         	  	                         
	my($sdcr_PAGESIZE)   = $SdcrPagesizeOptions[($sdramConfig{'sdcr'}{'val'} & $sdramConfig{'sdcr'}{'pagesize'}{'mask'}) 
	                         >> $sdramConfig{'sdcr'}{'pagesize'}{'shift'}];	   
	                         	                                                	                         

	my($sdrcr_RR)         = ($sdramConfig{'sdrcr'}{'val'} & $sdramConfig{'sdrcr'}{'rr'}{'mask'})
	                         >> $sdramConfig{'sdrcr'}{'rr'}{'shift'};
	                         
	my($sdtimr_TRFC)      = ($sdramConfig{'sdtimr'}{'val'} & $sdramConfig{'sdtimr'}{'t_rfc'}{'mask'})
	                         >> $sdramConfig{'sdtimr'}{'t_rfc'}{'shift'};
	                        $sdtimr_TRFC = $sdtimr_TRFC + 1;
	                         
	my($sdtimr_TRP)       = ($sdramConfig{'sdtimr'}{'val'} & $sdramConfig{'sdtimr'}{'t_rp'}{'mask'}) 
	                         >> $sdramConfig{'sdtimr'}{'t_rp'}{'shift'};
	                        $sdtimr_TRP = $sdtimr_TRP + 1;
	                         
	my($sdtimr_TRCD)      = ($sdramConfig{'sdtimr'}{'val'} & $sdramConfig{'sdtimr'}{'t_rcd'}{'mask'})
	                        >> $sdramConfig{'sdtimr'}{'t_rcd'}{'shift'};
	                        $sdtimr_TRCD = $sdtimr_TRCD + 1;
	                        
	my($sdtimr_TWR)       = ($sdramConfig{'sdtimr'}{'val'} & $sdramConfig{'sdtimr'}{'t_wr'}{'mask'})
	                        >> $sdramConfig{'sdtimr'}{'t_wr'}{'shift'};
	                        $sdtimr_TWR = $sdtimr_TWR + 1;
	
	my($sdtimr_TRAS)      = ($sdramConfig{'sdtimr'}{'val'} & $sdramConfig{'sdtimr'}{'t_ras'}{'mask'})
	                        >> $sdramConfig{'sdtimr'}{'t_ras'}{'shift'};
	                        $sdtimr_TRAS = $sdtimr_TRAS + 1;
	                        	
	my($sdtimr_TRC)       = ($sdramConfig{'sdtimr'}{'val'} & $sdramConfig{'sdtimr'}{'t_rc'}{'mask'})
	                        >> $sdramConfig{'sdtimr'}{'t_rc'}{'shift'};
	                        $sdtimr_TRC = $sdtimr_TRC + 1;

	                        	
	my($sdtimr_TRRD)      = ($sdramConfig{'sdtimr'}{'val'} & $sdramConfig{'sdtimr'}{'t_rrd'}{'mask'})
	                        >> $sdramConfig{'sdtimr'}{'t_rrd'}{'shift'};
	                        $sdtimr_TRRD = $sdtimr_TRRD + 1;
	                        
	my($sdsretr_TXS)      = ($sdramConfig{'sdsretr'}{'val'} & $sdramConfig{'sdsretr'}{'t_xs'}{'mask'})
	                        >> $sdramConfig{'sdsretr'}{'t_xs'}{'shift'};
	                        $sdsretr_TXS = $sdsretr_TXS + 1;
	
	###########################################################################
	# Create Main Window and Frames
	###########################################################################
	my($hSDRAMCfgWin) = MainWindow->new(
                   -title => "SDRAM Configuration",
                 );
                 
    $hSDRAMCfgWin->minsize(qw(600 250));
#    $hSDRAMCfgWin->configure(-background => 'cyan');
    
    my($hFrameButtons) = $hSDRAMCfgWin->Frame(
                           )->pack(
                           -side   => 'top',
                           -anchor => 'nw',
                           #-padx   => 8,
                           -pady   => 12,
                           #-expand => 1,
                           -fill => 'x',
                          );
 #   $hFrameButtons->configure(-background => 'yellow');             
                          
                          
    my($hSdramCfgFrame)   = $hSDRAMCfgWin->Frame(
 #                             -background=> 'cyan',
                              -relief => 'groove',
                              -borderwidth => 2,
                              )->pack(
                              -fill => 'both',
                              );
       
    ############################################################################
    # Create Objects for Config Frame
    ############################################################################                          
    my($hSdcrNmLabel)      = $hSdramCfgFrame->Label(
                              -text => "Data Bus Width (NM)",
	                          -font => 'bold 10',
#	                          -background => 'cyan',
	                          -justify => 'right',
	                           );  
	                                                                                 
    my($hSdcrNm)           = $hSdramCfgFrame->Scrolled(
                               'Optionmenu',
	                           -relief => 'groove',
#	                           -background => 'cyan',
	                           -borderwidth => 6,
	                           -variable =>\$sdcr_NM,
	                           -textvariable =>\$sdcr_NM,
	                           -options => [@SdcrNmOptions],	                           
	                           -command =>[ sub 
	                                        { 
		                                       $sdramConfig{'sdcr'}{'nm'}{'val'} = 0 if ($sdcr_NM == 32);		                                        
		                                       $sdramConfig{'sdcr'}{'nm'}{'val'} = 1 if ($sdcr_NM == 16);
		                                        return 1;
		                                     }
		                                   ],
	                           -font => 'bold 10',
	                           );
	                               
    
    my($hSdcrClLabel) = $hSdramCfgFrame->Label(
                          -text => "CAS Latency",
                          -font => 'bold 10',
#                          -background => 'cyan',
                          -justify => 'right',
                           );
	                                                        
     my($hSdcrCl) = $hSdramCfgFrame->Scrolled(
                       'Optionmenu',
                       -relief => 'groove',
#                       -background => 'cyan',
                       -borderwidth => 6,
                       -variable =>\$sdcr_CL,
                       -options => [@SdcrClOptions],
                       -command =>[ sub 
                                    { 
	                                   $sdramConfig{'sdcr'}{'cl'}{'val'} = 2 if ($sdcr_CL eq '2 EM CLK Cycles');
	                                   $sdramConfig{'sdcr'}{'cl'}{'val'} = 3 if ($sdcr_CL eq '3 EM CLK Cycles');
	                                   return 1;
	                                }
	                              ],	                           
                       -font => 'bold 10',
                       );
	                           	                           
     my($hSdcrBit11_9LockLabel) = $hSdramCfgFrame->Label(
                              -text => "CAS Latency Write Lock (BIT11_9LOCK)",
	                          -font => 'bold 10',
#	                          -background => 'cyan',
	                          -justify => 'right',
	                           );
	                                                  
     my($hSdcrBit11_9Lock) = $hSdramCfgFrame->Scrolled(
                               'Optionmenu',
	                           -relief => 'groove',
#	                           -background => 'cyan',
	                           -borderwidth => 6,
	                           -variable =>\$sdcr_BIT11_9LOCK,
	                           -options => [@SdcrBit11_9LockOptions],
	                           -command => 
	                           [ 
	                              sub 
	                              {
		                               $hSdcrCl->configure(-state=>'disabled')  if ($sdcr_BIT11_9LOCK eq 'CL cannot be written');
                                       $hSdcrCl->configure(-state=>'normal') if ($sdcr_BIT11_9LOCK eq 'CL can be written');
	                                   $sdramConfig{'sdcr'}{'bit11_9lock'}{'val'} = 0 if ($sdcr_BIT11_9LOCK eq 'CL cannot be written');
	                                   $sdramConfig{'sdcr'}{'bit11_9lock'}{'val'} = 1 if ($sdcr_BIT11_9LOCK eq 'CL can be written');
	                                   return 1;                                      
                                  }
                               ],
	                           -font => 'bold 10',
	                           );
	                                                          
     my($hSdcrIbankLabel) = $hSdramCfgFrame->Label(
                             -text => "Internal SDRAM Bank Size",
                             -font => 'bold 10',
 #                            -background => 'cyan',
                             -justify => 'right',
                             );
	                                                        
     my($hSdcrIbank) = $hSdramCfgFrame->Scrolled(
                       'Optionmenu',
                       -relief => 'groove',
#                       -background => 'cyan',
                       -borderwidth => 6,
                       -variable =>\$sdcr_IBANK,
                       -options => [@SdcrIbankOptions],
                       -command => [ sub 
                                     { 
	                       
	                                     $sdramConfig{'sdcr'}{'ibank'}{'val'} = 0 if ($sdcr_IBANK eq '1 Bank'); 
   	                                     $sdramConfig{'sdcr'}{'ibank'}{'val'} = 1 if ($sdcr_IBANK eq '2 Banks'); 
   	                                     $sdramConfig{'sdcr'}{'ibank'}{'val'} = 2 if ($sdcr_IBANK eq '4 Banks'); 

	                                  }
	                                ],
                       -font => 'bold 10',
                       );
	                                
     my($hSdcrPageSizeLabel) = $hSdramCfgFrame->Label(
                                 -text => "Page Size",
	                             -font => 'bold 10',
#	                             -background => 'cyan',
	                             -justify => 'right',
	                             ); 
	                                                        
     my($hSdcrPagesize) = $hSdramCfgFrame->Scrolled(
                           'Optionmenu',
                           -relief => 'groove',
#                           -background => 'cyan',
                           -borderwidth => 6,
                           -variable =>\$sdcr_PAGESIZE,
                           -options => [@SdcrPagesizeOptions],
                           -command => [ sub 
                                         { 	                           
	                                           $sdramConfig{'sdcr'}{'pagesize'}{'val'} = 0 
	                                                  if ($sdcr_PAGESIZE eq ' 8 column address bits (256 elements per row)'); 
	                                           $sdramConfig{'sdcr'}{'pagesize'}{'val'} = 1 
	                                                  if ($sdcr_PAGESIZE eq ' 9 column address bits (512 elements per row)'); 
	                                           $sdramConfig{'sdcr'}{'pagesize'}{'val'} = 2 
	                                                  if ($sdcr_PAGESIZE eq '10 column address bits (1024 elements per row)');
                                         }
                                        ],
                           -font => 'bold 10',
                           ); 
	                           
                                                               	                           
	                           
	##################################################################################
	# Populate Main Button Frame
	##################################################################################                         
	                           
    my($hSDRAMCfgWinOkButton) = $hFrameButtons->Button(
                         -text => "OK",
                         -font => 'bold 11',
                         -command => [\&saveSDRAMCfg, $hSDRAMCfgWin],                             
                         )-> pack (
                            -side => 'left',
                            -fill => 'x',
                         );
  
    my($hSDRAMCfgWinClearButton) = $hFrameButtons->Button(
                              -text => "Clear",
                              -font => 'bold 11',
                              -command => [ sub {
	                              	                                                                                        
	                              	$sdcr_NM          = $SdcrNmOptions[$sdramConfig{'sdcr'}{'nm'}{'default'}];
	                              	 
	                              	 if ($sdramConfig{'sdcr'}{'cl'}{'default'} == 2) {
	                              	      $sdcr_CL = '2 EM CLK Cycles';
	                                 } else {
		                                  $sdcr_CL = '3 EM CLK Cycles';
	                                 } 
	                              	 
	                              	 
	                              	$sdcr_BIT11_9LOCK = $SdcrBit11_9LockOptions[$sdramConfig{'sdcr'}{'bit11_9lock'}{'default'}];
	                                $sdcr_IBANK       = $SdcrIbankOptions[$sdramConfig{'sdcr'}{'ibank'}{'default'}];
	                                $sdcr_PAGESIZE    = $SdcrPagesizeOptions[$sdramConfig{'sdcr'}{'pagesize'}{'default'}];
	                                
	                                
	                                $sdrcr_RR         = $sdramConfig{'sdrcr'}{'rr'}{'default'};
	                                $sdtimr_TRFC      = $sdramConfig{'sdtimr'}{'t_rfc'}{'default'} + 1;
	                                $sdtimr_TRP       = $sdramConfig{'sdtimr'}{'t_rp'}{'default'} + 1;
	                                $sdtimr_TRCD      = $sdramConfig{'sdtimr'}{'t_rcd'}{'default'} + 1;
	                                $sdtimr_TWR       = $sdramConfig{'sdtimr'}{'t_wr'}{'default'} + 1;
	                                $sdtimr_TRAS      = $sdramConfig{'sdtimr'}{'t_ras'}{'default'} + 1;
	                                $sdtimr_TRC       = $sdramConfig{'sdtimr'}{'t_rc'}{'default'} + 1;
	                                $sdtimr_TRRD      = $sdramConfig{'sdtimr'}{'t_rrd'}{'default'} + 1;
	                                $sdsretr_TXS      = $sdramConfig{'sdsretr'}{'t_xs'}{'default'} + 1;
	                                
	                                $hSdcrCl->configure(-state=>'disabled')  if ($sdcr_BIT11_9LOCK eq 'CL cannot be written');
                                    $hSdcrCl->configure(-state=>'normal') if ($sdcr_BIT11_9LOCK eq 'CL can be written');
	                                $sdramConfig{'sdcr'}{'bit11_9lock'}{'val'} = $SdcrBit11_9LockValues{$sdcr_BIT11_9LOCK};
                                       
                                     
	                                }
	                              ],
                              )-> pack (
                              -side => 'left',
                              );
                                                          
     my($hSDRAMCfgWinCancelButton) = $hFrameButtons->Button(
                              -text => "Cancel",
                              -font => 'bold 11',
                              -command => [\&cancelSDRAMCfg, $hSDRAMCfgWin],
                              )-> pack (
                              -side => 'left',
                              );
                              
     ###############################################################################
     # Populate Config Frame
     ###############################################################################
     $hSdcrNmLabel-> grid (
                     -row    => 0,
                     -column => 0,
                     -padx => 1,
                     -pady => 1,
                     -sticky => 'e',
                   ); 
	                                                        
     $hSdcrNm-> grid (
                 -row    => 0,
                 -column => 1,
                 -padx => 1,
                 -pady => 1,
                 -sticky => 'w',
               ); 
	                                                     
     
     $hSdcrBit11_9LockLabel-> grid (
	                             -row    => 1,
	                             -column => 0,
	                             -padx => 1,
	                             -pady => 1,
	                             -sticky => 'e',
	                           ); 
	                                                        
     $hSdcrBit11_9Lock-> grid (
	                             -row    => 1,
	                             -column => 1,
	                             -padx => 1,
	                             -pady => 1,
	                             -sticky => 'w',
	                           ); 
	                                                     
                                                                          
      $hSdcrClLabel-> grid (
	                      -row    => 2,
	                      -column => 0,
	                      -padx => 1,
	                      -pady => 1,
	                      -sticky => 'e',
	                      ); 
	                                                        
     $hSdcrCl-> grid (
	                -row    => 2,
	                -column => 1,
	                -padx => 1,
	                -pady => 1,
	                -sticky => 'w',
	               ); 
	                                                     
          
     $hSdcrCl->configure(-state=>'disabled')  if ($sdcr_BIT11_9LOCK eq 'CL cannot be written');
     $hSdcrCl->configure(-state=>'normal') if ($sdcr_BIT11_9LOCK eq 'CL can be written');
    
     $hSdcrIbankLabel-> grid (
                        -row    => 3,
                        -column => 0,
                        -padx => 1,
                        -pady => 1,
                        -sticky => 'e',
                      ); 
	                                                        
     $hSdcrIbank  -> grid (
                     -row    => 3,
                     -column => 1,
                     -padx => 1,
                     -pady => 1,
                     -sticky => 'w',
                   ); 
	                           
	                           
     $hSdcrPageSizeLabel-> grid (
                            -row    => 4,
                            -column => 0,
                            -padx => 1,
                            -pady => 1,
                            -sticky => 'e',
                          ); 
                                                    
     $hSdcrPagesize-> grid (
	                  -row    => 4,
	                  -column => 1,
	                  -padx => 1,
	                  -pady => 1,
	                  -sticky => 'w',
	                 ); 
	                           

     my($hSdrcrRRLabel) = $hSdramCfgFrame->Label(
                                          -text => "Refresh Rate (0-131071)/(0-1FFFFh)",
	                                      -font => 'bold 10',
#	                                      -background => 'cyan',
	                                      -justify => 'right',
	                                      )-> grid (
	                                          -row    => 5,
	                                          -column => 0,
	                                          -padx => 1,
	                                          -pady => 1,
	                                          -sticky => 'e',
	                                      );                                 
	                                     
      my($hSdrcrRR) = $hSdramCfgFrame->Entry(
                                       -relief => 'groove',
                                       -font => 'bold 10',
#                                       -background => 'cyan',
                                       -highlightcolor => 'yellow',                     
                                       -borderwidth => '3',
                                       -width => '8',
                                       -textvariable=>\$sdrcr_RR,
                                       -validate => "all",
                                       -vcmd =>[ sub 
                                                 { #$sdrcr_RR = $sdcr_RR & ($sdramConfig{'sdrcr'}{'rr'}{'mask'} >>
                                                   #$sdramConfig{'sdrcd'}{'rr'}{'shift'});
                                                   $sdramConfig{'sdrcr'}{'rr'}{'val'} = $sdrcr_RR;
                                                   return 1; 
                                                 }
                                               ],                                      
	                                   )-> grid (
	                                       -row    => 5,
	                                       -column => 1,
	                                       -padx => 1,
	                                       -pady => 1,
	                                       -sticky => 'w',
	                                   );     

     my($hSdtimrTrfcLabel) = $hSdramCfgFrame->Label(
                                          -text => "Minimum Num of EM_CLK Cycles from Refresh to Refresh(T_RFC)",
	                                      -font => 'bold 10',
#	                                      -background => 'cyan',
	                                      -justify => 'right',
	                                      )-> grid (
	                                          -row    => 6,
	                                          -column => 0,
	                                          -padx => 1,
	                                          -pady => 1,
	                                          -sticky => 'e',
	                                      );                                 
	                                     
      my($hSdtimrTrfc) = $hSdramCfgFrame->Entry(
                                       -relief => 'groove',
                                       -font => 'bold 10',
#                                       -background => 'cyan',
                                       -highlightcolor => 'yellow',                     
                                       -borderwidth => '3',
                                       -width => '8',
                                       -textvariable=>\$sdtimr_TRFC,
                                       -validate => "all",
                                       -vcmd =>[ sub 
                                                 { #$sdtimr_TRFC = $sdtimr_TRFC & ($sdramConfig{'sdtimr'}{'t_rfc'}{'mask'} >>
                                                   #$sdramConfig{'sdtimr'}{'t_rfc'}{'shift'});
                                                   $sdramConfig{'sdtimr'}{'t_rfc'}{'val'} = $sdtimr_TRFC - 1; 
                                                  return 1;
                                                 }
                                               ],  	                                  
                                        )-> grid (
	                                       -row    => 6,
	                                       -column => 1,
	                                       -padx => 1,
	                                       -pady => 1,
	                                       -sticky => 'w',
	                                   ); 

     my($hSdtimrTrpLabel) = $hSdramCfgFrame->Label(
                                          -text => "Minimum Num of EM_CLK Cycles from Precharge to Activate(T_RP)",
	                                      -font => 'bold 10',
#	                                      -background => 'cyan',
	                                      -justify => 'right',
	                                      )-> grid (
	                                          -row    => 7,
	                                          -column => 0,
	                                          -padx => 1,
	                                          -pady => 1,
	                                          -sticky => 'e',
	                                      );                                 
	                                     
      my($hSdtimrTrp) = $hSdramCfgFrame->Entry(
                                       -relief => 'groove',
                                       -font => 'bold 10',
#                                       -background => 'cyan',
                                       -highlightcolor => 'yellow',                     
                                       -borderwidth => '3',
                                       -width => '8',
                                       -textvariable=>\$sdtimr_TRP,
                                       -validate => "all",
                                       -vcmd =>[ sub 
                                                 { #$sdtimr_TRP = $sdtimr_TRP & ($sdramConfig{'sdtimr'}{'t_rp'}{'mask'} >>
                                                   #$sdramConfig{'sdtimr'}{'t_rp'}{'shift'});
                                                   $sdramConfig{'sdtimr'}{'t_rp'}{'val'} = $sdtimr_TRP - 1; 
                                                  return 1;
                                                 }
                                               ],  	 
                                        )-> grid (
	                                       -row    => 7,
	                                       -column => 1,
	                                       -padx => 1,
	                                       -pady => 1,
	                                       -sticky => 'w',
	                                   );  
	                           
     my($hSdtimrTrcdLabel) = $hSdramCfgFrame->Label(
                                          -text => "Minimum Num of EM_CLK Cycles from Active to Read/Write(T_RCD)",
	                                      -font => 'bold 10',
#	                                      -background => 'cyan',
	                                      -justify => 'right',
	                                      )-> grid (
	                                          -row    => 8,
	                                          -column => 0,
	                                          -padx => 1,
	                                          -pady => 1,
	                                          -sticky => 'e',
	                                      );                                 
	                                     
     my($hSdtimrTrcd) = $hSdramCfgFrame->Entry(
                                       -relief => 'groove',
                                       -font => 'bold 10',
#                                       -background => 'cyan',
                                       -highlightcolor => 'yellow',                     
                                       -borderwidth => '3',
                                       -width => '8',
                                       -textvariable=>\$sdtimr_TRCD,
                                       -validate => "all",
                                       -vcmd =>[ sub 
                                                 { #$sdtimr_TRCD = $sdtimr_TRCD & ($sdramConfig{'sdtimr'}{'t_rcd'}{'mask'} >>
                                                   #$sdramConfig{'sdtimr'}{'t_rcd'}{'shift'});
                                                   $sdramConfig{'sdtimr'}{'t_rcd'}{'val'} = $sdtimr_TRCD - 1; 
                                                   return 1;
                                                 }
                                               ],  	 
                                        )-> grid (
	                                       -row    => 8,
	                                       -column => 1,
	                                       -padx => 1,
	                                       -pady => 1,
	                                       -sticky => 'w',
	                                   );     	 
	                                   
     my($hSdtimrTwrLabel) = $hSdramCfgFrame->Label(
                                          -text => "Minimum Num of EM_CLK Cycles from Last Write to Precharge(T_WR)",
	                                      -font => 'bold 10',
#	                                      -background => 'cyan',
	                                      -justify => 'right',
	                                      )-> grid (
	                                          -row    => 9,
	                                          -column => 0,
	                                          -padx => 1,
	                                          -pady => 1,
	                                          -sticky => 'e',
	                                      );                                 
	                                     
     my($hSdtimrTwr) = $hSdramCfgFrame->Entry(
                                       -relief => 'groove',
                                       -font => 'bold 10',
#                                       -background => 'cyan',
                                       -highlightcolor => 'yellow',                     
                                       -borderwidth => '3',
                                       -width => '8',
                                       -textvariable=>\$sdtimr_TWR,
                                       -validate => "all",
                                       -vcmd =>[ sub 
                                                 { #$sdtimr_TWR = $sdtimr_TWR & ($sdramConfig{'sdtimr'}{'t_wr'}{'mask'} >>
                                                   #$sdramConfig{'sdtimr'}{'t_wr'}{'shift'});
                                                   $sdramConfig{'sdtimr'}{'t_wr'}{'val'} = $sdtimr_TWR - 1;
                                                   return 1;                                                    
                                                 }
                                               ],  	 
                                        )-> grid (
	                                       -row    => 9,
	                                       -column => 1,
	                                       -padx => 1,
	                                       -pady => 1,
	                                       -sticky => 'w',
	                                   );    
	                                   
     my($hSdtimrTrasLabel) = $hSdramCfgFrame->Label(
                                          -text => "Minimum Num of EM_CLK Cycles from Activate to Precharge(T_RAS)",
	                                      -font => 'bold 10',
#	                                      -background => 'cyan',
	                                      -justify => 'right',
	                                      )-> grid (
	                                          -row    => 10,
	                                          -column => 0,
	                                          -padx => 1,
	                                          -pady => 1,
	                                          -sticky => 'e',
	                                      );                                 
	                                     
     my($hSdtimrTras) = $hSdramCfgFrame->Entry(
                                       -relief => 'groove',
                                       -font => 'bold 10',
#                                       -background => 'cyan',
                                       -highlightcolor => 'yellow',                     
                                       -borderwidth => '3',
                                       -width => '8',
                                       -textvariable=>\$sdtimr_TRAS,
                                       -validate => "all",
                                       -vcmd =>[ sub 
                                                 { #$sdtimr_TRAS = $sdtimr_TRAS & ($sdramConfig{'sdtimr'}{'t_ras'}{'mask'} >>
                                                   #$sdramConfig{'sdtimr'}{'t_ras'}{'shift'});
                                                   $sdramConfig{'sdtimr'}{'t_ras'}{'val'} = $sdtimr_TRAS - 1; 
                                                   return 1;
                                                 }
                                               ],  	 
                                        )-> grid (
	                                       -row    => 10,
	                                       -column => 1,
	                                       -padx => 1,
	                                       -pady => 1,
	                                       -sticky => 'w',
	                                   );     	 
	                                   	                   	                                    	 
     my($hSdtimrTrcLabel) = $hSdramCfgFrame->Label(
                                          -text => "Minimum Num of EM_CLK Cycles from Activate to Activate(T_RC)",
	                                      -font => 'bold 10',
#	                                      -background => 'cyan',
	                                      -justify => 'right',
	                                      )-> grid (
	                                          -row    => 11,
	                                          -column => 0,
	                                          -padx => 1,
	                                          -pady => 1,
	                                          -sticky => 'e',
	                                      );                                 
	                                     
     my($hSdtimrTrc) = $hSdramCfgFrame->Entry(
                                       -relief => 'groove',
                                       -font => 'bold 10',
#                                       -background => 'cyan',
                                       -highlightcolor => 'yellow',                     
                                       -borderwidth => '3',
                                       -width => '8',
                                       -textvariable=>\$sdtimr_TRC,
                                       -validate => "all",
                                       -vcmd =>[ sub 
                                                 { #$sdtimr_TRC = $sdtimr_TRC & ($sdramConfig{'sdtimr'}{'t_rc'}{'mask'} >>
                                                   #$sdramConfig{'sdtimr'}{'t_rc'}{'shift'});
                                                   $sdramConfig{'sdtimr'}{'t_rc'}{'val'} = $sdtimr_TRC - 1; 
                                                   return 1;
                                                 }
                                               ],  	 
                                        )-> grid (
	                                       -row    => 11,
	                                       -column => 1,
	                                       -padx => 1,
	                                       -pady => 1,
	                                       -sticky => 'w',
	                                   );     	 

     my($hSdtimrTrrdLabel) = $hSdramCfgFrame->Label(
                                          -text => "Minimum Num of EM_CLK Cycles from Activate to Activate For Different Bank(T_RRD)",
	                                      -font => 'bold 10',
#	                                      -background => 'cyan',
	                                      -justify => 'right',
	                                      )-> grid (
	                                          -row    => 12,
	                                          -column => 0,
	                                          -padx => 1,
	                                          -pady => 1,
	                                          -sticky => 'e',
	                                      );                                 
	                                     
     my($hSdtimrTrrd) = $hSdramCfgFrame->Entry(
                                       -relief => 'groove',
                                       -font => 'bold 10',
#                                       -background => 'cyan',
                                       -highlightcolor => 'yellow',                     
                                       -borderwidth => '3',
                                       -width => '8',
                                       -textvariable=>\$sdtimr_TRRD,
                                       -validate => "all",
                                       -vcmd =>[ sub 
                                                 { #$sdtimr_TRRD = $sdtimr_TRRD & ($sdramConfig{'sdtimr'}{'t_rrd'}{'mask'} >>
                                                   #$sdramConfig{'sdtimr'}{'t_rrd'}{'shift'});
                                                   $sdramConfig{'sdtimr'}{'t_rrd'}{'val'} = $sdtimr_TRRD - 1; 
                                                   return 1;
                                                 }
                                               ],  	 
                                        )-> grid (
	                                       -row    => 12,
	                                       -column => 1,
	                                       -padx => 1,
	                                       -pady => 1,
	                                       -sticky => 'w',
	                                   );     	 
     my($hSdsetrTxsLabel) = $hSdramCfgFrame->Label(
                                          -text => "Minimum Num of EM_CLK Cycles from exit Self-Refresh to next CMD (T_XS)",
	                                      -font => 'bold 10',
#	                                      -background => 'cyan',
	                                      -justify => 'right',
	                                      )-> grid (
	                                          -row    => 13,
	                                          -column => 0,
	                                          -padx => 1,
	                                          -pady => 1,
	                                          -sticky => 'e',
	                                      );                                 
	                                     
     my($hSdsetrTxs) = $hSdramCfgFrame->Entry(
                                       -relief => 'groove',
                                       -font => 'bold 10',
#                                       -background => 'cyan',
                                       -highlightcolor => 'yellow',                     
                                       -borderwidth => '3',
                                       -width => '8',
                                       -textvariable=>\$sdsretr_TXS,
                                       -validate => "all",
                                       -vcmd =>[ sub 
                                                 { 
                                                   $sdramConfig{'sdsretr'}{'t_xs'}{'val'} = $sdsretr_TXS - 1; 
                                                   return 1;
                                                 }
                                               ],  	 
                                        )-> grid (
	                                       -row    => 13,
	                                       -column => 1,
	                                       -padx => 1,
	                                       -pady => 1,
	                                       -sticky => 'w',
	                                   );     	 
	                                   	   	    	                                   	   	       
	       	                                                               	                                   	      	                                   	                                   	                                              	    	                                   	                                       	                                   	                  
	 return;
}



#--------------------------------------------------------------------------------------------
# Save SDRAM Configuration
#--------------------------------------------------------------------------------------------
sub saveSDRAMCfg {
	
	my($win) = shift(@_);
	
	$sdramConfig{'sdcr'}{'val'} = (
		              (($sdramConfig{'sdcr'}{'nm'}{'val'} << $sdramConfig{'sdcr'}{'nm'}{'shift'}) 
		                 & $sdramConfig{'sdcr'}{'nm'}{'mask'})
		            | (($sdramConfig{'sdcr'}{'cl'}{'val'} << $sdramConfig{'sdcr'}{'cl'}{'shift'}) 
		                 & $sdramConfig{'sdcr'}{'cl'}{'mask'})
##		            | (($sdramConfig{'sdcr'}{'bit11_9lock'}{'val'} << $sdramConfig{'sdcr'}{'bit11_9lock'}{'shift'}) 
##		                 & $sdramConfig{'sdcr'}{'bit11_9lock'}{'mask'})	 
##		            | (($sdramConfig{'sdcr'}{'ibank'}{'val'} << $sdramConfig{'sdcr'}{'ibank'}{'shift'}) 
##		                 & $sdramConfig{'sdcr'}{'ibank'}{'mask'})	 
		            | (($sdramConfig{'sdcr'}{'pagesize'}{'val'} << $sdramConfig{'sdcr'}{'pagesize'}{'shift'}) 
		                 & $sdramConfig{'sdcr'}{'pagesize'}{'mask'}));

	$sdramConfig{'sdrcr'}{'val'} = ($sdramConfig{'sdrcr'}{'rr'}{'val'} << $sdramConfig{'sdrcr'}{'rr'}{'shift'})
	                               & $sdramConfig{'sdrcr'}{'rr'}{'mask'};

	$sdramConfig{'sdtimr'}{'val'} = (
		              (($sdramConfig{'sdtimr'}{'t_rfc'}{'val'} << $sdramConfig{'sdtimr'}{'t_rfc'}{'shift'}) 
		                 & $sdramConfig{'sdtimr'}{'t_rfc'}{'mask'})
		            | (($sdramConfig{'sdtimr'}{'t_rp'}{'val'} << $sdramConfig{'sdtimr'}{'t_rp'}{'shift'}) 
		                 & $sdramConfig{'sdtimr'}{'t_rp'}{'mask'})
		            | (($sdramConfig{'sdtimr'}{'t_rcd'}{'val'} << $sdramConfig{'sdtimr'}{'t_rcd'}{'shift'}) 
		                 & $sdramConfig{'sdtimr'}{'t_rcd'}{'mask'})	 
		            | (($sdramConfig{'sdtimr'}{'t_wr'}{'val'} << $sdramConfig{'sdtimr'}{'t_wr'}{'shift'}) 
		                 & $sdramConfig{'sdtimr'}{'t_wr'}{'mask'})	 
		            | (($sdramConfig{'sdtimr'}{'t_ras'}{'val'} << $sdramConfig{'sdtimr'}{'t_ras'}{'shift'}) 
		                 & $sdramConfig{'sdtimr'}{'t_ras'}{'mask'})
		            | (($sdramConfig{'sdtimr'}{'t_rc'}{'val'} << $sdramConfig{'sdtimr'}{'t_rc'}{'shift'}) 
		                 & $sdramConfig{'sdtimr'}{'t_rc'}{'mask'})	 
		            | (($sdramConfig{'sdtimr'}{'t_rrd'}{'val'} << $sdramConfig{'sdtimr'}{'t_rrd'}{'shift'}) 
		                 & $sdramConfig{'sdtimr'}{'t_rrd'}{'mask'}));	
		                 	
    $sdramConfig{'sdsretr'}{'val'} = (($sdramConfig{'sdsretr'}{'t_xs'}{'val'}
                                       << $sdramConfig{'sdsretr'}{'t_xs'}{'shift'}) 
                                       & $sdramConfig{'sdsretr'}{'t_xs'}{'mask'}); 
                                       
	$sdramConfigured = 1;
    killWindow($win);
	
	return;
}


#--------------------------------------------------------------------------------------------
sub cancelSDRAMCfg {
	
	my($win) = shift(@_);
	
	$sdramConfigured = 0;

	$sdramConfig{'sdcr'}{'nm'}{'val'} = $sdramConfig{'sdcr'}{'nm'}{'default'};
	$sdramConfig{'sdcr'}{'cl'}{'val'} = $sdramConfig{'sdcr'}{'cl'}{'default'};
	$sdramConfig{'sdcr'}{'bit11_9lock'}{'val'} = $sdramConfig{'sdcr'}{'bit11_9lock'}{'default'};
	$sdramConfig{'sdcr'}{'ibank'}{'val'} = $sdramConfig{'sdcr'}{'ibank'}{'default'};
	$sdramConfig{'sdcr'}{'pagesize'}{'val'} = $sdramConfig{'sdcr'}{'pagesize'}{'default'};
	$sdramConfig{'sdrcr'}{'rr'}{'val'} = $sdramConfig{'sdrcr'}{'rr'}{'default'};
	$sdramConfig{'sdtimr'}{'t_rfc'}{'val'} = $sdramConfig{'sdtimr'}{'t_rfc'}{'default'};
	$sdramConfig{'sdtimr'}{'t_rp'}{'val'} = $sdramConfig{'sdtimr'}{'t_rp'}{'default'};
	$sdramConfig{'sdtimr'}{'t_rcd'}{'val'} = $sdramConfig{'sdtimr'}{'t_rcd'}{'default'};
	$sdramConfig{'sdtimr'}{'t_wr'}{'val'} = $sdramConfig{'sdtimr'}{'t_wr'}{'default'};
	$sdramConfig{'sdtimr'}{'t_ras'}{'val'} = $sdramConfig{'sdtimr'}{'t_ras'}{'default'};
	$sdramConfig{'sdtimr'}{'t_rc'}{'val'} = $sdramConfig{'sdtimr'}{'t_rc'}{'default'};
	$sdramConfig{'sdtimr'}{'t_rrd'}{'val'} = $sdramConfig{'sdtimr'}{'t_rrd'}{'default'};	
	
	killWindow($win);
	
    return;
}

#--------------------------------------------------------------------------------------------
# Configure Asynchronous RAM
#--------------------------------------------------------------------------------------------
sub asyncRamCfg {

	#====================================================================
	# Initialize Options for Menu Entries
	#====================================================================
	@A1crSSOptions = ('WE_Strobe_Mode', 'Select_Strobe_Mode');
	
    @AwwcrWp0Options = ('Insert_Wait_Cycles_if_AWAIT_is_low','Insert_Wait_Cycles_if_AWAIT_is_High');

   	@A1crAsizeOptions = ('8_bit', '16_bit', '32_bit');
    	 
    @A1crEwOptions = ('Disabled','Enabled');

    #======================================================================
	# Set initial values of all data entries
	#======================================================================
	my($awccr_WP0) = $AwwcrWp0Options[($asyncRamConfig{'awccr'}{'val'} & $asyncRamConfig{'awccr'}{'wp0'}{'mask'}) 
	                 >> $asyncRamConfig{'awccr'}{'wp0'}{'shift'}];
	                 
	my($awccr_MEWC) = ($asyncRamConfig{'awccr'}{'val'} & $asyncRamConfig{'awccr'}{'mewc'}{'mask'})
	                 >> $asyncRamConfig{'awccr'}{'mewc'}{'shift'};
	                 
	my($a1cr_SS) = $A1crSSOptions[($asyncRamConfig{'a1cr'}{'val'} & $asyncRamConfig{'a1cr'}{'ss'}{'mask'})
	                 >> $asyncRamConfig{'a1cr'}{'ss'}{'shift'}];
	                 
	my($a1cr_ASIZE) = $A1crAsizeOptions[($asyncRamConfig{'a1cr'}{'val'} & $asyncRamConfig{'a1cr'}{'asize'}{'mask'})
	                 >> $asyncRamConfig{'a1cr'}{'asize'}{'shift'}];
	                 
	my($a1cr_EW) = $A1crEwOptions[($asyncRamConfig{'a1cr'}{'val'} & $asyncRamConfig{'a1cr'}{'ew'}{'mask'})
	               >> $asyncRamConfig{'a1cr'}{'ew'}{'shift'}];
	               
	my($a1cr_TA) = (($asyncRamConfig{'a1cr'}{'val'} & $asyncRamConfig{'a1cr'}{'ta'}{'mask'})
	               >> $asyncRamConfig{'a1cr'}{'ta'}{'shift'}) + 1;
	               
	my($a1cr_WSETUP) = (($asyncRamConfig{'a1cr'}{'val'} & $asyncRamConfig{'a1cr'}{'w_setup'}{'mask'})
	                   >> $asyncRamConfig{'a1cr'}{'w_setup'}{'shift'}) + 1;
	
	my($a1cr_WSTROBE) = (($asyncRamConfig{'a1cr'}{'val'} & $asyncRamConfig{'a1cr'}{'w_strobe'}{'mask'})
	                   >> $asyncRamConfig{'a1cr'}{'w_strobe'}{'shift'}) + 1;
	                   	
	my($a1cr_WHOLD) = (($asyncRamConfig{'a1cr'}{'val'} & $asyncRamConfig{'a1cr'}{'w_hold'}{'mask'})
	                  >> $asyncRamConfig{'a1cr'}{'w_hold'}{'shift'}) + 1;
	
	my($a1cr_RSETUP) = (($asyncRamConfig{'a1cr'}{'val'} & $asyncRamConfig{'a1cr'}{'r_setup'}{'mask'})
	                  >> $asyncRamConfig{'a1cr'}{'r_setup'}{'shift'}) + 1;
	
	my($a1cr_RSTROBE) = (($asyncRamConfig{'a1cr'}{'val'} & $asyncRamConfig{'a1cr'}{'r_strobe'}{'mask'})
	                  >> $asyncRamConfig{'a1cr'}{'r_strobe'}{'shift'}) + 1;
	
	my($a1cr_RHOLD) = (($asyncRamConfig{'a1cr'}{'val'} & $asyncRamConfig{'a1cr'}{'r_hold'}{'mask'})
	                  >> $asyncRamConfig{'a1cr'}{'r_hold'}{'shift'}) + 1;
		
	my($hAsyncRamCfgWin) = MainWindow->new(
                   -title => "ASYNC RAM Configuration",
                 );
                 
    $hAsyncRamCfgWin->minsize(qw(600 250));
#    $hAsyncRamCfgWin->configure(-background => 'cyan');
    
    my($hFrameButtons) = $hAsyncRamCfgWin->Frame(
                           )->pack(
                           -side   => 'top',
                           -anchor => 'nw',
                           #-padx   => 8,
                           -pady   => 12,
                           #-expand => 1,
                           -fill => 'x',
                          );
   
    my($hAsyncCfgFrame) = $hAsyncRamCfgWin->Frame(
#                             -background => 'cyan',
                           )->pack (
                              -fill => 'both'
                           );
            
   ####################################################################################
   # Define extended Frame - we will populate later                                   #
   ####################################################################################
                                                                                           
    my($hAsyncExtendedFrame) = $hAsyncRamCfgWin->Frame(
     	                     -relief => 'groove',
	                         -borderwidth => 4,
#                             -background => 'cyan',
                           )->pack (
                              -fill => 'both'
                           );
                           
     my($hAwwcrWp0Label) = $hAsyncExtendedFrame->Label(
 	                         -text => "Extended Wait Polarity (AWWCR-WP0)",
	                         -font => 'bold 10',
#	                         -background => 'cyan',
	                         -justify => 'right',
                           );
	                     

	    	
     my($hAwwcrWp0) = $hAsyncExtendedFrame->Scrolled(
                      'Optionmenu',
	                    -relief => 'groove',
#	                    -background => 'cyan',
	                    -borderwidth => 6,
	                    -variable =>\$awccr_WP0,
	                    -font => 'bold 10',
	                    -options => [@AwwcrWp0Options],
		                -command=>[ sub 
		                            { 
			                            $asyncRamConfig{'awccr'}{'wp0'}{'val'}   = 0 if ($awccr_WP0 eq 'Insert_Wait_Cycles_if_AWAIT_is_low');
			                            $asyncRamConfig{'awccr'}{'wp0'}{'val'}   = 1 if ($awccr_WP0 eq 'Insert_Wait_Cycles_if_AWAIT_is_High');
			                            return 1;
			                         }
			                      ],	                    
	                    );                                                    
                          
     
     my($hAwwcrMewcLabel) = $hAsyncExtendedFrame->Label(
 	                         -text => "Maximum Extended Wait Cycles (AWWR-MEWC)(0-127)",
	                         -font => 'bold 10',
#	                         -background => 'cyan',
	                         -justify => 'right',
                           );
	                     
	  
      my($hAwwcrMewc) = $hAsyncExtendedFrame->Entry(
                        -relief => 'groove',
                        -font => 'bold 10',
#                        -background => 'cyan',
                        -highlightcolor => 'yellow',                     
                        -borderwidth => '2',
                        -width => '8',
                        -textvariable=>\$awccr_MEWC,
                        -validate => "all",
                        -vcmd => [ sub 
                                  {
	                                   $asyncRamConfig{'awccr'}{'mewc'}{'val'} = $awccr_MEWC; 
	                                   return 1;
                                   }
                                ]
                       );
                        
                          
    ###########################################################################
    # Populate Main Buttons Frame                                             #
    ###########################################################################
#	     $hFrameButtons->configure(-background => 'yellow');             
	     my($hAsyncRamCfgWinOkButton) = $hFrameButtons->Button(
	                         -text => "OK",
	                         -font => 'bold 11',
	                         -command => [\&saveAsyncRamCfg, 
	                                        $hAsyncRamCfgWin    
	                                      ],                             
	                         )-> pack (
	                            -side => 'left',
	                            -fill => 'x',
	                         );
	  
	    my($hAsyncRamCfgWinClearButton) = $hFrameButtons->Button(
	                              -text => "Clear",
	                              -font => 'bold 11',
	                              -command => [ sub 
	                                            {    
				                                   $awccr_WP0     = $AwwcrWp0Options[$asyncRamConfig{'awccr'}{'wp0'}{'default'}];
									               $awccr_MEWC    = $asyncRamConfig{'awccr'}{'mewc'}{'default'};
											       $a1cr_SS       = $A1crSSOptions[$asyncRamConfig{'a1cr'}{'ss'}{'default'}];
											       $a1cr_ASIZE    = $A1crAsizeOptions[$asyncRamConfig{'a1cr'}{'asize'}{'default'}];
											       $a1cr_EW       = $A1crEwOptions[$asyncRamConfig{'a1cr'}{'ew'}{'default'}];
											       $a1cr_WSETUP   = $asyncRamConfig{'a1cr'}{'w_setup'}{'default'};
											       $a1cr_WSTROBE  = $asyncRamConfig{'a1cr'}{'w_strobe'}{'default'};
											       $a1cr_WHOLD    = $asyncRamConfig{'a1cr'}{'w_hold'}{'default'};
											       $a1cr_RSETUP   = $asyncRamConfig{'a1cr'}{'r_setup'}{'default'};
											       $a1cr_RSTROBE  = $asyncRamConfig{'a1cr'}{'r_strobe'}{'default'};
											       $a1cr_RHOLD    = $asyncRamConfig{'a1cr'}{'r_hold'}{'default'};
											       $a1cr_TA       = $asyncRamConfig{'a1cr'}{'ta'}{'default'};
											       											       										       
											       $asyncRamConfig{'awccr'}{'val'}    = $asyncRamConfig{'awccr'}{'default'};
	                                               $asyncRamConfig{'a1cr'}{'val'}     = $asyncRamConfig{'a1cr'}{'default'};
	                                               
	                                     	       $hAwwcrMewc->configure(-state=>'disabled') if ($a1cr_EW eq 'Disabled');                   
	                                               $hAwwcrMewc->configure(-state=>'normal')if ($a1cr_EW ne 'Disabled');
		  		                   	               $hAwwcrWp0->configure(-state=>'disabled') if ($a1cr_EW eq 'Disabled');                   
	                                               $hAwwcrWp0->configure(-state=>'normal')if ($a1cr_EW ne 'Disabled');                 
										       }
										      ],
			                      )-> pack (
	                              -side => 'left',
	                              );
	                                                          
	     my($hAsyncRamCfgWinCancelButton) = $hFrameButtons->Button(
	                              -text => "Cancel",
	                              -font => 'bold 11',
	                              -command => [ sub 
	                                            {
				                                   $awccr_WP0     = $AwwcrWp0Options[$asyncRamConfig{'awccr'}{'wp0'}{'default'}];
									               $awccr_MEWC    = $asyncRamConfig{'awccr'}{'mewc'}{'default'};
											       $a1cr_SS       = $A1crSSOptions[$asyncRamConfig{'a1cr'}{'ss'}{'default'}];
											       $a1cr_ASIZE    = $A1crAsizeOptions[$asyncRamConfig{'a1cr'}{'asize'}{'default'}];
											       $a1cr_EW       = $A1crEwOptions[$asyncRamConfig{'a1cr'}{'ew'}{'default'}];
		                                            
												   $a1cr_WSETUP   = $asyncRamConfig{'a1cr'}{'w_setup'}{'default'};
												   $a1cr_WSTROBE  = $asyncRamConfig{'a1cr'}{'w_strobe'}{'default'};
												   $a1cr_WHOLD    = $asyncRamConfig{'a1cr'}{'w_hold'}{'default'};
												   $a1cr_RSETUP   = $asyncRamConfig{'a1cr'}{'r_setup'}{'default'};
												   $a1cr_RSTROBE  = $asyncRamConfig{'a1cr'}{'r_strobe'}{'default'};
												   $a1cr_RHOLD    = $asyncRamConfig{'a1cr'}{'r_hold'}{'default'};
												   $a1cr_TA       = $asyncRamConfig{'a1cr'}{'ta'}{'default'};
												 }				
		                                       ],
	                              )-> pack (
	                              -side => 'left',
	                              );
  
 
     ############################################################################
     # Populate A1 Control Register Configuration                               #
     ############################################################################                     
	     my($hA1crAsizeLabel) = $hAsyncCfgFrame->Label(
	 	                         -text => "Data Bus Width (A1CR-ASIZE)",
		                         -font => 'bold 10',
#		                         -background => 'cyan',
		                         -justify => 'right',
	                           )-> grid (
	                             -row    => 0,
	                             -column => 0,
	                             -padx => 1,
	                             -pady => 1,
	                             -sticky => 'e',
	                           ); 
		                     
	
	     my($hA1crAsize) = $hAsyncCfgFrame->Scrolled(
	                      'Optionmenu',
		                    -relief => 'groove',
#		                    -background => 'cyan',
		                    -borderwidth => 6,
		                    -variable =>\$a1cr_ASIZE,
		                    -options => [@A1crAsizeOptions],
		                    -command=>[sub 
		                               { 
			                               $asyncRamConfig{'a1cr'}{'asize'}{'val'}   = 0 if ($a1cr_ASIZE eq '8_bit');
			                               $asyncRamConfig{'a1cr'}{'asize'}{'val'}   = 1 if ($a1cr_ASIZE eq '16_bit');
			                               $asyncRamConfig{'a1cr'}{'asize'}{'val'}   = 2 if ($a1cr_ASIZE eq '32_bit');			                               
			                               return 1;
		                                }
			                          ],
		                    -font => 'bold 10',
		                    )->grid(
		                    -row    => 0,
		                    -column => 1,
		                    -pady => 1,
		                    -padx => 1,
		                    -sticky => 'w',
		                   );                                                       
	                                    		                                                             
	     my($hA1crSSLabel) = $hAsyncCfgFrame->Label(
	 	                         -text => "Strobe Mode Select",
		                         -font => 'bold 10',
#		                         -background => 'cyan',
		                         -justify => 'right',
	                           )-> grid (
	                             -row    => 1,
	                             -column => 0,
	                             -padx => 1,
	                             -pady => 1,
	                             -sticky => 'e',
	                           ); 
		                     
	
	     my($hA1crSS) = $hAsyncCfgFrame->Scrolled(
	                      'Optionmenu',
		                    -relief => 'groove',
#		                    -background => 'cyan',
		                    -borderwidth => 6,
		                    -variable =>\$a1cr_SS,
		                    -font => 'bold 10',
		                    -options => [@A1crSSOptions], 
		                    -command => [ sub 
		                                  {
			                                  $asyncRamConfig{'a1cr'}{'ss'}{'val'} = 0 if ($a1cr_SS eq 'WE_Strobe_Mode');
			                                  $asyncRamConfig{'a1cr'}{'ss'}{'val'} = 1 if ($a1cr_SS eq 'Select_Strobe_Mode');
			                                  return 1;
			                               }
		                                ],
		                    )->grid(
		                    -row    => 1,
		                    -column => 1,
		                    -pady => 1,
		                    -padx => 1,
		                    -sticky => 'w',
		                   );                                                       
	 
		            		 
	     my($hA1crEwLabel) = $hAsyncCfgFrame->Label(
	 	                         -text => "Extended Wait Mode",
		                         -font => 'bold 10',
#		                         -background => 'cyan',
		                         -justify => 'right',
	                           )-> grid (
	                             -row    => 2,
	                             -column => 0,
	                             -padx => 1,
	                             -pady => 1,
	                             -sticky => 'e',
	                           ); 
		                     
	
	     my($hA1crEw) = $hAsyncCfgFrame->Scrolled(
	                      'Optionmenu',
		                    -relief => 'groove',
#		                    -background => 'cyan',
		                    -borderwidth => 6,
		                    -variable =>\$a1cr_EW,
		                    -options => [@A1crEwOptions],
		                    -font => 'bold 10',
	  		                -command=>[ sub 
	  		                            {
		  		                   	       $hAwwcrMewc->configure(-state=>'disabled') if ($a1cr_EW eq 'Disabled');                   
	                                       $hAwwcrMewc->configure(-state=>'normal')if ($a1cr_EW ne 'Disabled');
		  		                   	       $hAwwcrWp0->configure(-state=>'disabled') if ($a1cr_EW eq 'Disabled');                   
	                                       $hAwwcrWp0->configure(-state=>'normal')if ($a1cr_EW ne 'Disabled');     
	                                       $asyncRamConfig{'a1cr'}{'ew'}{'val'} = 0 if ($a1cr_EW eq 'Disabled');
	                                       $asyncRamConfig{'a1cr'}{'ew'}{'val'} = 1 if ($a1cr_EW eq 'Enabled');
	                                       return 1;	                                       
                                        }
                                      ],
                        )->grid(
		                    -row    => 2,
		                    -column => 1,
		                    -pady => 1,
		                    -padx => 1,
		                    -sticky => 'w',
		                   );                                                       
	                              	                                                                                          
        
	     my($hA1crWSetupLabel) = $hAsyncCfgFrame->Label(
	 	                         -text => "Write Setup Time in Num Cycles(1-16)",
		                         -font => 'bold 10',
#		                         -background => 'cyan',
		                         -justify => 'right',
	                           )-> grid (
	                             -row    => 3,
	                             -column => 0,
	                             -padx => 1,
	                             -pady => 1,
	                             -sticky => 'e',
	                           ); 
		                     
	
	     my($hA1crWSetup) = $hAsyncCfgFrame->Entry(
	                        -relief => 'groove',
	                        -font => 'bold 10',
#	                        -background => 'cyan',
	                        -highlightcolor => 'yellow',                     
	                        -borderwidth => '2',
	                        -width => '8',
	                        -textvariable=>\$a1cr_WSETUP,
	                        -validate => "all",
	                        -vcmd => [ sub 
	                                   {
		                                   $asyncRamConfig{'a1cr'}{'w_setup'}{'val'} = $a1cr_WSETUP - 1;
	                                       return 1;
		                                }
	                                 ],
	                       )-> grid (
	                         -row    => 3,
	                         -column => 1,
	                         -padx => 1,
	                         -pady => 1,
	                         -sticky => 'w',
	                       );  
	                       
	     my($hA1crWStrobeLabel) = $hAsyncCfgFrame->Label(
	 	                         -text => "Write Strobe in Num Cycles(1-64)",
		                         -font => 'bold 10',
#		                         -background => 'cyan',
		                         -justify => 'right',
	                           )-> grid (
	                             -row    => 4,
	                             -column => 0,
	                             -padx => 1,
	                             -pady => 1,
	                             -sticky => 'e',
	                           ); 
		                     
	
	     my($hA1crWStrobe) = $hAsyncCfgFrame->Entry(
	                        -relief => 'groove',
	                        -font => 'bold 10',
#	                        -background => 'cyan',
	                        -highlightcolor => 'yellow',                     
	                        -borderwidth => '2',
	                        -width => '8',
	                        -textvariable=>\$a1cr_WSTROBE,
	                        -validate => "all",
	                        -vcmd => [ sub 
	                                   {
		                                   $asyncRamConfig{'a1cr'}{'w_strobe'}{'val'} = $a1cr_WSTROBE - 1;
	                                       return 1;
		                                }
	                                 ],
	                       )-> grid (
	                         -row    => 4,
	                         -column => 1,
	                         -padx => 1,
	                         -pady => 1,
	                         -sticky => 'w',
	                       );  	          
	                       
	     my($hA1crWHoldLabel) = $hAsyncCfgFrame->Label(
	 	                         -text => "Write Hold Time in Num Cycles(1-8)",
		                         -font => 'bold 10',
#		                         -background => 'cyan',
		                         -justify => 'right',
	                           )-> grid (
	                             -row    => 5,
	                             -column => 0,
	                             -padx => 1,
	                             -pady => 1,
	                             -sticky => 'e',
	                           ); 
		                     
	
	     my($hA1crWHold) = $hAsyncCfgFrame->Entry(
	                        -relief => 'groove',
	                        -font => 'bold 10',
#	                        -background => 'cyan',
	                        -highlightcolor => 'yellow',                     
	                        -borderwidth => '2',
	                        -width => '8',
	                        -textvariable=>\$a1cr_WHOLD,
	                        -validate => "all",
	                        -vcmd => [ sub
	                                   {
		                                   $asyncRamConfig{'a1cr'}{'w_hold'}{'val'} = $a1cr_WHOLD - 1;
		                                   return 1;
	                                   }
	                                 ],
	                       )-> grid (
	                         -row    => 5,
	                         -column => 1,
	                         -padx => 1,
	                         -pady => 1,
	                         -sticky => 'w',
	                       );  	                                                        	                                                                         
	                            
	     my($hA1crRSetupLabel) = $hAsyncCfgFrame->Label(
	 	                         -text => "Read Setup Uptime in Num Cycles(1-16)",
		                         -font => 'bold 10',
#		                         -background => 'cyan',
		                         -justify => 'right',
	                           )-> grid (
	                             -row    => 6,
	                             -column => 0,
	                             -padx => 1,
	                             -pady => 1,
	                             -sticky => 'e',
	                           ); 
		                     
	
	     my($hA1crRSetup) = $hAsyncCfgFrame->Entry(
	                        -relief => 'groove',
	                        -font => 'bold 10',
#	                        -background => 'cyan',
	                        -highlightcolor => 'yellow',                     
	                        -borderwidth => '2',
	                        -width => '8',
	                        -textvariable=>\$a1cr_RSETUP,
	                        -validate => "all",
	                        -vcmd => [ sub
	                                   {
		                                   $asyncRamConfig{'a1cr'}{'r_setup'}{'val'} = $a1cr_RSETUP - 1;
		                                   return 1;
	                                   }
	                                 ],
	                       )-> grid (
	                         -row    => 6,
	                         -column => 1,
	                         -padx => 1,
	                         -pady => 1,
	                         -sticky => 'w',
	                       );  
	                       
	     my($hA1crRStrobeLabel) = $hAsyncCfgFrame->Label(
	 	                         -text => "Read Strobe in Num Cycles(1-64)",
		                         -font => 'bold 10',
#		                         -background => 'cyan',
		                         -justify => 'right',
	                           )-> grid (
	                             -row    => 7,
	                             -column => 0,
	                             -padx => 1,
	                             -pady => 1,
	                             -sticky => 'e',
	                           ); 
		                     
	
	     my($hA1crRStrobe) = $hAsyncCfgFrame->Entry(
	                        -relief => 'groove',
	                        -font => 'bold 10',
#	                        -background => 'cyan',
	                        -highlightcolor => 'yellow',                     
	                        -borderwidth => '2',
	                        -width => '8',
	                        -textvariable=>\$a1cr_RSTROBE,
	                        -validate => "all",
	                        -vcmd => [ sub
	                                   {
		                                   $asyncRamConfig{'a1cr'}{'r_strobe'}{'val'} = $a1cr_RSTROBE - 1;
		                                   return 1;
	                                   }
	                                 ],
	                       )-> grid (
	                         -row    => 7,
	                         -column => 1,
	                         -padx => 1,
	                         -pady => 1,
	                         -sticky => 'w',
	                       );  	          
	                       
	     my($hA1crRHoldLabel) = $hAsyncCfgFrame->Label(
	 	                         -text => "Read Hold Time in Num Cycles(1-8)",
		                         -font => 'bold 10',
#		                         -background => 'cyan',
		                         -justify => 'right',
	                           )-> grid (
	                             -row    => 8,
	                             -column => 0,
	                             -padx => 1,
	                             -pady => 1,
	                             -sticky => 'e',
	                           ); 
		                     
	
	     my($hA1crRHold) = $hAsyncCfgFrame->Entry(
	                        -relief => 'groove',
	                        -font => 'bold 10',
#	                        -background => 'cyan',
	                        -highlightcolor => 'yellow',                     
	                        -borderwidth => '2',
	                        -width => '8',
	                        -textvariable=>\$a1cr_RHOLD,
	                        -validate => "all",
	                        -vcmd => [ sub
	                                   {
		                                   $asyncRamConfig{'a1cr'}{'r_hold'}{'val'} = $a1cr_RHOLD - 1;
		                                   return 1;
	                                   }
	                                 ],
	                       )-> grid (
	                         -row    => 8,
	                         -column => 1,
	                         -padx => 1,
	                         -pady => 1,
	                         -sticky => 'w',
	                       );  
	                       
	     my($hA1crTALabel) = $hAsyncCfgFrame->Label(
	 	                         -text => "Turn Around Time in Num Cycles(1-4)",
		                         -font => 'bold 10',
#		                         -background => 'cyan',
		                         -justify => 'right',
	                           )-> grid (
	                             -row    => 9,
	                             -column => 0,
	                             -padx => 1,
	                             -pady => 1,
	                             -sticky => 'e',
	                           ); 
		                     
	
	     my($hA1crTA) = $hAsyncCfgFrame->Entry(
	                        -relief => 'groove',
	                        -font => 'bold 10',
#	                        -background => 'cyan',
	                        -highlightcolor => 'yellow',                     
	                        -borderwidth => '2',
	                        -width => '8',
	                        -textvariable=>\$a1cr_TA,
	                        -validate => "all",
	                        -vcmd => [ sub
	                                   {
		                                   $asyncRamConfig{'a1cr'}{'ta'}{'val'} = $a1cr_TA - 1;
		                                   return 1;
	                                   }
	                                 ],
	                       )-> grid (
	                         -row    => 9,
	                         -column => 1,
	                         -padx => 1,
	                         -pady => 1,
	                         -sticky => 'w',
	                       );  	
	     ########################################################################
	     # Populate Exended Wait Frame - based on EW field value                #
	     ########################################################################                  
			                                                                                              	                                                     
		     $hAwwcrWp0Label-> grid (
		                             -row    => 10,
		                             -column => 0,
		                             -padx => 1,
		                             -pady => 1,
		                             -sticky => 'e',
		                           ); 
			                     
	
		    	
	         $hAwwcrWp0->grid(
		                    -row    => 10,
		                    -column => 1,
		                    -pady => 1,
		                    -padx => 1,
		                    -sticky => 'w',
		                   );                                                       
	                          
		    $hAwwcrWp0->configure(-state=>'disabled') if ($a1cr_EW eq 'Disabled');                   
		    $hAwwcrWp0->configure(-state=>'normal')if ($a1cr_EW eq 'Enabled');  	
		                     
	        $hAwwcrMewcLabel-> grid (
	                             -row    => 11,
	                             -column => 0,
	                             -padx => 1,
	                             -pady => 1,
	                             -sticky => 'e',
	                           ); 
		                     
		  
	        $hAwwcrMewc-> grid (
	                         -row    => 11,
	                         -column => 1,
	                         -padx => 1,
	                         -pady => 1,
	                         -sticky => 'w',
	                       ); 
	                        
		   $hAwwcrMewc->configure(-state=>'disabled') if ($a1cr_EW eq 'Disabled');                   
		   $hAwwcrMewc->configure(-state=>'normal')if ($a1cr_EW eq 'Enabled');  
	                                               	             
                                

    return;
}

#--------------------------------------------------------------------------------------------
# Save Data Entries For Async Ram Configuration
#--------------------------------------------------------------------------------------------
sub saveAsyncRamCfg {
	
	my($win)          = shift(@_);
			
	$asyncRamConfigured = 1;
	
	$asyncRamConfig{'awccr'}{'val'}    = ( (($asyncRamConfig{'awccr'}{'wp0'}{'val'} << $asyncRamConfig{'awccr'}{'wp0'}{'shift'})
	                                       &$asyncRamConfig{'awccr'}{'wp0'}{'mask'})
                                         | (($asyncRamConfig{'awccr'}{'mewc'}{'val'} << $asyncRamConfig{'awccr'}{'mewc'}{'shift'})
                                           &$asyncRamConfig{'awccr'}{'mewc'}{'mask'}));
                                                                              
	$asyncRamConfig{'a1cr'}{'val'}     = ( (($asyncRamConfig{'a1cr'}{'ss'}{'val'} << $asyncRamConfig{'a1cr'}{'ss'}{'shift'})
	                                       &$asyncRamConfig{'a1cr'}{'ss'}{'mask'})
	                                     | (($asyncRamConfig{'a1cr'}{'asize'}{'val'} << $asyncRamConfig{'a1cr'}{'asize'}{'shift'})
	                                       &$asyncRamConfig{'a1cr'}{'asize'}{'mask'})
	                                     | (($asyncRamConfig{'a1cr'}{'ew'}{'val'} << $asyncRamConfig{'a1cr'}{'ew'}{'shift'})
	                                       &$asyncRamConfig{'a1cr'}{'ew'}{'mask'})
                                         | (($asyncRamConfig{'a1cr'}{'w_setup'}{'val'} << $asyncRamConfig{'a1cr'}{'w_setup'}{'shift'})
	                                       &$asyncRamConfig{'a1cr'}{'w_setup'}{'mask'})
                                         | (($asyncRamConfig{'a1cr'}{'w_strobe'}{'val'} << $asyncRamConfig{'a1cr'}{'w_strobe'}{'shift'})
	                                       &$asyncRamConfig{'a1cr'}{'w_strobe'}{'mask'})
                                         | (($asyncRamConfig{'a1cr'}{'w_hold'}{'val'} << $asyncRamConfig{'a1cr'}{'w_hold'}{'shift'})
	                                       &$asyncRamConfig{'a1cr'}{'w_hold'}{'mask'})
                                         | (($asyncRamConfig{'a1cr'}{'r_setup'}{'val'} << $asyncRamConfig{'a1cr'}{'r_setup'}{'shift'})
	                                       &$asyncRamConfig{'a1cr'}{'r_setup'}{'mask'})
                                         | (($asyncRamConfig{'a1cr'}{'r_strobe'}{'val'} << $asyncRamConfig{'a1cr'}{'r_strobe'}{'shift'})
	                                       &$asyncRamConfig{'a1cr'}{'r_strobe'}{'mask'})
                                         | (($asyncRamConfig{'a1cr'}{'r_hold'}{'val'} << $asyncRamConfig{'a1cr'}{'r_hold'}{'shift'})
	                                       &$asyncRamConfig{'a1cr'}{'r_hold'}{'mask'})
                                         | (($asyncRamConfig{'a1cr'}{'ta'}{'val'} << $asyncRamConfig{'a1cr'}{'ta'}{'shift'})
	                                       &$asyncRamConfig{'a1cr'}{'ta'}{'mask'}));   
                                         
                                          
                                                                                    
    killWindow($win);
	
	return;
}



#--------------------------------------------------------------------------------------------
# Set PLL Configuration
#---------------------------------------------------------------------------------------------
sub pllCfg {

	
    my($weight) = 3;
    my($hPllCfgWin) = MainWindow->new(
                   -title => "PLL Configuration",
                 );
                 
    $hPllCfgWin->minsize(qw(600 600));
#    $hPllCfgWin->configure(-background => 'cyan');
    
    $numPllCfgs = 0;
    
    if ($importData == 1) {
	    $int_osc = ($pllCfg{'int_osc'}{'val'} == 0) ? "Internal" : "External";
	    $inputFreq = $pllCfg{'osc'}{'val'};
	    $cpuFreq = $pllCfg{'cpu'}{'val'};
	    $emifFreq = $pllCfg{'emif'}{'val'};
	    $weight = $pllCfg{'weight'}{'val'};
    }
    
    my($hFrameButtons) = $hPllCfgWin->Frame(
                           )->pack(
                           -side   => 'top',
                           -anchor => 'nw',
                           #-padx   => 8,
                           -pady   => 12,
                           #-expand => 1,
                           -fill => 'x',
                          );
   
#    $hFrameButtons->configure(-background => 'yellow');             
  
    my($hPllCfgWinClearButton) = $hFrameButtons->Button(
                              -text => "Clear",
                              -font => 'bold 11',
                              -command => [ sub 
                                            {
	                                          $int_osc = 'Internal';
											  $inputFreq = '';
											  $cpuFreq = '';
											  $emifFreq = '';
											  $weight = 3;
										    }
										   ],
                              )-> pack (
                              -side => 'left',
                              );
                                                          
    my($hPllCfgWinCancelButton) = $hFrameButtons->Button(
                              -text => "Cancel",
                              -font => 'bold 11',
                              -command => [\&cancelPllCfg, $hPllCfgWin],
                              )-> pack (
                              -side => 'left',
                              );
    
    my($hPllCfgFrame) = $hPllCfgWin->Frame(
                           )->pack(
                           -side   => 'top',
                           -anchor => 'nw',
                           -pady   => 12,
                           -fill => 'x',
                          );  
                          
                          
    my($hPllCfgResultsFrame) = $hPllCfgWin->Frame(
                           )->pack(
                           -side   => 'top',
                           -anchor => 'nw',
                           -pady   => 12,
                           -fill => 'x',
                          );  
                                                    
#    $hPllCfgFrame->configure(-background=> 'cyan');
                                                             
    my($hPllInputClkLabel) = $hPllCfgFrame->Label(
                         -text => 'Oscillator Source',
                         -font => 'bold 10',
                         -justify => 'right',
#                         -background => 'cyan',
                         )->grid(
                          -row    => 0,
                          -column => 0, 
                          -padx => 1,
                          -sticky => 'e',
                         );   
                          
    my($hPllInputClk) = $hPllCfgFrame->Scrolled(
                      'Optionmenu',
	                    -relief => 'groove',
#	                    -background => 'cyan',
	                    -borderwidth => 6,
	                    -variable =>\$int_osc,
	                    -font => 'bold 10',
	                    -options => [qw(Internal  External)],
	                    )->grid(
	                    -row    => 0,
	                    -column => 1,
	                    -pady => 5,
	                    -padx => 1,
	                    -sticky => 'w',
	                   );                 

	                   
# 	my($hPllOptSysclk3) = $hPllCfgFrame->Radiobutton(
# 	                          -text => 'Optimize for EMIF (sysclk3)',
#                               -font => 'bold 10',
#                               -justify => 'left',
#                               -value => 3,
#                               -variable => \$sysclk   
#                            ) -> grid (
#                                -row => 2,
#                                -column => 0, 
#                                -padx => 1,
#                                -sticky => 'e',
#                            );
#                            
# 	my($hPllOptSysclk2) = $hPllCfgFrame->Radiobutton(
# 	                          -text => 'Optimize for Periph (sysclk2)',
#                               -font => 'bold 10',
#                               -justify => 'left',
#                               -variable => \$sysclk   
#                            ) -> grid (
#                                -row => 3,
#                                -column => 0, 
#                                -padx => 1,
#                                -sticky => 'e',
#                            );                           
                             
   my($hPllOscClkLabel) = $hPllCfgFrame->Label(
                         -text => 'Oscillator Frequency (MHZ)',
                         -font => 'bold 10',
                         -justify => 'right',
                         ) -> grid (
                          -row => 4,
                          -column => 0, 
                          -padx => 1,
                          -sticky => 'e',
                         );                                             

    my($hOscClk) = $hPllCfgFrame->Entry(
                     -relief => 'groove',
                     -font => 'bold 10',
#                     -background => 'cyan',
                     -highlightcolor => 'yellow',                     
                     -borderwidth => '2',
                     -width => '8',
                     -textvariable=>\$inputFreq,
                     )-> grid (
                       -row    => 4,
                       -column => 1,
                       -padx => 1,
                       -sticky => 'w',
                     );

    my($hPllCpuClkLabel) = $hPllCfgFrame->Label(
                         -text => 'Maximum CPU Frequency Required (MHZ)',
                         -font => 'bold 10',
                         -justify => 'right',
#                         -background => 'cyan',
                         ) -> grid (
                          -row => 5,
                          -column => 0, 
                          -padx => 1,
                          -sticky => 'e',
                         ); 
                                                                   
    my($hPllCpuClk) = $hPllCfgFrame->Entry(
                     -relief => 'groove',
                     -font => 'bold 10',
#                     -background => 'cyan',
                     -highlightcolor => 'yellow',                     
                     -borderwidth => '2',
                     -width => '8',
                     -textvariable=>\$cpuFreq,
                     )-> grid (
                       -row    => 5,
                       -column => 1,
                       -padx => 1,
                       -sticky => 'w',
                     ); 
    
 
    my($hPllEmifClkLabel) = $hPllCfgFrame->Label(
                         -text => 'Max EMIF Frequency Required (MHZ)',
                         -font => 'bold 10',
#                         -background => 'cyan',
                         -justify => 'right',
                         ) -> grid (
                          -row => 6,
                          -column => 0, 
                          -padx => 1,
                          -sticky => 'e',
                         );  
                         
    my($hPllEmifClk) = $hPllCfgFrame->Entry(
                     -relief => 'groove',
                     -font => 'bold 10',
#                     -background => 'cyan',
                     -highlightcolor => 'yellow',                     
                     -borderwidth => '2',
                     -width => '8',
                     -textvariable=>\$emifFreq,
                     )-> grid (
                       -row    => 6,
                       -column => 1,
                       -padx => 1,
                       -sticky => 'w',
                     ); 
    
                                                
    my($hPllCPuWeightLabel) = $hPllCfgFrame->Label(
                         -text => 'Weight to give CPU vs EMIF Frequency Accuracy (1-5)',
                         -font => 'bold 10',
                         -justify => 'right',
#                         -background => 'cyan',
                         ) -> grid (
                          -row => 10,
                          -column => 0, 
                          -padx => 1,
                          -sticky => 'e',
                         ); 
                         
    my($hPllCpuWeight) = $hPllCfgFrame->Entry(
                     -relief => 'groove',
                     -font => 'bold 10',
#                     -background => 'cyan',
                     -highlightcolor => 'yellow',                     
                     -borderwidth => '2',
                     -width => '8',
                     -textvariable=>\$weight,
                     )-> grid (
                       -row    => 10,
                       -column => 1,
                       -padx => 1,
                       -sticky=> 'w',
                     );              
                                                                   
    my($hPllCfgCalcButton) = $hPllCfgFrame->Button(
                              -text => "CALCULATE 'n' Best Solutions",
                              -font => 'bold 11',
                              -command => [\&calcPllCfg, \$emifFreq, \$cpuFreq, \$int_osc, \$inputFreq, \$weight, \$hPllCfgResultsFrame, \$hPllCfgWin],
                           )-> grid (
                               -row    => 12,
                               -column => 1,
                               -pady => 10,
                           );                       
                                                      
 
    return;
}

		
#--------------------------------------------------------------------------------------------
# Calculate possible PLLM,DIV0,DIV1,DIV2,DIV3 values based on input osc frequency
# desired CPU and EMIF frequencies. 	
#--------------------------------------------------------------------------------------------
sub calcPllCfg{
	my($emifFreqPtr)     = shift(@_);
	my($cpuFreqPtr)      = shift(@_);
	my($intOscPtr)       = shift(@_);
	my($inputFreqPtr)    = shift(@_);
	my($weightPtr)       = shift(@_);
	my($resultsWinPtr)      = shift(@_);
	my($parentWinPtr)       = shift(@_);
	
	my($cpuMax)       = $$cpuFreqPtr;
	my($emifMax)      = $$emifFreqPtr;
	my($int_osc)      = ($$intOscPtr eq 'Internal') ? 1: 0;
	my($inputFreq)    = $$inputFreqPtr;
#	my($numSolutions) = $$numSolutionsPtr;  # Unused 'n' best solutions?
	my($weight)       = $$weightPtr;
	my($resultsWin)   = $$resultsWinPtr;
	my($parentWin)    = $$parentWinPtr;
	my($bestSolutionMsg);
	my($index)        = 0;
	my($maxIndex)     = 100;
	my($DEBUG)        = 0;
	my($status)       = 0;
	my($dispText);
	
	my($cfgIndex)     = $numPllCfgs;
	
	++$numPllCfgs;
	
	$pllResults[$cfgIndex] = PLL->new($inputFreq, $cpuMax, $emifMax, $int_osc, $weight, $DEBUG);
	
	$index = $pllResults[$cfgIndex]->{'rIndex'};
	$maxIndex = $pllResults[$cfgIndex]->{'maxIndex'};
	
	my $dispOsc  = $pllResults[$cfgIndex]->{'osc'};	
	my $dispCpu  = $pllResults[$cfgIndex]->{'cpu'}[$index];
	my $dispEmif = $pllResults[$cfgIndex]->{'emif'}[$index];	
	my $dispPllm = $pllResults[$cfgIndex]->{'pllm'}[$index];
	my $dispDiv0 = $pllResults[$cfgIndex]->{'div0'}[$index]-1;
	my $dispDiv1 = $pllResults[$cfgIndex]->{'div1'}[$index]-1;
	my $dispDiv2 = $pllResults[$cfgIndex]->{'div2'}[$index]-1;
	my $dispDiv3 = $pllResults[$cfgIndex]->{'div3'}[$index]-1;
	
	my($hresultsWin) = $resultsWin->Frame(
	                    -relief => 'groove',
#	                    -background => 'cyan',
	                    -borderwidth => 4,
	                    -height => 500,
	                    -width  => 800,
	                    )->pack(
	                      -fill=> 'both'
	                    );               
	
	                    
	                    
	my($hText1)    = $hresultsWin->Label(
	                     -text => "Best Solution For Given Parameters",
	                     -font => 'bold 11',
#	                     -background => 'cyan',
                    )-> grid (
                       -row    => 0,
                       -column => 0,
                       -padx => 1,
                       -sticky => 'w',
                     ); 

	my($hOscFreqLabel) = $hresultsWin->Label(
	                    -text => "OSC Frequency",
	                     -font => 'bold 10',
#	                     -background => 'cyan',
	                     -justify => 'left',
                     )-> grid (
                       -row    => 1,
                       -column => 0,
                       -padx => 1,
                       -sticky => 'w',
                     ); 
	                     
    my($hOscFreq) = $hresultsWin->Entry(
                     -relief => 'groove',
                     -font => 'bold 10',
#                     -background => 'cyan',
                     -highlightcolor => 'yellow',                     
                     -borderwidth => '2',
                     -width => '8',
                     -textvariable=>\$dispOsc,
                     )-> grid (
                       -row    => 1,
                       -column => 1,
                       -padx => 1,
                       -sticky => 'w',
                     ); 
    	                                           	                     	  
	my($hCPuFreqLabel) = $hresultsWin->Label(
	                    -text => "CPU Frequency",
	                     -font => 'bold 10',
#	                     -background => 'cyan',
	                     -justify => 'left',
                         )-> grid (
                         -row    => 2,
                         -column => 0,
                         -padx => 1,
                         -sticky => 'w',
                         ); 
	                     
    my($hCpuFreq) = $hresultsWin->Entry(
                     -relief => 'groove',
                     -font => 'bold 10',
#                     -background => 'cyan',
                     -highlightcolor => 'yellow',                     
                     -borderwidth => '2',
                     -width => '8',
                     -textvariable=>\$dispCpu,
                     )-> grid (
                      -row    => 2,
                      -column => 1,
                      -padx => 1,
                      -sticky => 'w',
                     ); 
    	                      
	my($hEmifFreqLabel) = $hresultsWin->Label(
	                    -text => "Emif Frequency",
	                     -font => 'bold 10',
#	                     -background => 'cyan',
	                     -justify => 'left',
                         )-> grid (
                          -row    => 3,
                          -column => 0,
                          -padx => 1,
                          -sticky => 'w',
                         ); 

    my($hEmifFreq) = $hresultsWin->Entry(
                     -relief => 'groove',
                     -font => 'bold 10',
#                     -background => 'cyan',
                     -highlightcolor => 'yellow',                     
                     -borderwidth => '2',
                     -width => '8',
                     -textvariable=>\$dispEmif,
                     )-> grid (
                      -row    => 3,
                      -column => 1,
                      -padx => 1,
                      -sticky => 'w',
                     ); 
                                                            
	my($hPllMLabel) = $hresultsWin->Label(
	                    -text => "PLLM",
	                     -font => 'bold 10',
#	                     -background => 'cyan',
	                     -justify => 'left',
                       )-> grid (
                        -row    => 4,
                        -column => 0,
                        -padx => 1,
                        -sticky => 'w',
                       ); 
	                     
    my($hPllM) = $hresultsWin->Entry(
                     -relief => 'groove',
                     -font => 'bold 10',
#                     -background => 'cyan',
                     -highlightcolor => 'yellow',                     
                     -borderwidth => '2',
                     -width => '8',
                     -textvariable=>\$dispPllm,
                     )-> grid (
                       -row    => 4,
                       -column => 1,
                       -padx => 1,
                       -sticky => 'w',
                     ); 
                         	                     
	  
	my($hPllDiv0Label) = $hresultsWin->Label(
	                    -text => "PLLDIV0",
	                     -font => 'bold 10',
#	                     -background => 'cyan',
	                     -justify => 'left',
                     )-> grid (
                       -row    => 5,
                       -column => 0,
                       -padx => 1,
                       -sticky => 'w',
                     ); 
	                     
    my($hPllDiv0) = $hresultsWin->Entry(
                     -relief => 'groove',
                     -font => 'bold 10',
#                     -background => 'cyan',
                     -highlightcolor => 'yellow',                     
                     -borderwidth => '2',
                     -width => '8',
                     -textvariable=>\$dispDiv0,
                     )-> grid (
                       -row    => 5,
                       -column => 1,
                       -padx => 1,
                       -sticky => 'w',
                     ); 	                     
	                      	  
	  
	my($hPllDiv1Label) = $hresultsWin->Label(
	                    -text => "PLLDIV1",
	                     -font => 'bold 10',
#	                     -background => 'cyan',
	                     -justify => 'left',
                        )-> grid (
                         -row    => 6,
                         -column => 0,
                         -padx => 1,
                         -sticky => 'w',
                        ); 	                     
	                     
     
	my($hPllDiv1) = $hresultsWin->Entry(
                     -relief => 'groove',
                     -font => 'bold 10',
#                     -background => 'cyan',
                     -highlightcolor => 'yellow',                     
                     -borderwidth => '2',
                     -width => '8',
                     -textvariable=>\$dispDiv1,
                     )-> grid (
                      -row    => 6,
                      -column => 1,
                      -padx => 1,
                      -sticky => 'w',
                     ); 	                     
	                      	  	                      	  
	                     	  
	my($hPllDiv2Label) = $hresultsWin->Label(
	                    -text => "PLLDIV2",
	                     -font => 'bold 10',
#	                     -background => 'cyan',
	                     -justify => 'left',
                         )-> grid (
                          -row    => 7,
                          -column => 0,
                          -padx => 1,
                          -sticky => 'w',
                         ); 	
	  
	my($hPllDiv2) = $hresultsWin->Entry(
                     -relief => 'groove',
                     -font => 'bold 10',
#                     -background => 'cyan',
                     -highlightcolor => 'yellow',                     
                     -borderwidth => '2',
                     -width => '8',
                     -textvariable=>\$dispDiv2,
                     )-> grid (
                      -row    => 7,
                      -column => 1,
                      -padx => 1,
                      -sticky => 'w',
                     ); 	                     
	                      	 
	my($hPllDiv3Label) = $hresultsWin->Label(
	                    -text => "PLLDIV3",
	                     -font => 'bold 10',
#	                     -background => 'cyan',
	                     -justify => 'left',
                         )-> grid (
                          -row    => 8,
                          -column => 0,
                          -padx => 1,
                          -sticky => 'w',
                         ); 	
	  
	my($hPllDiv3) = $hresultsWin->Entry(
                     -relief => 'groove',
                     -font => 'bold 10',
#                     -background => 'cyan',
                     -highlightcolor => 'yellow',                     
                     -borderwidth => '2',
                     -width => '8',
                     -textvariable=>\$dispDiv3,
                     )-> grid (
                      -row    => 8,
                      -column => 1,
                      -padx => 1,
                      -sticky => 'w',
                     ); 	                                       	                         
                     
     $hText1->configure(-state=>'disabled')  if ($index ne $pllResults[$cfgIndex]->{'rIndex'});
     $hText1->configure(-state=>'normal')  if ($index eq $pllResults[$cfgIndex]->{'rIndex'});
                    
    my($hresultsButtonFrame) = $hresultsWin->Frame(
#                                -background => 'yellow',
                               )->grid(
                                -row => 9,
                                -column => 0,
                                -columnspan => 2,
                                -ipadx => 2,
                                -ipady => 2,
                                -padx => 2,
                                -pady => 2,
                                );
                                  	  
	my($hPrevious) = $hresultsButtonFrame->Button(
                              -text => "PREV",
                              -font => 'bold 10',
#                              -background => 'cyan',
                              -command => [\&updatePllDisplay, \$index, -1, $cfgIndex, $maxIndex, \$hresultsWin, \$hText1, \$dispCpu,
                                           \$dispEmif, \$dispPllm, \$dispDiv0, \$dispDiv1, \$dispDiv2, \$dispDiv3],
                     )->grid(
                      -row => 0,
                      -column => 0,
                     );    
                                                         	                         
                         
                           
   $hPrevious->configure(-state=>'disabled') if ($index <= 0);
                         
   my($hNext) = $hresultsButtonFrame->Button(
                -text => "NEXT",
                -font => 'bold 10',
#                -background => 'cyan',
                -command => [\&updatePllDisplay, \$index, 1, $cfgIndex, $maxIndex, \$hresultsWin, \$hText1, \$dispCpu,
                             \$dispEmif, \$dispPllm, \$dispDiv0, \$dispDiv1, \$dispDiv2, \$dispDiv3],
                )->grid(
                 -row => 0,
                 -column => 1,
                );    
                      
                           
   my($hCancel) = $hresultsButtonFrame->Button(
                  -text => "Cancel",
                  -font => 'bold 10',
#                  -background => 'cyan',
                  -command => [ sub 
                                {
	                                for($i=0;$i<$cfgIndex; ++$i) 
	                                {
	                                   PLL->delete($pllResults[$i]);
                                    }  
	                                killWindow($hresultsWin);
                                }
                              ],
                 )->grid(
                  -row => 0,
                  -column => 2,
                 );     
                     
   my($hOk) = $hresultsButtonFrame->Button(
               -text => "OK",
               -font => 'bold 10',
#               -background => 'cyan',
               -command => [ sub 
                             {
	                            savePllCfg($hresultsWin, $parentWin, $cfgIndex, $index);
                              }
                            ],
                            )->grid(
                             -row => 0,
                             -column => 3,
                            );                                                                            
	return;
}

#--------------------------------------------------------------------------------------------
# Save PLL Configuration
#--------------------------------------------------------------------------------------------
sub savePllCfg {
	
	my($win)       = shift(@_);
	my($parentWin) = shift(@_);
	my($cfgIndex)  = shift(@_);
	my($index)     = shift(@_);
	
	my($i);
	
	$pllConfigured = 1;

	$pllCfg{'osc'}{'val'}  = $pllResults[$cfgIndex]->{'osc'};		
	$pllCfg{'cpu'}{'val'}  = $pllResults[$cfgIndex]->{'cpu'}[$index];
	$pllCfg{'emif'}{'val'} = $pllResults[$cfgIndex]->{'emif'}[$index];	
    $pllCfg{'weight'}{'val'}  = $pllResults[$cfgIndex]->{'weight'};		
	$pllCfg{'int_osc'}{'val'}  = $pllResults[$cfgIndex]->{'int_osc'};		

	$pllCfg{'pllm'}{'val'} = $pllResults[$cfgIndex]->{'pllm'}[$index];
	$pllCfg{'div0'}{'val'} = $pllResults[$cfgIndex]->{'div0'}[$index]-1;
	$pllCfg{'div1'}{'val'} = $pllResults[$cfgIndex]->{'div1'}[$index]-1;
	$pllCfg{'div2'}{'val'} = $pllResults[$cfgIndex]->{'div2'}[$index]-1;
	$pllCfg{'div3'}{'val'} = $pllResults[$cfgIndex]->{'div3'}[$index]-1;    

    for($i=0;$i<$cfgIndex; ++$i) 
	{
	     PLL->delete($pllResults[$i]);
    }
#	printf("Osc Freq  = %f\n",$pllCfg{'osc'});		
# 	printf("CPU Freq  = %f\n",$pllCfg{'cpu'});
# 	printf("Emif Freq = %f\n",$pllCfg{'emif'});
# 	printf("PLLM  = %f\n",$pllCfg{'pllm'});
# 	printf("PLLDIV0  = %f\n",$pllCfg{'div0'});
# 	printf("PLLDIV1  = %f\n",$pllCfg{'div1'});
# 	printf("PLLDIV2  = %f\n",$pllCfg{'div2'});
# 	printf("PLLDIV3  = %f\n",$pllCfg{'div3'});

	killWindow($win);
	killWindow($parentWin);
	
	return;
}

#--------------------------------------------------------------------------------------------
# Update PLL Display as User Browses Thru Calculated Solutions
#--------------------------------------------------------------------------------------------
sub updatePllDisplay {
    my($indexPtr)    = shift(@_);
    my($direction)   = shift(@_);
    my($cfgIndex)    = shift(@_);
    my($maxIndex)    = shift(@_);
    my($winPtr)      = shift(@_);
    my($textWinPtr)  = shift(@_);
    my($dispCpuPtr)  = shift(@_);
    my($dispEmifPtr)  = shift(@_);
    my($dispPllmPtr)  = shift(@_);
    my($dispDiv0Ptr)  = shift(@_);
    my($dispDiv1Ptr)  = shift(@_);
    my($dispDiv2Ptr)  = shift(@_);
    my($dispDiv3Ptr)  = shift(@_);

       
    my($index)    = $$indexPtr;
    my($textWin)  = $$textWinPtr;
    my($win)      = $$winPtr;
    
    $index = (($index >= 1) ? --$index : $index) if ($direction eq -1);
    $index = (($index < ($maxIndex-1)) ? ++$index : $index) if ($direction eq 1);
   

    
    $$dispCpuPtr  = $pllResults[$cfgIndex]->{'cpu'}[$index];
    $$dispEmifPtr = $pllResults[$cfgIndex]->{'emif'}[$index];	
  	$$dispPllmPtr = $pllResults[$cfgIndex]->{'pllm'}[$index];
    $$dispDiv0Ptr = $pllResults[$cfgIndex]->{'div0'}[$index]-1;
    $$dispDiv1Ptr = $pllResults[$cfgIndex]->{'div1'}[$index]-1;
    $$dispDiv2Ptr = $pllResults[$cfgIndex]->{'div2'}[$index]-1;
    $$dispDiv3Ptr = $pllResults[$cfgIndex]->{'div3'}[$index]-1;
 
#     printf("Index[%d], MaxIndex[%d], :%s:\n",$index,$maxIndex,$$dispText{'cpu'});
    $$indexPtr = $index;
    
   $textWin->configure(-state=>'disabled')  if ($index ne $pllResults[$cfgIndex]->{'rIndex'});
   $textWin->configure(-state=>'normal')  if ($index eq $pllResults[$cfgIndex]->{'rIndex'});
 
    return;   
}

#--------------------------------------------------------------------------------------------
# User has decided to cancel current configuration for PLL
#--------------------------------------------------------------------------------------------
sub cancelPllCfg {
	
	my($win) = shift(@_);
	
	$pllConfigured = 0;

	
	killWindow($win);
	
    return;
}



#--------------------------------------------------------------------------------------------
# Set I2C Clock Configuration
#---------------------------------------------------------------------------------------------
sub i2cClkCfg {

	my($clkh) = $i2cClkCfg{'clkh'}{'default'};
	my($clkl) = $i2cClkCfg{'clkl'}{'default'};
	my($psc) = $i2cClkCfg{'psc'}{'default'};
	my($highClock) = $i2cClkCfg{'highClock'}{'default'};
	my($lowClock) = $i2cClkCfg{'lowClock'}{'default'};
    my($weight) = $i2cClkCfg{'weight'}{'default'};
    
    
    
    my($hI2cClkCfgWin) = MainWindow->new(
                   -title => "I2C Clock Configuration",
                 );
                 
    $hI2cClkCfgWin->minsize(qw(600 600));
    
 #   $numI2cCfgs = 0;
        
    if (($importData == 1) || ($pllConfigured == 1)){
	    $int_osc = ($pllCfg{'int_osc'}{'val'} == 0) ? "Internal" : "External";
	    $inputFreq = $pllCfg{'osc'}{'val'};
	    $cpuFreq = $pllCfg{'cpu'}{'val'};
	    $emifFreq = $pllCfg{'emif'}{'val'};
	    $weight =  $i2cClkCfg{'weight'}{'val'}  if ($importData == 1);
	    $highClock = $i2cClkCfg{'highClock'}{'val'} if ($importData == 1);
	    $lowClock = $i2cClkCfg{'lowClock'}{'val'} if ($importData == 1);
	    $psc = $i2cClkCfg{'psc'}{'val'} if ($importData == 1);
	    $clkl = $i2cClkCfg{'clkl'}{'val'} if ($importData == 1);
	    $clkh = $i2cClkCfg{'clkh'}{'val'} if ($importData == 1);
    }
    
    my($hFrameButtons) = $hI2cClkCfgWin->Frame(
                           )->pack(
                           -side   => 'top',
                           -anchor => 'nw',
                           #-padx   => 8,
                           -pady   => 12,
                           #-expand => 1,
                           -fill => 'x',
                          );
   
#    $hFrameButtons->configure(-background => 'yellow');             
   my($hI2cClkCfgWinOkButton) = $hFrameButtons->Button(
                              -text => "Ok",
                              -font => 'bold 11',
                              -command => [\&saveI2cClkCfg, 
                                            $hI2cClkCfgWin, 
                                            \$psc,
                                            \$clkl,
                                            \$clkh,
#                                            \$lowClock,
#                                            \$highClock,
#                                            \$weight
                                           ],

                              )-> pack (
                              -side => 'left',
                              );
                                    
    my($hI2cClkCfgWinClearButton) = $hFrameButtons->Button(
                              -text => "Clear",
                              -font => 'bold 11',
                              -command => [ sub 
                                            {
	                                          $psc = 0;
											  $clkl = 0;
											  $clkh = 0;
#											  $highClock = '';
#											  $lowClock = '';
#											  $weight = 3;
										    }
										   ],
                              )-> pack (
                              -side => 'left',
                              );
                                                          
    my($hI2cClkCfgWinCancelButton) = $hFrameButtons->Button(
                              -text => "Cancel",
                              -font => 'bold 11',
                              -command => [\&cancelI2cClkCfg, $hI2cClkCfgWin],
                              )-> pack (
                              -side => 'left',
                              );
    
    my($hI2cClkCfgFrame) = $hI2cClkCfgWin->Frame(
                           )->pack(
                           -side   => 'top',
                           -anchor => 'nw',
                           -pady   => 12,
                           -fill => 'x',
                          );  
                          
                          
    my($hI2cClkCfgResultsFrame) = $hI2cClkCfgWin->Frame(
                           )->pack(
                           -side   => 'top',
                           -anchor => 'nw',
                           -pady   => 12,
                           -fill => 'x',
                          );  

############################################################################################
# Place holder for future enhancements - i.e. provide same frequency calculation
# capability as done for PLL at future date
############################################################################################                                                                              
#    $hPllCfgFrame->configure(-background=> 'cyan');
                                                             
#     my($hI2cClkHighClockLabel) = $hI2cClkCfgFrame->Label(
#                          -text => 'Required High Clock Hold Time in ns',
#                          -font => 'bold 10',
#                          -justify => 'right',
# #                         -background => 'cyan',
#                          )->grid(
#                           -row    => 0,
#                           -column => 0, 
#                           -padx => 1,
#                           -sticky => 'e',
#                          );   
#                           

#     my($hI2cHighClock) = $hI2cClkCfgFrame->Entry(
#                      -relief => 'groove',
#                      -font => 'bold 10',
# #                     -background => 'cyan',
#                      -highlightcolor => 'yellow',                     
#                      -borderwidth => '2',
#                      -width => '8',
#                      -textvariable=>\$highClock,
#                      )-> grid (
#                        -row    => 0,
#                        -column => 1,
#                        -padx => 1,
#                        -sticky => 'w',
#                      );
                     	                   
#     my($hI2cClkLowClockLabel) = $hI2cClkCfgFrame->Label(
#                          -text => 'Required Low Clock Hold Time in ns',
#                          -font => 'bold 10',
#                          -justify => 'right',
# #                         -background => 'cyan',
#                          ) -> grid (
#                           -row => 2,
#                           -column => 0, 
#                           -padx => 1,
#                           -sticky => 'e',
#                          );                                             

#     my($hI2cLowClock) = $hI2cClkCfgFrame->Entry(
#                      -relief => 'groove',
#                      -font => 'bold 10',
# #                     -background => 'cyan',
#                      -highlightcolor => 'yellow',                     
#                      -borderwidth => '2',
#                      -width => '8',
#                      -textvariable=>\$lowClock,
#                      )-> grid (
#                        -row    => 2,
#                        -column => 1,
#                        -padx => 1,
#                        -sticky => 'w',
#                      );

 
    my($hI2cClkPscLabel) = $hI2cClkCfgFrame->Label(
                         -text => 'System Clock Divide Down (PSC)',
                         -font => 'bold 10',
                         -justify => 'right',
#                         -background => 'cyan',
                         ) -> grid (
                          -row => 3,
                          -column => 0, 
                          -padx => 1,
                          -sticky => 'e',
                         );                                             

    my($hI2cPsc) = $hI2cClkCfgFrame->Entry(
                     -relief => 'groove',
                     -font => 'bold 10',
#                     -background => 'cyan',
                     -highlightcolor => 'yellow',                     
                     -borderwidth => '2',
                     -width => '8',
                     -textvariable=>\$psc,
                     )-> grid (
                       -row    => 3,
                       -column => 1,
                       -padx => 1,
                       -sticky => 'w',
                     );    
                     
   
   my($hI2cClkClkhLabel) = $hI2cClkCfgFrame->Label(
                         -text => 'High Clock Divide Down (CLKH)',
                         -font => 'bold 10',
                         -justify => 'right',
#                         -background => 'cyan',
                         ) -> grid (
                          -row => 4,
                          -column => 0, 
                          -padx => 1,
                          -sticky => 'e',
                         );                                             

    my($hI2cClkh) = $hI2cClkCfgFrame->Entry(
                     -relief => 'groove',
                     -font => 'bold 10',
#                     -background => 'cyan',
                     -highlightcolor => 'yellow',                     
                     -borderwidth => '2',
                     -width => '8',
                     -textvariable=>\$clkh,
                     )-> grid (
                       -row    => 4,
                       -column => 1,
                       -padx => 1,
                       -sticky => 'w',
                     );    
                                                                                 
    my($hI2cClkClklLabel) = $hI2cClkCfgFrame->Label(
                         -text => 'Low Clock Divide Down (CLKL)',
                         -font => 'bold 10',
                         -justify => 'right',
#                         -background => 'cyan',
                         ) -> grid (
                          -row => 5,
                          -column => 0, 
                          -padx => 1,
                          -sticky => 'e',
                         );                                             

    my($hI2cCLkl) = $hI2cClkCfgFrame->Entry(
                     -relief => 'groove',
                     -font => 'bold 10',
#                     -background => 'cyan',
                     -highlightcolor => 'yellow',                     
                     -borderwidth => '2',
                     -width => '8',
                     -textvariable=>\$clkl,
                     )-> grid (
                       -row    => 5,
                       -column => 1,
                       -padx => 1,
                       -sticky => 'w',
                     );  
                       
###############################################################################################
# Place Holder For Future Enhancements 
###############################################################################################                                                
#     my($hI2cClkWeightLabel) = $hI2cClkCfgFrame->Label(
#                          -text => 'Weight to give High vs Low Hold Time Accuracy (1-5)',
#                          -font => 'bold 10',
#                          -justify => 'right',
# #                         -background => 'cyan',
#                          ) -> grid (
#                           -row => 10,
#                           -column => 0, 
#                           -padx => 1,
#                           -sticky => 'e',
#                          ); 
#                          
#     my($hI2cClkWeight) = $hI2cClkCfgFrame->Entry(
#                      -relief => 'groove',
#                      -font => 'bold 10',
# #                     -background => 'cyan',
#                      -highlightcolor => 'yellow',                     
#                      -borderwidth => '2',
#                      -width => '8',
#                      -textvariable=>\$weight,
#                      )-> grid (
#                        -row    => 10,
#                        -column => 1,
#                        -padx => 1,
#                        -sticky=> 'w',
#                      );              
                                                                   
#     my($hI2cClkCfgCalcButton) = $hI2cClkCfgFrame->Button(
#                               -text => "CALCULATE 'n' Best Solutions",
#                               -font => 'bold 11',
#                               -command => [\&calcI2cClkCfg, \$lowClock, \$highClock, \$int_osc, \$inputFreq, \$weight, \$hPllCfgResultsFrame, \$hPllCfgWin],
#                            )-> grid (
#                                -row    => 12,
#                                -column => 1,
#                                -pady => 10,
#                            );                       
#                                                       
#  
    return;
}


#--------------------------------------------------------------------------------------------
# User has decided to cancel current configuration for I2C Clock 
#--------------------------------------------------------------------------------------------
sub cancelI2cClkCfg {
	
	my($win) = shift(@_);
	
	$i2cClkConfigured = 0;
	
	killWindow($win);
	
    return;
}



#--------------------------------------------------------------------------------------------
# Save I2C Clock Configuration
#--------------------------------------------------------------------------------------------
sub saveI2cClkCfg {
	
	my($win)   = shift(@_);
	my($pscPtr)   = shift(@_);
	my($clklPtr)  = shift(@_);
	my($clkhPtr)  = shift(@_);
	my($lowClockPtr)  = shift(@_);
	my($highClockPtr) = shift(@_);
	my($weightPtr)    = shift(@_);
	
	my($i);
	
	$i2cClkConfigured = 1;
	
	$i2cClkCfg{'psc'}{'val'} = $$pscPtr;
	$i2cClkCfg{'clkl'}{'val'} = $$clklPtr;
	$i2cClkCfg{'clkh'}{'val'} = $$clkhPtr;
#	$i2cClkCfg{'lowClock'}{'val'} = $$lowClockPtr;
#	$i2cClkCfg{'highClock'}{'val'} = $$highClockPtr;
#	$i2cClkCfg{'weight'}{'val'} = $$weightPtr;
	
   
# 	$pllCfg{'osc'}{'val'}  = $pllResults[$cfgIndex]->{'osc'};		
# 	$pllCfg{'cpu'}{'val'}  = $pllResults[$cfgIndex]->{'cpu'}[$index];
# 	$pllCfg{'emif'}{'val'} = $pllResults[$cfgIndex]->{'emif'}[$index];	
#     $pllCfg{'weight'}{'val'}  = $pllResults[$cfgIndex]->{'weight'};		
# 	$pllCfg{'int_osc'}{'val'}  = $pllResults[$cfgIndex]->{'int_osc'};		

# 	$pllCfg{'pllm'}{'val'} = $pllResults[$cfgIndex]->{'pllm'}[$index];
# 	$pllCfg{'div0'}{'val'} = $pllResults[$cfgIndex]->{'div0'}[$index]-1;
# 	$pllCfg{'div1'}{'val'} = $pllResults[$cfgIndex]->{'div1'}[$index]-1;
# 	$pllCfg{'div2'}{'val'} = $pllResults[$cfgIndex]->{'div2'}[$index]-1;
# 	$pllCfg{'div3'}{'val'} = $pllResults[$cfgIndex]->{'div3'}[$index]-1;    

#     for($i=0;$i<$cfgIndex; ++$i) 
# 	{
# 	     PLL->delete($pllResults[$i]);
#     }
#	printf("Osc Freq  = %f\n",$pllCfg{'osc'});		
# 	printf("CPU Freq  = %f\n",$pllCfg{'cpu'});
# 	printf("Emif Freq = %f\n",$pllCfg{'emif'});
# 	printf("PLLM  = %f\n",$pllCfg{'pllm'});
# 	printf("PLLDIV0  = %f\n",$pllCfg{'div0'});
# 	printf("PLLDIV1  = %f\n",$pllCfg{'div1'});
# 	printf("PLLDIV2  = %f\n",$pllCfg{'div2'});
# 	printf("PLLDIV3  = %f\n",$pllCfg{'div3'});

	killWindow($win);
	
	return;
}



#------------------------------------------------------------------------------
#  The following files are a set of utilities used to parse option strings, etc.
#------------------------------------------------------------------------------
sub parseOptionsString {

  my ($inputStr)  = shift(@_);
  my ($inputArgs) = {@_};
  my ($args);
  my ($arg);
  my ($strArgs);

  %$args = %$inputArgs;
  
  $strArgs = parseCommandString($inputStr);
  
  %$args = (%$args, %$strArgs);

  return $args;
}
	
#--------------------------------------------------------------------------------------------
sub parseArguments {

  my ($argv)           = shift(@_);
  my ($inputDefaults)  = {@_};
  my ($status)         = 0;
  my ($args)           = {};
  my ($argStr)         = "";
  my ($rcStr)          = "";
  my ($strArgs);
  my ($key);
  my ($arg);

  # Baseline defaults for librray specific arguments
  my ($defaults) = {
	  -i =>"",
	  -o =>"",
	  -mode => "FLASH",
	  -cfg  => "",
  };

  # Assign base defaults to args
  foreach $key (keys %$defaults) {
    $args->{$key} = $defaults->{$key};
  }

  # Assign input defaults to args
  foreach $key (keys %$inputDefaults) {
    $args->{$key} = $inputDefaults->{$key};
  }

  # Need to double quote all entries in @argv that have white-space
  foreach $arg (@$argv) {
    if ($arg =~ m/\s+/) {
      $arg = "\"$arg\"";
    }
  }

  # Combine command line arguments into a string
  $argStr = join(' ',@$argv);

  # Assign the argument string to the return hash
  $args->{_argument_str_} = $argStr;

  # Parse the argument string into a hash
  $strArgs = parseCommandString($argStr);

  # Assign the string arguments to the arguments hash
  foreach $key (keys %$strArgs) {
    $args->{$key} = $strArgs->{$key};
  }

  # Set help level
  $args->{-h} = 2 if ($args->{-hh});

  # This is used by the setupLog() subroutine to get original command line arguments
  $args->{_original_args_} = $args;

  return $args;
}

#------------------------------------------------------------------------------
sub parseCommandString {

  my ($inputStr) = shift(@_);
  my ($args);
  my ($state);
  my (@chars);
  my ($ch);
  my (@tokens);
  my ($token);
  my ($string);
  my ($switch);
  my (@nonSwitches);

  #*******************************************************
  # Tokenizing state machine, turn string into array of
  # strings and tokens.
  #*******************************************************

  # Initialize state information
  @chars  = split(//,$inputStr);
  $ch     = shift(@chars);
  $state  = 'base';
  $token  = "";
  $string = "";
  @tokens = ();

  # Enter the state machine
  while (1) {

    #=== base state =======================================
    if ($state eq 'base') {

      if (! defined $ch) {
        $state = 'done';
        next;
      }
      elsif ($ch eq '#') {
        $state = 'done';
        next;
      }
      elsif ($ch =~ m/\s/) {
        $ch = shift(@chars);
        next;
      }
      elsif ($ch eq '"') {
        $ch = shift(@chars);
        $state = 'string';
        next;
      }
      else {
        $token = $ch;
        $ch = shift(@chars);
        $state = 'token';
        next;
      }
    }

    #=== token state ======================================
    elsif ($state eq 'token') {

      if (! defined $ch) {
        push(@tokens,$token);
        $token = "";
        $state = 'base';
        next;
      }
      if ($ch eq '#') {
        push(@tokens,$token);
        $token = "";
        $state = 'base';
        next;
      }
      elsif ($ch =~ m/\s/) {
        push(@tokens,$token);
        $token = "";
        $state = 'base';
        next;
      }
      else {
        $token .= $ch;
        $ch = shift(@chars);
        next;
      }
    }

    #=== string state =====================================
    elsif ($state eq 'string') {

      if (! defined $ch) {
        push(@tokens, $token);
        $token = "";
        $state = 'base';
        next;
      }
      elsif ($ch eq '"') {
        push(@tokens, $token);
        $token = "";
        $ch = shift(@chars);
        $state = 'base';
        next;
      }
      else {
        $token .= $ch;
        $ch = shift(@chars);
        next;
      }
    }

    #=== done state =======================================
    elsif ($state eq 'done') {
      last;
    }

  }


  #*******************************************************
  # Switch parsing state machine, turn tokens and strings
  # into switch hash values.
  #*******************************************************

  # Initialize state information
  $args = {};
  @nonSwitches = ();
  $token = shift(@tokens);
  $state = 'base';
  $switch = "";

  # Enter the state machine
  while (1) {

    #=== base state =======================================
    if ($state eq 'base') {

      if (! defined $token) {
        $state = 'done';
        next;
      }

      elsif ($token =~ m/^-/) {
        $switch = $token;
        $token = shift(@tokens);
        $state = 'switch';
        next;
      }

      else {
        push(@nonSwitches,$token);
        $token = shift(@tokens);
        next;
      }
    }

    #=== switch state =====================================
    elsif ($state eq 'switch') {

      if (! defined $token) {
        $args->{$switch} = '1';
        $switch = "";
        $state = 'done';
        next;
      }

      elsif ($token =~ m/^-/) {
        $args->{$switch} = '1';
        $switch = "";
        $state = 'base';
        next;
      }

      else {
        $args->{$switch} = $token;
        $token = shift(@tokens);
        $state = 'base';
        next;
      }
    }

    #=== done state =======================================
    elsif ($state eq 'done') {
      last;
    }
  }

  #*******************************************************
  # Done with state machine parsing
  #*******************************************************

  return $args;
}

#--------------------------------------------------------------------------------------------
sub doHelp {

  my ($helpText)  = shift(@_);


    print $helpText;


  exit();
}   
#----------------------------------------------------------------------------------------------

__END__
###############################################################################################
# End of File
###############################################################################################
