#!/usr/bin/perl -w

use strict;
use Opt;
use Common;
use Net;
use Data::Dumper;

sub run($$$$) {
    my $refdes = shift;
    my $ignore = shift;
    my $limit = shift;
    my $file = shift;
    my @line = Common::read_file($file);
    my ($pin2net, $net2pin, $pfx) = Net::net_parse(@line);

    #print Dumper($pin2net);
    my @pin = grep { m/$refdes-\d+/ } keys %$pin2net;
    @pin = sort { Net::sort_pin($a, $b) } @pin;

    #print "ignore = <$ignore>\n";
    for my $pin (@pin) {
	my $nr = $$pin2net{$pin};
	for my $net (@$nr) {
	    if ($ignore && $net =~ /$ignore/) {
		# print "ign: <$pin> <$net>\n";
		next;
	    }
	    my $pr  = $$net2pin{$net};
	    my $str = "";
	    my @arr = @$pr;
	    if ($limit && $limit < $#arr) {
		@arr = @arr[0 .. $limit-1];
		$str = " ...";
	    }
	    print "$pin: $net ", join(" ", @arr), "$str\n";
	}
    }
}


sub main() {
    Opt::opt();
    if (@ARGV == 0) {
	print "print nets which refdes occur in\n";
	exit 0;
    }
    my $rd  = $Opt::OPT{refdes};
    my $ig  = $Opt::OPT{ignore} // "";
    my $lim = $Opt::OPT{limit} // 0;

    for my $f (@ARGV) {
	run($rd, $ig, $lim, $f);
    }
}

main();

