#!/usr/bin/perl -w

use strict;

my %type =
    qw{
	  I/O io
	  I in
	  O out
	  S pwr
  };

##########

my @pkg;
my @fld;
my $line; # for debug

##########

sub prt( $ $ ) {
    #my $a = shift;
    my $b = shift;
    my $c = shift;
    my $pin = '';

    my $k;
    my %d;

    if ($c =~ m/VREF-/) {
    } else {
	$c =~ s/-/ /g;
    }
    $c =~ tr| /| |s;
    $c =~ s/TAMPER-? */TAMPER_/g;

    for $k (split(/ /, $c)) {
	if (!$pin && $k =~ m/^P.\d+$/) {
	    $pin = $k;
	} elsif ($pin eq $k) {
	    # skip
	} else {
	    $d{$k} = 1;
	}
    }
    my @lst = sort(keys(%d));
    $c = join(" ", @lst);
    my $rest = '';
    if ($pin) {
	if (@lst > 0) {
	    $rest = "$pin $c";
	} else {
	    $rest = "$pin";
	}
    } else {
	if (@lst != 1) {
	    print "Warn 1 <$line>: ", join(" ", @lst), "\n";
	}
	$rest = "$c";
    }

    for (my $ix = 0; $ix < @fld; $ix++) {
	$fld[$ix] = sprintf "%3s", $fld[$ix]; # to make them easy to sort num./alpha
    }

    my $pins;
    $pins = join(" ", @fld);
    if ($rest =~ m/ADC|OSC/) {
	$b = "pas";
    }
    printf FH "%s %-3s %s\n", $pins, $b, $rest;
}

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

    my $pre;
    my $func;
    my $rest;
    my $cnt = 0;
    my $cnt_dir = +1;
    my $pfx;

    open(FI, $file) || return;

    {
	my $ix = rindex($file, ".");
	if ($ix < 1) { return; }
	$pfx = substr($file, 0, $ix);
    }

    open(FH, ">$pfx.pins");

    $_ = <>;
    chomp;
    @pkg = split;
    print FH "$_\n";

    while (<>) {
	chomp;
	$line = $_;
	s/\(\d{1,2}\)//g;	# remove footnote references
	s|//.*||;		# remove my comments
	tr/\t\r\n/ /;
	s/ $//;
	next if (m/^$/);

	if (m/^  /) {	      # assume the is a multiline cell present
	    tr/ / /s;
	    s/^ //;
	    if ($cnt == 0) {
		$cnt_dir = +1;
		@fld = ();
		$pre = '';
		$func = '';
		$rest = '';
	    }
	    $cnt += $cnt_dir;
	    $pre = "$pre $_";
	    if ($cnt == 0) {
		prt($func, "$rest $pre");
		@fld = ();
		$pre = '';
		$func = '';
		$rest = '';
	    }
	} else {
	    $cnt_dir = -1;
	    tr/ \t\r\n/ /s;
	    s/^ //;
	    @fld = split(/ /, $_, @pkg + 1);

	    my $tt = $fld[$#fld];
	    $#fld--;
	    if ($tt =~ m/^(.* |)(I\/O|I|O|S)( (FT)?(.*))?$/) {
		if (defined($type{$2})) {
		    $func = $type{$2};
		} else {
		    $func = "pas";
		}
		#if (defined($4)) { $func .= "*"; }
		#else             { $func .= " "; }
		if (defined($5)) {
		    $rest = "$1 $5";
		} else {
		    $rest = $1;
		}
	    } elsif ($tt eq "Not connected") {
		$func = "pas";
		$rest = "N.C.";
	    } else {
		print "Warn: $_\n";
	    }
	    if (!$pre) {
		prt($func, $rest);
		@fld = ();
		$pre = '';
		$func = '';
		$rest = '';
	    }
	}
    }
    close(FH);
    close(FI);
}

##########

for my $file (@ARGV) {
    run($file);
}

__END__
