#!/tools/misc/bin/perl
#
# This script converts TSSI wgl files to TDX .vec files
# 
# Usage:
#       wgl2vec XXX.wgl [XXX.vec|-]
# or    wgl2vec XXX.wdb [XXX.vec|-]
#
# Ommision of the second parameter or using "-" specifies output is written
# to standard output.

#
# Change Log:
#
# 5/27/1999 - Many changes.
#	1.) Skipping unsupported blocks
#	2.) Case insensitive
#	3.) Support for ALLVEC states (via merging)
#	4.) Support for repeat statements in pattern
#	5.) Max Vectors
#

#
# if the following is asserted then scan data will be output in the
# order defined by the groups in the scancell section.  Otherwise, the
# order defined in the scanchain section will be used.
$groupScanOrder = 0;

# inserts necessary syntax in output file to convert between "command" and
# "vector" modes.
sub setCommandMode {
    ($newVal) = @_;

    if ($commandMode == 0 && $newVal == 1) {
	print $VECOUT "\${";
    }
    if ($commandMode == 1 && $newVal == 0) {
	print $VECOUT "\n\$}\n";
    }
    $commandMode = $newVal;
}
 
# take $_ and look for fractional time duration (eg.  399.9ns) and
# attempt to convert to integral numbers of ps
sub deFloatTime {
    local ($line) = $_;

    while ($line =~ /(\d+[\.]\d+)n[sS]/) {
    
	$ns = $1;		# time in ns
	$ps = int ($ns * 1000);
    	$err++, print ERR "Time of ${ns}ns truncated to ${ps}ps\n"
	    if ($ps != $ns * 1000);
    	$line =~ s/${ns}n[sS]/${ps}pS/;
    }
# A couple of clean up items
    $line =~ s/([^\d])0[pn][sS]/${1}0nS/;
    $line =~ s/(np)s(?=\s*:)/${1}S/g;

    $_ = $line;
}

# get a non-comment line (comments start with hash's and extend to the end
# of the line.  Also filter out { database annotations }
sub wgl {
    local ($line);

    return "" unless ($line = <INF>);
    while ($line =~ /^\s*$/  && !eof) 
    {
	$line .=  <INF>;
    }
    $line =~ s/\043.*$//;	# kill any comment to the end of line
    $line =~ s/\x7b[^\x7d]*\x7d//g;	# 0173 == {,  0175 == }
    while ($line =~ /\x7b/  && ! eof (INF)) {
	$line .= <INF>;
#	print "[$line]";
	$line =~ s/\x7b[^\x7d]*\x7d//g;	
    }
#    print "wgl:$line";
    return $line;
}

sub skipUnsupportedBlock {
    local ($blockName) = @_;

    if ($blockName ne "nowarn" && $blockName ne "") {
        print STDERR "$.: WARNING: Can't understand block \"$blockName\" - ignoring it.\n";
        print ERR "$.: WARNING: Can't understand block \"$blockName\" - ignoring it.\n";
        $warn++;
    }

    while ($_ = &wgl) {
        last if (/^\s*end/);
    }
}

sub mergeTwoPatterns {
    local ($pattern1, $pattern2) = @_;
    local @pattern_list1;
    local @pattern_list2;
    local $final_pattern;

    @pattern_list1 = split //, $pattern1;
    @pattern_list2 = split //, $pattern2;
    $final_pattern = "";

    if ($#pattern_list1 != $#pattern_list2) {
        print STDERR "ERROR: Can not merge uneven length ($#pattern_list1 and $#pattern_list2) patterns\n";
        print ERR "ERROR: Can not merge uneven length ($#pattern_list1 and $#pattern_list2) patterns\n";
        return;
    }
    while (@pattern_list1) {
        $value1 = shift @pattern_list1;
        $value2 = shift @pattern_list2;
        if ($value1 eq $value2 || $value2 eq 'X') {
            $final_pattern = join '', $final_pattern, $value1;
        } elsif ($value1 eq 'X') {
            $final_pattern = join '', $final_pattern, $value2;
        } else {
            print STDERR "ERROR: Conflicts during merging patterns\n";
            print ERR "ERROR: Conflicts during merging patterns\n";
            $final_pattern = join '', $final_pattern, 'X';
        }
    }

    return $final_pattern;
}

