#!/usr/bin/perl
# ways to invoke:
#  1. Get a search list from farnell and feed HTML source to
#     this script with no args.  Will produce part number list.
#  2. Feed one or more outputs from farnell-find <item> to
#     this script with args  <mfprefix> <valueprefix>...
#     where <mfprefix> is the re for the first part of the mfr
#     code and <valueprefix> is the words of the part name prefix.
if (@ARGV>=2) {
    ($kind,@prefix)= @ARGV;
    sub insdot ($) {
	my ($x)= @_;
	$x =~ s/[mkr]/./;
	return $x;
    }	
    while (<STDIN>) {
	if (m/^Avail\s/) {
	    undef $value;
	} elsif (m/^Description\s+\[$kind (\d[0-9MKR]+)\]\s+RESISTOR/) {
	    $value= lc $1;
	} elsif (m/^Description\s+(\S.*)/) {
	    print "#  $1\n";
	    $value= '';
	} elsif (m/^Item\s+([-0-9]+)$/) {
	    die unless defined $value;
	    next unless length $value;
	    $item= $1;
	    die if exists $v2i{$value} and $v2i{$value} ne $1;
	    $v2i{$value}= $item;
	    undef $value;
	}
    }
    foreach $v (sort {
	foreach $mkr (qw(m k r)) {
	    $z= ($a =~ m/$mkr/) <=> ($b =~ m/$mkr/);
	    return $z if $z;
	}
	return insdot($a) <=> insdot($b);
    }
		keys %v2i) {
	printf "%s =\t%s\n", join(' ',@prefix,$v), $v2i{$v};
    }    
} elsif (!@ARGV) {
    while (<STDIN>) {
	if (m/viewproductdetails.*\?prodId\=(\d{3})(\d{3,7})\"/) {
	    print "$1-$2\n" or die $!;
	}
    }
} else {
    die;
}
