#!/usr/bin/perl
#
# Extract dependency files from a Quartus .qsf file
#

use strict;

my($infile,$project) = @ARGV;

my %map_deps = ($infile);
my %asm_deps = ();
my %cof_list = ();

my $output_dir = 'output_files';

open(my $in, '<', $infile) or die;
while (defined(my $l = <$in>)) {
    chomp $l;
    next unless ($l =~ /^\s*set_global_assignment\s+\-name\s+(\w+)\s+\"?(.*?)\"?\s*$/);
    my $type = $1;
    my $name = $2;

    if ($type =~ /^project_output_directory$/i) {
	$output_dir = $name;
	next;
    }
    
    next if ($type !~ /_file$/i || $type =~ /^generate_/i);
    
    $name =~ s/^quartus_\w+://;
    $name =~ s/\s-.*$//;

    if ($name =~ /\.cof$/i) {
	$cof_list{$name}++;
    } elsif ($type =~ /^(signaltap_file|use_signaltap_file|sld_file)$/i) {
	# Skip
    } elsif ($type =~ /^(mif|hex)_file$/i) {
	$asm_deps{$name}++;
    } else {
	$map_deps{$name}++;
    }
}

close($in);

sub print_deps($%) {
    my($target,%deps) = @_;

    print "\n", $target, " :";

    foreach my $dep (sort keys(%deps)) {
	print " \\\n\t", $dep;
    }

    print "\n";
}

my $map_target = "$output_dir/$project.map.rpt";
print_deps($map_target, %map_deps);

my $asm_target = "$output_dir/$project.mif_update.rpt";
print_deps($asm_target, %asm_deps);

exit 0;
