#!/usr/bin/perl

$cc = "g++";
$libtool = "../libtool";
$vhdl_source_name = "";
$source = "";
$includes = "-I ..";
$cpplibs = "../kernel/libfreehdl-kernel.la ../std/libfreehdl-std.la";
$vhdl_library = "testlib"; # Library the design entity is compiled into
$cpp_options = "-static ";
$no_cpp_compile = 0;
$verbose = false;
$vhdl_libdir = "..";

# The main program
sub main {

  my $arg_index = 0;
  while ($arg_index < scalar(@ARGV)) {
    $argument = $ARGV[$arg_index];
    if ($argument =~ /^\-l/) {
      die "gvhdl: Missing argument for '-l'!\n" if (++$arg_index >= scalar(@ARGV));
      $vhdl_library = $ARGV[$arg_index];
    } elsif ($argument =~ /^\-c/) {
      $no_cpp_compile = 1;
    } elsif ($argument =~ /^\-C/) {
      $cc = $ARGV[++$arg_index];
    } elsif ($argument =~ /^\-/) {
      $cpp_options = $cpp_options . " " . $argument;
    } elsif ($argument =~ /^\-v/) {
      $verbose = true;
    } else {
      $vhdl_source_name = $argument;
    }
    ++$arg_index;
  }

  ##############################################################
  # Comiling vhdl -> cc
  ##############################################################
  $_ = $vhdl_source_name;
  s/\.[^\.]*$/\.cc/i;
  my $out_file_name = $_;
  
  $cmd = "./freehdl-v2cc -L $vhdl_libdir $vhdl_source_name > $out_file_name";
  print "gvhdl: executing '$cmd'\n";
  system ($cmd)/256 == 0 || die "gvhdl: Compilation failed!\n";

  ##############################################################
  # Comiling cc -> o
  ##############################################################
  s/\.[^\.]*/\.o/i;
  my $object_file_name = $_;
  s/\.[^\.]*//i;
  my $target_name = $_;

  if ($no_cpp_compile == 0) {
    my $cmd = "$cc $cpp_options $includes -c $out_file_name";
    print "gvhdl:\n";
    print "gvhdl: ================================\n";
    print "gvhdl: Compiling '$out_file_name'...\n";
    print "gvhdl: ================================\n";
    print "gvhdl: $cmd\n";
    system ($cmd)/256 == 0 || die "gvhdl: Compilation failed!\n";
    $cmd = "$libtool $cc $cpp_options $object_file_name $cpplibs -o $target_name";
    print "gvhdl: Linking simulator '$target_name'...\n";
    print "gvhdl: $cmd\n";
    system ($cmd)/256 == 0 ||
      die "gvhdl: Linking failed!\n";
  }
  print "gvhdl: ================================\n";
  print "gvhdl: Simulator '$target_name' created.\n";
  print "gvhdl: ================================\n";
}


&main;
