#!/usr/bin/perl -w
#
use strict;
#
# script to take extract from dialcnet.dat from 
# FMC-TLU design (connections to FMC connector)
# and SP601 master UCF
# and produce a section of UCF to include in FMC-TLU firmware.
#
# extract from dialcnet.dat is like:
# SPARE1                   J4               H34      ASP-134606-01 
#
# master UCF contains lines like:
# NET "FMC_LA22_N"                    LOC = "T7";  ## G25 on J1
#
#
# two args. First is master UCF , second is extract from dialcnet.dat
#
# David Cussans, November 2012
#

my $masterUCF = $ARGV[0];
my $netlist = $ARGV[1];

print "ucf , netlist = $masterUCF , $netlist\n";

open UCF , "<$masterUCF" or die "Can't open master UCF: $!";
open NETLIST , "<$netlist" or die "Can't open netlist: $!";

my %fpga_fmc_pins;
my %fmc_nets;
my %fpga_fmc_labels;

while ( <UCF> ) {
    next unless /FMC/;
    # print $_;
    my @fields = split;
    my $fpga_pin = $fields[4];
    my $fmc_pin  = $fields[6];
    $fpga_pin =~ s/[\";]//g;

    my $fmc_label = $fields[1];
    $fpga_fmc_labels{$fmc_pin} = $fmc_label;

    #print $fields[4], $fields[6] , "\n"
    #print $fpga_pin , $fmc_pin , "\n";
    $fpga_fmc_pins{$fmc_pin} = $fpga_pin;

}
#while (<>){
#print %fpga_fmc_pins;

while (<NETLIST>) {
    my @fields = split;
    my $netname = $fields[0];
    my $fmc_pin = $fields[2];

    my $inverted_signal;
    if ($netname =~ s/\*//) { $inverted_signal = 1 } else { $inverted_signal = 0}
    if ( $netname = /^(\D+)(\d+)/) {
	$netname =~ s/[<>]//g;
	my $netbase = $1;
	my $netindex = $2;
	## print "$netbase , $netindex\n";
	# we have an name like NET000
	if ($inverted_signal) { $netbase = $netbase . "_N"} else {$netbase = $netbase . "_P"}
	## print "$netbase , $netindex\n";
	$netname = $netbase . "<" . $netindex . ">";
	## print "netname = $netname\n";
    }
    #if ($netname =~ s/\*//) { $netname = $netname . "_N" } else { $netname = $netname . "_P" } ;  
    ## print "netname , fmcpin = $netname $fmc_pin\n";
    $fmc_nets{$fmc_pin} = $netname;
}

my $fmc_pin;

foreach $fmc_pin ( sort keys %fmc_nets ) {

#    print "$fmc_pin , $fmc_nets{$fmc_pin} , $fpga_fmc_pins{$fmc_pin} \n";
    print "NET \"$fmc_nets{$fmc_pin}\"\t\tLOC = \"$fpga_fmc_pins{$fmc_pin}\"; ## $fpga_fmc_labels{$fmc_pin} , $fmc_pin on FMC\n";
}
