#!/usr/bin/perl -w

use strict;
use lib ".";
use Geda;
use Sch;
use Pcb;
use Opt;
use Data::Dumper;

if (@ARGV < 1) { Opt::Usage("find refdes and source attributes in .sch files"); }

my ($db_sym, $db_sch, $db_fp, $db_pcb) = Geda::get_files();

my %sym_found;
my %src_found;
my %pcb_found;

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

    my @line = Common::read_file($file);
    my $data = Sch::sch_parse(@line);
    my %Hash = Sch::data2Hash($data);
    #my %Attr = Sch::get_glb_attr($data, \%Hash);
    my @ref_sym = @{$Hash{C}};

    for my $ix (@ref_sym) {
	my $fld = $$data[$ix]{fld};
	my ($type, $x, $y, $selectable, $angle, $mirror, $basename) = @$fld;
	my $ratt = $$data[$ix]{rev_att};
	my $refdes = $$ratt{refdes} // "";
	my $src = $$ratt{source} // "";

	$sym_found{$basename}++;
	next unless $src;
	my $pcb = $src;
	$pcb =~ s/\.sch/.pcb/;
	$src_found{$src}++;
	if (!defined($pcb_found{$pcb})) { $pcb_found{$pcb} = []; }
	push @{$pcb_found{$pcb}}, "$rd$refdes";
	my $src_file = Common::filedb_BNtoFull($db_sch, $src);
	run($src_file, $refdes);
    }
}

for my $file (@ARGV) {
    if ($file !~ m/\.sch/) {
	warn("only run this program on .sch files");
	next;
    }

    run($file, "");
}

for my $k (sort keys %sym_found) {
    my $file = Common::filedb_BNtoFull($db_sym, $k);
    print "$file\n";
}
print "\n";
for my $k (sort keys %src_found) {
    my $file = Common::filedb_BNtoFull($db_sch, $k);
    print "$file\n";
}
print "\n";
for my $k (sort keys %pcb_found) {
    my @val = @{$pcb_found{$k}};
    my $file = Common::filedb_BNtoFull($db_pcb, $k);
    if ($file) { print "$file  "; }
    else { print "$k missing  "; }
    print  "<", join("/", @val), ">\n";
}
