#!/usr/bin/perl -w

use strict;
#use Data::Dumper;

my %typemap = (
    in      => "in",
    out     => "out",
    inout   => "io",
    linkage => "pwr",
);
my %pin;

my $in_port = 0;
my $in_map = 0;
my $package = "";

while (<>) {
    chomp;
    tr/ \t\r\n/ /s;
    s/^ //;
    s/ $//;


    if ($in_port == 0 && m/^port \($/) {
	$in_port = 1;
	#print "Port start\n";
    } elsif ($in_port == 1 && m/^\);$/) {
	$in_port = 0;
	#print "Port end\n";
    } elsif ($in_port == 1 && m/^([A-Z_]+\d*) : (in|inout|out|linkage) (bit|bit_vector\((\d+) to (\d+)\));?$/) {
	if (defined($4) && defined($5)) {
	    for (my $ix = $4; $ix <= $5; $ix++) {
		my $name = $1 . $ix;
		my $type = $typemap{$2};
		#print "<$name:$type>\n";
		$pin{$name}{type} = $type;
	    }
	} else {
	    my $name = $1;
	    my $type = $typemap{$2};
	    #print "<$name:$type>\n";
	    $pin{$1}{type} = $type;
	}
    } elsif ($in_port == 0 && m/^constant (.*)_PACKAGE: PIN_MAP_STRING :=$/) {
	$in_map = 1;
	$package = $1;
	#print "Package start\n";
    } elsif ($in_map == 1) {
	my $name;
	my $lst = "";
	my $num;
	if (m/^\"([A-Z_]+\d*) : ([A-Z0-9_]+),\" (.)$/) {
	    $name = $1;
	    $num = $2;
	    $lst = $3;
	    #print "S<$name:$num>\n";
	    $pin{$name}{num} = $num;
	} elsif (m/^\"([A-Z_]+\d*) : \(([A-Z0-9, ]+)\),?\" (.)$/) {
	    #print "o<$_>\n";
	    $name = $1;
	    $num = $2;
	    $lst = $3;
	    #print "<$name|$num|$lst>\n";
	    my @fld = split(/ ?, ?/, $num);
	    for (my $ix = 0; $ix < @fld; $ix++) {
		my $tt = $ix+1;
		my $str = $name . $tt;
		#print "M<$str|$fld[$ix]|$lst>\n";
		$pin{$str}{num} = $fld[$ix];
	    }
	}
	if ($lst eq ";") {
	    $in_map = 0;
	    #print "Package end\n";
	    last;
	}
    } else {
    }
}

my @line;
for my $name (sort keys %pin) {
    my $type = $pin{$name}{type};
    my $num  = $pin{$name}{num};

    if (!defined($type)) { $type = "pas"; }
    if (!defined($num)) { $num = 0; }

    if ($num =~ m/[A-Z]/) {
	push @line, sprintf("%-4s  %-3s  %s\n", $num, $type, $name);
    } else {
	push @line, sprintf("%4s  %-3s  %s\n", $num, $type, $name);
    }

}
print "$package\n";
print sort @line;

__END__

     constant LQFP100_PACKAGE: PIN_MAP_STRING :=
          "BOOT0               : 94," &
          "JTDI         : 77," &

          "VDD          : (50, 75, 100, 28, 11)," &
          "VSS          : (49, 74, 99, 27, 10)" ;
