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

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

open (INFILE, $input) || die "cannot open $input: $!";
open (OUTFILE,"> $output") || die "cannot open $output: $!";

$/=";";

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/; 

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

sub printout {
  my ($scanout, @chain) = @_;
  for my $i (0 .. $#{$chain[1]}){
    my $chars = "";
    for (@chain) { 
      next unless defined;
      $chars .= $_->[$i];
    }
    if ($scanout) {
      $chars =~ tr/01/LH/; 
    } else {
      $chars =~ tr/X/0/;
    }
    print OUTFILE 
      $scanout ? "\n(ct_so\n" : "\n(ct_si  $ct_si{tdi}\n",
        "$chars\n )";
  }
}

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