#!/usr/bin/perl -w

use strict;

my %attr;

sub data_read( $ ) {
    my $file = shift;

    my $fh;
    open($fh, "$file") || return [];
    my @pins = ();
    my $state = "";

    my $cp = [];
    while(<$fh>) {
	chomp;
	my $line = $_;
	next if (m/^[vTBL] /);
	if (m/^P /) {
	    $state = "p";
	    $cp = ["", "", ""]; # pinnum type lbl, don't care about seq
	    next;
	}
	if (m/^{/) {
	    if ($state eq "p") { $state = "P"; next; }
	    warn("uknown line <$line>");
	    next;
	}
	if (m/^}/) {
	    if ($state eq "P") {
		if (@$cp == 3) {
		    push @pins, $cp;
		}
		$state = "";
		next;
	    }
	    warn("uknown line <$line>");
	    next;
	}
	if (m/^([a-zA-Z0-9]+)=(.*)$/) {
	    my $k = $1;
	    my $v = $2;
	    if ($state eq "") {
		$attr{$k} = $v;
		next;
	    } elsif($state = "P") {
		if ($k eq "pinnumber") { $$cp[0] = $v; next; }
		if ($k eq "pintype"  ) { $$cp[1] = $v; next; }
		if ($k eq "pinlabel" ) { $$cp[2] = $v; next; }
		if ($k eq "pinseq"   ) { next; } # ignore pinseq
		warn("uknown line <$k=$v> <$line>");
		next;
	    }
	    warn("uknown line <$line>");
	}

    }

    close($fh);

    @pins;
}

for my $file (@ARGV) {

    my @pins = data_read($file);
    @pins = sort { $$a[0] <=> $$b[0] } @pins;

    $file =~ m/([^\/]*)\.[^.]*$/;
    my $pfx = $1;
    my $sym = $pfx . ".sym";

    for my $k (keys(%attr)) {
	my $v = $attr{$k};
	print "$k=$v\n"
    }

    for my $p (@pins) {
	my $num = $$p[0];
	my $type = $$p[1];
	my $lbl = $$p[2];

	printf "%3d %3s %s\n", $num, $type, $lbl;
    }
}
