#!/usr/bin/perl -w

use strict;
use lib ".";
use Sch;
use Common;
use Data::Dumper;

sub rm_net($$);
sub rm_net($$) {
    my $lvl = shift;
    my $data = shift;

    #print "\n\n";
    for (my $ix = 0; $ix < @$data; $ix++) {
	my $fld = $$data[$ix]{fld};
	if ($lvl == 1 && $$fld[0] eq 'T') {
	    if (@{$$data[$ix]{text}} == 1) {
		my $str = $$data[$ix]{text}[0];
		if ($str =~ m/^net=/) {
		    $$data[$ix] = undef;
		}
	    }
	} elsif ($lvl == 0 && $$fld[0] eq 'C' && $$fld[6] =~ m/^netif_/) {
	    rm_net($lvl+1, $$data[$ix]{att});
	}
    }

}

sub main() {
    for my $file (@ARGV) {
	if ($file !~ m/\.sch/) {
	    warn("only run this program on .sch files");
	    next;
	}
	print "\n$file:\n";
	my @line = Common::read_file($file);
	my $data = Sch::sch_parse(@line);

	rm_net(0, $data);

	my $str = Sch::data2str($data);
	Common::write_file("${file}.out", $str);

	my $diff = `diff -b -B ${file}.out $file`;
	if ($diff) {
	    print $diff;
	    print "ok to replace: ";
	    if (<STDIN> =~ m/y/i) {
		`mv ${file}.out $file`;
	    }
	}
    }
}

main();
