: # -*- perl -*-
eval 'exec perl -w -S $0 ${1+"$@"}'
  if 0;

use strict;
use Synopsys;

my $i=0;
my $shell_name = 'pt_shell';
my $outfile    = 'Magic.spicepaths';

$| = 1;

$Synopsys::Verbose = 3;

print "Initializing $shell_name...";
my $shell = Synopsys->new($shell_name)
              or die "Init of $shell_name failed, exiting.\n";
print "Done.\n";

$shell->install_error_handler(\&my_error_handler);

$shell->variable('search_path', 
  '.', '$synopsys_root/libraries/syn', '/cad/lsi/lsitk_3.1/lib/synopsys/lcb500k');

$shell->variable('link_library', '*', 'lcb500kiov.db', 'sgi500kv.db', 'lcb500kv_magic_mems.db');

print "Reading in MagicPMonBCT database...\n";
$shell->read_verilog('MagicPMonBCT.v');
print "Done.\n";

$shell->current_design('Magic');

print "Getting pin object 'Pads/PadsClock/Phi1Drive/A'\n";
my $pin = $shell->get_pins('Pads/PadsClock/Phi1Drive/A');

open OUT, "> $outfile" or die "Error opening '$outfile': $!\n";
print "Opened '$outfile' for writing.\n";

$pin->get_transitive_fanout( 
        '-callback' => \&callback,
        '-stop'     => [ '^DEL', '^MUX21H' ],
        '-skip'     => [ '^BAL' ],
      );

close OUT;

$shell->exit;

sub callback {
  my @path = @_;

  return if $path[$#path]->{'pin_out'} =~ /Z$/;
  return if $path[$#path]->{'pin_in'} =~ /D$/;

  $i++;
  print OUT "spice_path path$i ";
  foreach my $node (@path) {
    print OUT "/$node->{'pin_in'} ";
    print OUT "/$node->{'pin_out'} " if $node->{'pin_out'} ne '';
  }
  print OUT ";\n\n";
}

sub my_error_handler {
  my ($shell, $error_type) = @_;

  if( $error_type == 1 ) {
    if( $shell->verbose < 3 ) {
      $shell->printer(1, "Error with the command '", 
                         $shell->current_command, "'\n\n",
                         $shell->output_string);
    }
    $shell->printer(1, "Exiting...\n");
    exit;
  } elsif( $error_type == -1 ) {
    $shell->printer(0, "Fatal error, exiting.\n");
    exit;
  }
}
