print STDERR "DRC Expander - expands the DRC rules in MAGIC tech files\n";

my $tech=$ARGV[0] || "/usr/local/lib/magic/sys/sky130A.tech";

my %contacts=();
my %alias=();

#magic:  tech layers allli
open IN,"<$tech";
while(<IN>)
{
  tr/\\//;
  if(m/^\s*(spacing)\s+(\S+)\s+(\S+)\s+/)
  {
    $alias{$2}=1;
    $alias{$3}=1;
    foreach(split(",",$2))
    {
      $alias{$_}=1;
    }
    foreach(split(",",$3))
    {
      $alias{$_}=1;
    }
  }
}
close IN;


    open OUT,"|magic -dnull -noconsole -T $tech >magic.layers.out";
    print OUT "puts \"CUT HERE -------- CUT HERE\"\n";
    foreach(sort keys %alias)
    {
      print OUT "puts \"EXPANDING: $_\"\n";
      print OUT "puts [tech layers $_]\n";
    }
    print OUT "puts \"CUT HERE -------- CUT HERE\"\n";
    print OUT "quit -noprompt\n";
    close OUT;

open IN,"<magic.layers.out";
while(<IN>)
{
  if(m/^EXPANDING: (\S+)/)
  {
     my $next=<IN>;
     chomp $next;
     $alias{$1}=$next;
  }
}
close IN;

foreach(keys %alias)
{
	#  print "$_ -> $alias{$_}\n";
}

open IN,"<$tech";

sub allLayers($)
{
	#if($_[0] !~ m/\//) # If we do not look for "images" (which are signalled by / in the typelist and are currently not supported by magic), then we can just use the whole typelist which is more efficient.
	#{
	#return split " ",$alias{$_[0]} ;
        #}

  my @a=split ",",$_[0];
  my %b=();
  foreach(@a)
  {
    print STDERR "piece: $_\n";	  
    if(m/(\/\S+)/ && defined($alias{$_}))
    {    
      my $image=$1;
      foreach my $part(split " ",$alias{$_})
      {
        $b{$part.(($part =~ m/\//)?"":$image)}=1;
      }
    }
    else
    {
      foreach my $part(split " ",$alias{$_})
      {
        $b{$part}=1;
      }
    }
  }
  return sort keys %b;
}

my $section="";

while(<IN>)
{
  while($_=~m/\\$/)
  {
    $_.=<IN>;
  }
  if(m/^(\w+)/)
  {
    $section=$1;
  }
  #  if($section eq "contact" && m/^\s+(\w+)/)
  #{
  #  my $a=$_;
  #  $a=~s/^\s+//; $a=~s/\s+$//;
  #  my @a=split(/\s+/,$a);
  #  my $cont=shift(@a);
  #  foreach my $cnt(@a)
  #  {
  #    print STDERR "CONTACT: $cont -> $cnt\n";
  #    $contacts{$cont}{$cnt}=1;
  #    $contacts{$cnt}{$cont}=1;
  #  }
  #}
  #if($section eq "aliases" && m/^\s+(\w+)/)
  #{
  #  my $a=$_;
  #  $a=~s/^\s+//; $a=~s/\s+$//;
  #  my @a=split(/\s+/,$a);
  #  my $cont=shift(@a);
  #  foreach my $cnt(@a)
  #  {
  #    print STDERR "ALIAS: $cont -> $cnt\n";
  #    $alias{$cont}=$cnt;
  #  }
  #}
  my $oneline=$_;	  
  $oneline=~s/\n//sg;
  tr/\\//;
  if(m/^\s*(spacing)\s+(\S+)\s+(\S+)\s+(\d+)\s+\\?\s*(\w+)\s+\\?\s*"([^"]+)"/)
  {
    print " # ORIGINAL RULE:$oneline\n";
    my $vl1=$2;
    my $vl2=$3;
    my $text=$6;
    foreach my $layer1(allLayers($vl1))
    {
      foreach my $layer2(allLayers($vl2))
      {
        print "  $1 $layer1 $layer2 $4 $5 \"$6 [erase $layer1]".(($layer1 eq $layer2)?"":"[erase $layer2]")."\"\n"; 
      }
    }
    print "\n";
  }
  else
  {
    print $_;
  }
}
close IN;
