#!/usr/bin/perl -w
use strict;
use CGI qw/:standard /;

my $source = param('source') || "";

if($source ne "") {
    my @raw = split /\n/, $source;
    my @lines = &lex(@raw);

# symbol table
    my %sym_table;

#first run to find data
    my $pos = "[##THETA NOT SET##]";
    foreach my $line (@lines){
	if($line =~ /GK/){
	    $pos = -1;
	}
	if($line =~ /\[\=(.*)\]/) {
	    $sym_table{$1} = $pos;
	}
	if($pos >= -1){ $pos++ }
    }

# now go back and make the switches
    print header, "<html><head><title>EDSAC code</title></head><body><pre>\n";
    $pos = "[##theta not set##]";
    foreach my $line (@lines) {
	if($line =~ /GK/){
	    $pos = -1;
	}

	$line =~ s/\s*\[\$here\$\] */$pos/g;
	$line =~ s/\s*\[\$(.*)\] */$sym_table{$1}/g;
	$line =~ s/\s*\[\=(.*)\] *//g;
	print $line;
	if($pos >= -1){ $pos++ }
    }
    print "</pre></html>";
} else {
    print header;
    print<<END_HTML;
<html><head><title>EDSAC assembler</title>
</head>
  <body>
  <form action="edsac.pl" method="POST">
<textarea name="source" cols="60" rows="25" wrap="virtual"></textarea>
<br />
    <input type="submit" value="assemble program" />
  </form>
  </body>
</html>
END_HTML
}

# simple lexer. removes comments and blank lines
sub lex {
    my @raw_code = @_;
    my @results = ();
    foreach my $line (@raw_code){
	$line =~ s/\[\#.*\]//g;
	if($line =~ /\S/){
	    # if there's anything that isn't whitespace
	    # we add it 
	    push @results, $line;
	}
    }
    return @results;
}





