#!/usr/local/bin/perl5 -w

$input = 'chaintest.scan';
$output= "OUT.out";

open (INFILE,"$input")||die "cannot open $input";
open(OUTFILE,">$output")||die "canoot\n";

#######################################################
$/=";";
$ct_scanout = 0;

while (<INFILE>) {
  chomp;
  last if /^SCAN_CELLS/;
  $seen_CHAIN_TEST=1  if /CHAIN_TEST/;
  next unless /apply/ && $seen_CHAIN_TEST;
  die "Missing ';' in 'apply' line" if /apply[^;]*\n/; 

  $ct_scanout = 1 if /apply\s*"grp[0-9]_unload"/;
  next unless /\t*chain\s+"chain([0-9])"/;
  $chain[$1] = cleanup($_);
  &printout if $1 == 7;
}

sub printout {
  if ($ct_scanout ) {
    for ($i=0;$i<@{$chain[3]};$i++){
      for (@chain) { 
        next unless defined;
        $_->[$i] =~ s/0/L/g; 
        $_->[$i] =~ s/1/H/g;
      }
      my @chars = map $_->[$i], @chain;
      print OUTFILE "\n(ct_so\n", join("", @chars), "\n )";
    }
    $ct_scanout=0;
  } elsif ($ct_scanout==0) {
    for ($i=0;$i<@{$chain[3]};$i++) {
      for (@chain) {
        next unless defined;
        $_->[$i] =~ s/X/0/g;
      }
      my @chars = map $_->[$i], @chain;
      print OUTFILE "\n(ct_si  $ct_si{tdi}\n", join("", @chars), "\n )";
    }
  }
}

sub cleanup {
  local $_ = shift;
  s/.*=//s;
  tr/01X//cd;
  return [ split // ]
}

