#!/usr/bin/perl -w

use strict;

my %pfx = (
    "" => 1,
    p => -12,
    n => -9,
    u => -6,
    m => -3,
    k => 3,
    M => 6,
);
my %pfxmap = (
    # just something that makes p < n etc.
    p => "d",
    n => "e",
    u => "f",
    m => "g",
    "" => "h", # no prefix, as in 1; 1m < 1 < 1k
    k => "i",
    M => "j",
);
my %part;

sub sortstr($) {
    my $r = shift;
    my @arr = @$r;

    my $ta = $arr[2];
    my $va = "Z" . $ta;
    if ($ta =~ m/^([0-9.]+)([pnumkM]?)/) {
	my $v = $1;
	my $k = $pfxmap{$2};
	if (!defined($k)) { $k = "h"; }
	$va = sprintf(" %s%7.3f", $k, $v);
    }

    $ta = $arr[3];
    if ($ta =~ m/(.*[a-zA-Z])(\d+)/) {
	$ta = sprintf("%s%02d", $1, $2);
    } else {
	print STDERR "sortstr <$ta>\n";
    }

    my $str = "$arr[0] $arr[1] $va $ta";
    #print "$str\n";
    #exit(0);
    return $str;
}
sub sort_pfx {
    return sortstr($a) cmp sortstr($b);
}

sub run($) {
    my $file = shift;
    print `gnetlist -g partslist1 -o $file.list $file`;
    if (!open(FH, "$file.list")) {
	warn("no file $file.list");
	return;
    }

    my $col = 5;
    my @line;
    my @len = (0) x $col;
    while (<FH>) {
	chomp;
	next if (m/^\.(START|END)$/);
	next if (m/^\./);
	next if (m/^U\?	unknown	unknown	unknown	1$/);
	my @fld = split(/[ \t]+/, $_, $col);
	if (@fld != 5) {
	    warn("not 5 cols <$_>");
	    next;
	}
	pop @fld; # skip quantity which is always 1
	# I want following order: device footprint value refdes
	$fld[1] =~ s/^resistor$/Resistor/;
	@fld = @fld[1,3,2,0];
	for (my $ix = 0; $ix < @fld; $ix++) {
	    my $l = length($fld[$ix]);
	    if ($len[$ix] < $l) {
		$len[$ix] = $l;
	    }
	}
	push @line, [ @fld ];
    }
    close(FH);
    @line = sort sort_pfx @line;

    my $fmt1 = sprintf("%%-%ds %%-%ds %%-%ds", @len[0..2]);
    my $fmt = $fmt1 . " %s\n";
    if (!open(F1, ">$file.list1")) {
	warn("cannot open output file ($file.list1)");
	return;
    }
    if (!open(F2, ">$file.list2")) {
	warn("cannot open output file ($file.list2)");
	return;
    }
    my $str = "";
    my $key = sprintf($fmt1, @{$line[0]}[0,1,2]);
    for my $l (@line) {
	my @arr = @$l;
	my $k = sprintf($fmt1, @arr[0,1,2]);
	if ($k ne $key) {
	    $str =~ s/ $//;
	    my $cnt = split(" ", $str);
	    printf(F2 "%s %2d %s\n", $key, $cnt, $str);
	    $str = "";
	    $key = $k;
	    print F1 "\n"; # Note: F1 here
	}
	$str .= $arr[3] . " ";
	printf(F1 $fmt, @$l);
    }
    if ($str ne "") {
	$str =~ s/ $//;
	my $cnt = split(" ", $str);
	printf(F2 "%s %2d %s\n", $key, $cnt, $str);
    }
    close(F1);
    close(F2);
    `cat $file.list1 | mpage -f1o  > $file.list1.ps`;
    `cat $file.list2 | mpage -f1ol > $file.list2.ps`;
}

sub main() {
    for my $f (@ARGV) {
	run($f);
    }
}

main();