$usage = "wgl2vec [-max num] XXX.wgl|XXX.wdb [XXX.vec|-]\n" ;

$inputForm = 0;
$maxVector = 0;

for ($i = 0; $i <= $#ARGV; $i++)
{
    $arg = $ARGV[$i];
    if ($arg =~ /^-/) {
	if ($arg eq "-max") {
	    $i++;
	    $maxVector = $ARGV[$i];
	} else {
	    die ("$arg not recognized.  Usage: $usage");
	}
    } else {
	last;
    }
}

die ("Missing argument.  Usage: $usage") unless ($#ARGV - $i >= 0);
die ("Excess arguments.  Usage: $usage") unless ($ARGV - $i < 2);

$inputFile = $ARGV[$i++];
$outputFile = "-";		# stdout, by default
$outputFile = $ARGV[$i] if ($i <= $#ARGV);

if ($outputFile eq "-") {
    $VECOUT = STDOUT;
} else {
    open(VEC,  ">$outputFile") || die ("Cannot write $outputFile: $!\n");
    $VECOUT = VEC;
}
# open files for output
open(ERR, ">Errors_wgl2vec");
open (SCN, ">wgl.scn");
@scanchains = ();


if ($inputFile =~ /[.]wdb$/) {
    die ("Can't locate TDS; Please setenv TDSDIR\n") unless ($ENV{"TDSDIR"});
    $tempFile = "tmp$$.wgl";
    # need to wgl-out the data first
    open (WGLOUT, ">wglout.do") || die ("Cannot write scenario file: $!\n");
    print WGLOUT <<EndOfScenario;
_command.1/Command = out
_command.1/TdsVersion = Version 10.0.0.6
out.1/CAEOut = WGL
out.1/SourceWDB = $inputFile
out.1/createPinNames = YES
out.1/KeepSourceWDB = YES
out.1/WGLsectionOut = ALL_NO_EQUATIONS
out.1/WGLmessages = NONE
out.1/WGLaddressing = AUTO-INCREMENT
out.1/WGLfile = $tempFile
out.1/TmpPrefix = .
out.1/BinPattern = NO
EndOfScenario
    close WGLOUT;
    $tds = $ENV{"TDSDIR"}."/tds";
    $cmd = "$tds do wglout.do";
    $rc = 0xffff & system ("$cmd 1> Errors 2>&1 ");

    if ($rc == 0) {
	
    } elsif ($rc == 0xff00) {
	print "Command \"$cmd\" failed: $!\n";
    } elsif ($rc > 0x80) {
	$rc >>= 8;
	print "\"$cmd\" ran with non-zero exit status $rc\n";
    } else {
	print "\"$cmd\" ran with ";
	if ($rc & 0x80) {
	    $rc &= ~0x80;
	print "coredump from ";
	}
	print "signal $rc\n";
    }
    if ($rc != 0) {
	open (CERR, "Errors");
	while (<CERR>) {
	    print ERR $_;
	}
	close CERR;
	print ERR "WGL out-converter failed\n";
	exit 1;
    }
    unlink Errors;
    unlink "wglout.do";
    open (INF, $tempFile) || die ("Cannot open for read $tempFile: $!\n");
} else {
    open (INF, $inputFile) || die ("Cannot open for read $inputFile: $!\n");
}


$INPUT = 2;
$OUTPUT = 1;
$BIDIR = 3;
%dirmap = ("input", $INPUT, "output", $OUTPUT, "bidir", $BIDIR);
%radmap = ("octal", 3, "hex", 4, "binary", 1);
$fndsig = 0 ;
$vecnum = 0 ;
$err = 0;
$warn = 0;
$commandMode = 0;
$allscan_pending = 0;
while ($_ = &wgl) {
#    print  "***$_";
    
    if ($allscan_pending == 1) {
        print "chainlength for group ALLSCAN is $chainlength{ALLSCAN}\n";
        $allscan_pending = 0;
    }
    s/\043.*$//;
    next if (/^\s*$/);
    next if (/^\s*waveform/i);
    if (/^\s*signal\s*$/i) {
	# --------------------------------------------------------
	# process signal block.  Remember each signal and output
	# bus definitions as necessary.
	# --------------------------------------------------------
	$fndsig = 1 ;
	$_ = &wgl;
	while (!/^\s*end\s*$/) {
	    s/^[\t\s]+//;		# lose leading white space
	    if (/(\S+)\s*[[]\s*(\d+)\s*\.\.\s*(\d+)\s*[]]\s*:\s*(\w+)\s*/) {
		# ------------------------------------------------
		# bus definition  <sig>[<msb>..<lsb>] : <dir>
		# ------------------------------------------------
		$sig = $1; 
		$msb = $2;
		$lsb = $3;
		$dir = $4;
		$_ = $';
		$sig =~ s/"//g;
		$width = ($msb - $lsb) + 1;
		$width = - $width if ($width < 0);
		if (/radix ((binary|octal|hexadecimal))/) {
		    $rad = $1;
		    $rad = "hex" if ($rad eq "hexadecimal");
		    # calculate the character width of the field
		    $radwidth = $radmap{$rad}; # 3 or 4
		    $width = int(($width + $radwidth - 1)/$radwidth);
		} else {
		    $rad = "binary";
		    # character width is same was number of bits
		}
print "sig:<$sig>\n";
		$radix{$sig} = $rad;
		$colWidth{$sig} = $width;
		$direction{$sig} = $dirmap{$dir};  # 1, 2, 3 for output, input or bidir
		unless ($dirmap{$dir}) {
		    print STDERR "ERROR: Invalid direction '$dir' for signal '$sig'\n";
		    print ERR "ERROR: Invalid direction '$dir' for signal '$sig'\n";
		    $err++;
		}
		while ($_ !~ /;/) {	# look for end of clause
		    $_ = &wgl;
		}
		&setCommandMode (1);
		print $VECOUT "\nbus $sig $rad ";
		if ($msb <= $lsb) {
		    foreach $index ($msb..$lsb) {
			print $VECOUT "$sig\[$index\] ";
		    }
		} else {
		    for ($index = $msb; $index >= $lsb; $index--) {
			print $VECOUT "$sig\[$index\] ";
		    }
		}
			
		print $VECOUT "\n";
		if ($dir eq "bidir") {
		    print $VECOUT "\nbus ${sig}__in $rad ";
		    if ($msb <= $lsb) {
			foreach $index ($msb..$lsb) {
			    print $VECOUT "$sig\[$index\]___I ";
			}
		    } else {
			for ($index = $msb; $index >= $lsb; $index--) {
			    print $VECOUT "$sig\[$index\] ";
			}
		    }
		    print $VECOUT "\n";
		}
		$_ = &wgl;
	    } elsif (/^(\S+)\s*:\s*(\w+)\s*/) {
		# ------------------------------------------------
		# scalar definition
		# ------------------------------------------------
		$sig = $1;
		$dir = $2;
		$_ = $';
	        $sig =~ s/"//g;
		$radix{$sig} = 1;
		$colWidth{$sig} = 1;
		$direction{$sig} = $dirmap{$dir};  # 1, 2, 3 for output, input or bidir
		unless ($dirmap{$dir}) {
		    print STDERR "ERROR: Invalid direction '$dir' for signal '$sig'\n";
		    print ERR "ERROR: Invalid direction '$dir' for signal '$sig'\n";
		    $err++;
		}
		while ($_ !~ /;/) {	# look for end of clause
		    $_ = &wgl;
		}
		$_ = &wgl;
	    } else {
		print STDERR "ERROR: signal defn not recognised: $_\n";
		print ERR "ERROR: signal defn not recognised: $_\n";
		$err++;
		$_ = &wgl;
		next;
	    }
	}
    } elsif (/^\s*scancell\s+/i) {
        push (@scanchains, ALLSCAN) if ($groupScanOrder);
        $allscan_pending = 0;
        $chainlength{ALLSCAN} = 0;
        $numgroups = 0;
	@allscan = ();
	while (($_ = &wgl) && ! /^\s*end\s*/) 
	{
	    #
	    # either a simple cell id (optionally in double-quotes, followed by a ';')
	    # OR a group [<cell>, <cell>,...];
	    #
	    $_ .= &wgl until ($_ =~ /;/);
	    if (/\s*(\S+)\s*\[\s*/) {
		$groupname = $1;
		$group = $';
		$group .= &wgl until ($group =~ /;/);
		$group =~ s/\s*\][^;]*;\s*//;
		$group =~ s/"//g;  #"
		print SCN "-- group $groupname:\n" if ($groupScanOrder);
		$ct = 0;
		foreach $sig (split (/\s*,\s*/, $group)) {
		    if ($scancell{$sig} != 1) {
                        print SCN "SCN $sig\n" if ($groupScanOrder);
		        $scancell{$sig} = 1;
                    }
		    $ct++;
		}
                $numgroups++;
		$chainlength{$groupname} = $ct;
		print "group $groupname has length $ct\n" if ($groupScanOrder);
		push (@scanchains, $groupname) if ($groupScanOrder);
	    } else {
		# simple scan cell declaration

                $chainlength{ALLSCAN} += 1;
	    
		chop;
		s/"//g;
		s/;//;
		s/\s//g;
		$scancell{$_} = 1;
		push (@allscan, $_);
                $allscan_pending = 1;
            }
	}
        if ($groupScanOrder && $numgroups == 0) {
		foreach $sig (@allscan) {
		        print SCN "SCN $sig\n";
                }
        }
    } elsif (/^\s*scanchain\s+/i) {
	# Defines the scan chain(s).  Example:
	# scanchain
	#    chain1 [ SC1_IN, datareg[0], latchA, SC1_OUT] : radix octal;
	#    chain2 [ SC2_IN, datareg[2], datareg[3], ff2];
	# end
	# 
	while (($_ = &wgl) && ! /^\s*end\s*/) 
	{
	    $_ .= &wgl until (/;/);
	    $lineCopy = $_;
	    $radix = "binary";
	    if (/\s*(\w+)\s*\[/) {
                undef $scanin_port;
                undef $scanout_port;
		$chainname = $1;
		$tail = $';
		if ($tail =~ /\]\s*(:\s*radix\s+((binary|octal|decimal|hex|hexadecimal|symbolic))\s*)?;/) {
		    $sigs = $`;
		    $radix = $1 if ($1);
		    push (@scanchains,$chainname) unless ($groupScanOrder);
		    #
		    # deconstruct scan chain
		    #
		    @sigs = split (/\s*,\s*/, $sigs);
		    @sane_sigs = ();
		    print SCN "-- chain $chainname:\n" unless ($groupScanOrder);
                    $idx = 0;
		    foreach $sig (@sigs) {
                        $idx++, next if ($sig =~ /!/);
			$sig =~ s/"//g;
                        $sig =~ s/\s//g;
                        $sig =~ s/\n//g;
			if ($sig =~ /\[\d+\.\.\d+\]/) {
			    print STDERR "ERROR: Can't handle range: $sig\n";
			    print ERR "ERROR: Can't handle range: $sig\n";
			    $err++;
			}
                        if ($scancell{$sig}) {
			    push (@sane_sigs, $sig);
			    print SCN "SCN $sig\n"  unless ($groupScanOrder);
			} else {
			    if ($idx > 0 && $idx < $#sigs) {
				print STDERR "ERROR: $sig is not a declared scancell\n";
				print ERR "ERROR: $sig is not a declared scancell\n";
				$err++;
                            } elsif ($idx == 0) {
                                $scanin_port = $sig;
                            } elsif ($idx == $#sigs) {
                                $scanout_port = $sig;
                            }
			}
		        $idx++;
		    }
                    $chainlength{$chainname} = @sane_sigs;
	            print "scan chain $chainname is length $chainlength{$chainname}\n";
                    if ($scanin_port) {
	                print "        scan in port is $scanin_port\n";
                    }
                    if ($scanout_port) {
	                print "        scan out port is $scanout_port\n";
                    }
		} else {
		    print "didn't find end of scan chain definition:\n$tail\n";
		}
	    } else {
		print "Don't understand scanchain line:\n$.:$lineCopy";
	    }
	}
        print "--INFO: wrote TDX scan chain definition to ./wgl.scn\n";
    } elsif (/^\s*scanstate/i) {
	# defines scan data:
	# scanState
	# 	state1 := chain(xxx00010100111);
	#	state2 := chain(xx100001000111);
	# end
	while (($_ = &wgl) && ! /^\s*end\s*/) 
	{
	    $_ .= &wgl until (/;/);
	    $lineCopy = $_;
	    if (/^\s*(\w+)\s*:=\s*/) {
		$stateName = $1;
		$_ = $';
		if (/^(\w+)\s*\(([^)]+)\)/) {
		    $scanChain = $1;
		    $scanData = $2;
		    $scanData =~ s/\s//g;
		    $scanState{$stateName} = $scanData;
		    $stateGroup{$stateName} = $scanChain;
                    $len = length ($scanData);
                    if ($len != $chainlength{$scanChain}) {
			if ($chainlength{$scanChain} > 0) {
			    print "$.:Data length of $stateName ($len) differs from expected length ($chainlength{$scanChain}) of chain $scanChain\n";
			    print "$scanData<" if ($len < 400);
			} else {
			    print "$.: ERROR: Scanstate $stateName references unknown scan chain $scanChain\n";
			}
                        $err++;
                    }
		} else {
		    print "Failed to parse scan data in:\n$.:$lineCopy\n";
		}
	    } else {
		print "Scan state line not recognized:\n$.:$lineCopy\n";
	    }
	}

    } elsif (/^\s*timeplate\s+/i) { # print timeplate as-is
	# --------------------------------------------------------
	# timeplate definition
	# --------------------------------------------------------
	# TDX gets upset if you use 'DEFAULT_TIMEPLATE' because it has
	# a hard-coded timeplate of that name
        # Not anymore. The name of the hardcoded timeplate has been
        # changed to TDX_DEFAULT_TIMEPLATE
	&setCommandMode (1);
	&deFloatTime;
	print $VECOUT  "\n$_";
	do { 
	    $_ = &wgl;
	    &deFloatTime;
	    print $VECOUT $_;
	} while (! /^\s*end\s*$/);
    } elsif (/^\s*pattern\s+\w+/i) {
	# --------------------------------------------------------
	# process pattern block up to 'end'
	# first build a signal list from the entries within the brackets
	# --------------------------------------------------------
	print "Scanchains: @scanchains\n";
	if ($patternCount > 0) {
	    print ERR "$.: Can handle at most one pattern block\n";
	    exit 1;
	}
	$last1Vector = "nonscan";
	$last2Vector = "nonscan";
	$paras = $';
	chop $paras;
	while ($paras !~ /\)/) {
	    $more = &wgl;
	    chop $more;
	    $more =~ s/^\s+//;
	    $paras .= $more;
	}
	$paras =~ s/^\s*\(//;
	$paras =~ s/\)//;
	$count = 0;		# index into various arrays, one element per signal
	$linect = 0;
	$tdxParas = "";
	foreach $sig (split (/\s*,\s*/, $paras)) {
	    next if ($sig =~ /^\s*$/); # skip blanks
	    $rem = $sig;
	    $isinput = $isoutput = 0;
	    if ($sig =~ / *:O$/) {
		$sig = $`;
		$isoutput = 1;
	    }
	    if ($sig =~ / *:I$/) {
		$sig = $`;
		$isinput = 1;
	    }
            $sig =~ s/\s+$//;
            $sig =~ s/"//g;
	    $dir = $direction{$sig};
	    if (!$dir) {
		print ERR "signal '$sig' not specified in signals block\n";
	    } else {
		if ($isinput && ($dir & $INPUT) == 0) {
		    print ERR "$rem is invalid because '$sig' has direction $dir\n";
		}
		if ($isoutput && ($dir & $OUTPUT) == 0) {
		    print ERR "$rem is invalid because '$sig' has direction $dir\n";
		}
	    }
	    if ($isinput || $isoutput) {
		$newdir = $isinput * $INPUT + $isoutput * $OUTPUT;
		$dir = $dir & $newdir;
	    }
	    $bitwidth = 1;
	    if ($direction{$sig} == 3 && ($dir & $INPUT) == $INPUT) {
		$tdxParas .= "${sig}___I ";
		$coldir[$count] = $INPUT;
		$radix[$count] = $radix{$sig};
		$colWidth[$count] = $colWidth{$sig};
		$totalWidth += $colWidth{$sig};
		$count++;
		$dir = $dir & (~$INPUT);
	    }
	    if ($dir != 0) {
		$tdxParas .= "$sig ";
		$coldir[$count] = $dir;
		$radix[$count] = $radix{$sig};
		$colWidth[$count] = $colWidth{$sig};
		$count++;
		$totalWidth += $colWidth{$sig};
	    }
	    $linect = 0, $tdxParas .= "\\\n   " if ($linect++ > 10);
	}
	&setCommandMode (1);
	print $VECOUT "\n\nvector in $tdxParas\n";
	$currentTimeplate = "";
	while (($_ = &wgl) && ! /^\s*end\s*/  && !eof) 
	{
	    # --------------------------------------------------------
	    # process each 'vector' clause within the block
	    # --------------------------------------------------------
	    $_ .= &wgl until (/;/ || /end/ || eof);
	    s/^\s+//;		# get rid of leading space
	    s/\n//g;		# get rid of newlines
            break if (/^end/);
	    $repeatCount = 1;
	    $_ = $', $repeatCount = $1 if (/^repeat\s+(\d+)\s+/);
#	    print "==$_==\n";
	    if (/^(vector|scan)\s*\(([^)]+)\)\s*:=\s*\[([^]]+)\]/) {
	        $cmd = $1;
	        $address = $2;
                $data = $3;
		$postfix = $';
#print "cmd:$cmd address:$address  data:$data\n";
		&setCommandMode (0);
		if ($address =~ /(\w+)$/) {
		    $template = $1;
		    if ($template ne $lastTemplate) {
			print $VECOUT "\$$template  ";
			$lastTemplate = $template;
		    }
		}
		$data =~ s/ //g;
		#
		# "don't care" (-) must be converted to Z for input, X for output
		#
	        @data = split (//, $data);
		$data = "";
	        for ($i = 0; $i <= $#data; $i++) 
		{
		    $dat = $data[$i];
		    if ($dat eq "-") {
			$dat = ($coldir[$i] == $INPUT) ? "Z" : "X";
		    }
		    $data .= $dat;
		}
		$thisLength = length($data);
		if ($thisLength != $totalWidth && !$wrongLength) {
		    $wrongLength = 1;
		    print STDERR "$.: ERROR: expected $totalWidth characters in vector, got $thisLength\n";
		    print ERR "$.: ERROR: expected $totalWidth characters in vector, got $thisLength\n";
		    $err++;
                }

		#
		# We will print out repeatCount vectors, all of them
		# identical. This assumes that there isn't a repeat of
		# the scan vectors.
		#
		while ($repeatCount > 0) {
		    print $VECOUT "    $data\n";
		    $last2Vector = $last1Vector;
		    $last1Vector = "nonscan";
		    $vectorCount++;
		    $repeatCount--;
		}

		if ($cmd eq "scan") {
		    #
		    # $prefix contains (one or more) scan data of the form:
		    #  , input[chainname:statename]
		    #
		    undef %in;
		    undef %out;

		    $last1Vector = "scan";

                    $allscan = 0;
                    $inpattern = "";
                    $outpattern = "";

		    $_ = $postfix;
                    $lineCopy = $prefix;
		    while (/\s*,\s*(input|output)\[\s*(\w+)\s*:\s*(\w+)\s*\]/) {
			$dir = $1;
			$chainname = $2;
			$statename = $3;
			$postfix = $';
                        $chainname = $stateGroup{$statename}
                            if ($groupScanOrder); 

                        if ($chainname eq "ALLSCAN") {
                            $allscan = 1;
                        }
			if ($dir eq "input") {
                            if ($allscan == 1) {
                                if ($inpattern eq "") {
                                    $inpattern = $scanState{$statename};
                                } else {
                                    $inpattern = &mergeTwoPatterns($inpattern, $scanState{$statename});
                                }
                            } else {
			        $in{$chainname} = $statename;
                            }
			} else {
                            if ($allscan == 1) {
                                if ($outpattern eq "") {
                                    $outpattern = $scanState{$statename};
                                } else {
                                    $outpattern = &mergeTwoPatterns($outpattern, $scanState{$statename});
                                }
                            } else {
			        $out{$chainname} = $statename;
                            }
			}
			$_ = $postfix;
		    }
		    unless (/^\s*;\s*$/) {
			print "Tail of scan line not recognised: \n$.:<$_>\n";
		    }
		    #
		    # print scan data for every scanchain.  First input, 
		    # then output (per TDX convention)
		    #
		    print $VECOUT "SCAN_IN ";
                    if ($allscan == 1) {
			print $VECOUT "$inpattern  $outpattern\n";
                    } else {
		        foreach $chain (@scanchains)
		        {
			    next if ($chain eq "ALLSCAN");
			    if ($in{$chain} ne "") {
                                $pat = $scanState{$in{$chain}};
			        print $VECOUT "$pat ";
				if ($pat eq "") {
				    print STDERR "ERROR: scanstate $in{$chain} not defined\n";
				    print ERR "ERROR: scanstate $in{$chain} not defined\n";
                                    $err++;
                                }
			    } else {
                                print $VECOUT "X"x$chainlength{$chain}, " ";
#    			    print ERR "ERROR: input state data for chain $chain NOT requested at line $.\n";
#    			    print ERR "ERROR: (TDX requires a complete definition of scan data for every scan vector)\n" unless ($compDefnNeeded);
#                                $compDefnNeeded = 1;
#                                $err++;
			    }
		        }
		        print $VECOUT "  ";
		        foreach $chain (@scanchains)
		        {
			    next if ($chain eq "ALLSCAN");
			    if ($out{$chain} ne "") {
                                $pat = $scanState{$out{$chain}};
			        print $VECOUT "$pat ";
				if ($pat eq "") {
				    print STDERR "ERROR: scanstate $out{$chain} not defined\n";
				    print ERR "ERROR: scanstate $out{$chain} not defined\n";
                                    $err++;
				}
			    } else {
                                print $VECOUT "X"x$chainlength{$chain}, " ";
#    			    print ERR "ERROR: output state data for chain $chain NOT requested at line $.\n";
#    			    print ERR "ERROR: (TDX requires a complete definition of scan data for every scan vector)\n" unless ($compDefnNeeded);
#                               $compDefnNeeded = 1;
#                                $err++;
			    }
		        }
		        print $VECOUT "\n";
                    }
		} else {
		    if ($maxVector > 0 && $vectorCount >= $maxVector) {
			if ($last1Vector eq "nonscan" && $last2Vector eq "nonscan") {
			    print STDERR "Max Vector exceeded ($vectorCount, max=$maxVector)\n";
			    &skipUnsupportedBlock ("nowarn");
			    last;
			}
		    }
		}
	    } else {
		print STDERR "$.: ERROR: Can't translate '$_'\n";
		print ERR "$.: ERROR: Can't translate '$_'\n";
		$err++;
	    }
	} 
        # ---------------------------------------------------
        # end of "pattern" processing section
        #
    } elsif (/^\s*(equationdefaults)/i) {
        &skipUnsupportedBlock ($1);
    } elsif (/^\s*(equationsheet)/i) {
        &skipUnsupportedBlock ($1);
    } elsif (/^\s*(format)/i) {
        &skipUnsupportedBlock ($1);
    } elsif (/^\s*(pingroup)/i) {
        &skipUnsupportedBlock ($1);
    } elsif (/^\s*(register)/i) {
        &skipUnsupportedBlock ($1);
    } elsif (/^\s*(timegen)/i) {
        &skipUnsupportedBlock ($1);
    } elsif (/^\s*(timeset)/i) {
        &skipUnsupportedBlock ($1);
    } elsif (/^\s*(subroutine)/i) {
        &skipUnsupportedBlock ($1);
    } elsif (/^\s*end/i) {
	$count = 0;
	while ($_ = &wgl)
	{
	    $count++ unless (/^\s+$/);
	}
	if ($count > 0) {
	    print STDERR "ERROR: Warning: $count non-blank lines beyond 'end'\n";
	    print ERR "ERROR: Warning: $count non-blank lines beyond 'end'\n";
	    $err++;
	}
	break;
    } else {
	print STDERR "$.: WARNING: ignoring line: $_\n";
	print ERR "$.: WARNING: ignoring line: $_\n";
	$warn++;
    }
	
}

print "--INFO: translated $vectorCount vectors\n";
print "--INFO: found $warn warnings (see ./Errors_wgl2vec)\n" if ($warn > 0);
print "--INFO: found $err errors (see ./Errors_wgl2vec)\n" if ($err > 0);
exit 1 if ($err > 0);
exit 0;
