#!/usr/bin/perl

##
## Melange License Notice
##
## The contents of this file are subject to the Lesser Gnu Public License
## (the "License"). You may not use this file except in compliance with 
## the License. A copy of the License is available at
## http://opensource.org/licenses/lgpl-license.php
##
## Copyright 2004 Tobi Schaefer. All Rights Reserved.
##
## $RCSfile$
## $Author$
## $Revision$
## $Date$
##

$file = $ARGV[0];
if (!$file) {
   die "Missing file argument from command-line";
}

$ISCLASS = 1;
$ISMETHOD = 2;

$METAPATTERN = "^(?:\\/){2}(?:\\+){2} *(Class|Interface)+ *extends *([^ ]*) *(?:\\+){2}(?:\\/){2}.*";

$PROTOPATTERN = "melange\.([^ ]*) * = function([^{]*\\) *\\{)";
$METHODPATTERN = "   this\.([^ ]*) *= *function(.*)";
$METHODPATTERN2 = "   this\.([^ ]*) *= *new Function(.*);";
$ENDPATTERN = "};";

open(file, $file);

$state = 0;
while ($line = <file>) {
   if ($line =~ m/$METAPATTERN/) {
      $line =~ s/\n//g;
      $type = $proto = $line;
      $type =~ s/$METAPATTERN/$1/;
      $proto =~ s/$METAPATTERN/$2/;
      $line = "";
   } elsif ($line =~ m/$PROTOPATTERN/) {
      $state = $ISCLASS;
      $line =~ s/$PROTOPATTERN/Melange.add$type("melange.$1", $proto, function$2/;
   } elsif ($line =~ m/$METHODPATTERN/) {
      $state = $ISMETHOD;
      $line =~ s/$METHODPATTERN/   Melange.addMethod(this, "$1", function$2/;
   } elsif ($line =~ m/$METHODPATTERN2/) {
      $state = $ISCLASS;
      $line =~ s/$METHODPATTERN2/   Melange.addMethod(this, "$1", new Function$2);/;
   } elsif ($line =~ m/^   $ENDPATTERN/ and $state eq $ISMETHOD) {
      $state = $ISCLASS;
      $line =~ s/^   $ENDPATTERN/   });/;
   } elsif ($line =~ m/^$ENDPATTERN/ and $state eq $ISCLASS) {
      $state = 0;
      $line =~ s/^$ENDPATTERN/});/;
   }
#print $state;
#print $line;
   $code .= $line;
}

close(file);

print $code;
