#!/usr/bin/perl -w

use strict;

my @header = ();
my %pin;
while (<>) {
    tr/ \t\r\n/ /s;
    s/^ //;
    s/ $//;

    next if (m/^$/);

    if (m/^\S+$/) {
	push @header, $_;
	next;
    }

    my $str = undef;
    my $num = undef;
    if (m/(\((.*)\) )?(\S+) ([A-Z]?\d+)$/) {
	$str = $3;
	$num = $4;
	if (defined($2)) {
	    my @alt = split(/\//, $2);
	    my $alt = join(" ", sort @alt);
	    $str .= " " . $alt;
	    #print "$4 $3 $alt\n";
	} else {
	    #print "$4 $3\n";
	}
    } elsif (m/([A-Z]?\d+) (\S+)( \((.*)\))?$/) {
	$str = $2;
	$num = $1;
	if (defined($4)) {
	    my @alt = split(/\//, $4);
	    my $alt = join(" ", sort @alt);
	    $str .= " " . $alt;
	    #print "$1 $2 $alt\n";
	} else {
	    #print "$1 $2\n";
	}
    } else {
	#print "$_\n";
	next;
    }

    if (!defined($pin{$str})) {
	$pin{$str} = [];
    }

    my $r = $pin{$str}[$#header];
    if (!defined($r)) {
	$r = $pin{$str}[$#header] = [];
    }
    push @$r, $num;
}

sub ksval($) {
    my $k = shift;
    my $v = $pin{$k};
    sprintf "%4s", $$v[0][0];
}
sub ks {
    ksval($a) cmp ksval($b);
}

sub numval($) {
    my $v = shift;
    sprintf "%4s", $v;
}
sub ns {
    numval($a) cmp numval($b);
}

# sort pin numbers
for my $key (keys(%pin)) {
    my $ref = $pin{$key};
    for my $rr (@$ref) {
	if (!defined($rr)) { $rr = [ "-" ]; }
	my @arr = sort ns @$rr;
	$rr = [ @arr ];
    }
}

my @line;
for my $key (sort ks keys(%pin)) {
    my $ref = $pin{$key};

    # find max size of arrs
    my $sz = 0;
    for my $rr (@$ref) {
	my @arr = @$rr;
	my $dim = @arr;
	if ($dim > $sz) { $sz = $dim; }
    }


    for (my $ix = 0; $ix < $sz; $ix++) {
	my $str = "";
	for my $rr (@$ref) {
	    my $val = $$rr[$ix];
	    if (!defined($val)) { $val = "-"; }
	    $str .= sprintf "%4s", $val;
	}
	my $type = "io ";
	if ($key =~ m/VCC|VDD|VREF|GND|VSS/) {
	    $type = "pwr";
	} elsif ($key =~ m/ADC|DAC/) {
	    $type = "pas";
	}
	$str .= "  $type $key\n";
	push @line, $str;
    }
}

print join(" ", @header), "\n";
print sort @line;
