#!/usr/bin/perl
#Replicate functionality of Constants from RISC OS build system
#DM

$infile=$ARGV[0];
$outfile=$ARGV[1];
$constfile=$ARGV[2];

#read in consts
open (CONSTS, "<$constfile") || die "Could not open constants file";
%consts = {};
while ($line=<CONSTS>) {
	if ($line =~ /^(\w+),\s*([\w+\-&]+)$/) {
		$key=$1;
		$value=$2;
		#Check if offset from previous
		if ($value =~ /\+(\d+)/) {
			$value=$previousvalue+$1;
		}
		$consts{$key}=$value;
		$previousvalue=$value;
	}
}
close (CONSTS);

#open files for input and output
open (IN, "<$infile") || die "Could not open input file";
open (OUT, ">$outfile") || die "Could not open output file";

#replace constants
while ($line=<IN>) {
	if ($line =~ /CONST_(\w*)%/) {
		if (defined ($consts{$1})) {
			$replace = $consts{$1};
			$line =~ s/CONST_$1%/$replace/;
		}
	}
	print OUT $line;
}
close (IN);
close (OUT);
