#!/usr/bin/perl -w
# 

use strict;

use Getopt::Long;

my ($input, $output, @definitions);

if (!GetOptions( 
		'i=s' => \$input,
		'o=s' => \$output,
		'd=s' => \@definitions)) {
	exit(1);
}

print "$input -> $output\n";


foreach my $definition (@definitions) {
	my @parts = split(/\s*;\s*/, "$definition");

	$definition = { 'NAME' => $parts[0] || '',
			'SOURCE' => $parts[1] || '',
			'TARGET' => $parts[2] || '',
			'VARIANTE' => $parts[3] || '',
			};
}

sub replacement($$$$) {
	my $startIdx = shift;
	my $endIdx = shift;
	my $text = shift;
	my $separator = shift;
	my $res = '';
	for(my $idx="$startIdx"; $idx<=$endIdx; $idx++) {
		if ($idx>$startIdx) {
			$res .= $separator;
		}
		my $rtext = "$text";
		$rtext =~ s/xxxSOURCExxx/$definitions[$idx]{'SOURCE'}/sg;
		$rtext =~ s/xxxTARGETxxx/$definitions[$idx]{'TARGET'}/sg;
		$rtext =~ s/xxxVARIANTExxx/$definitions[$idx]{'VARIANTE'}/sg;
		$rtext =~ s/xxx2xxx/$definitions[$idx]{'NAME'}/sg;
		$res .= "$rtext";
	}
	return $res;
}

local *INFILE;
#local *OUTFILE;

open(*INFILE, "< $input") or die("$input: $!\n");
open(*OUTFILE, "> $output") or die("$output: $!\n");

my @content = <INFILE>;
my $content = join('',@content);
@content = undef;

# Replace the LOOP
my @blocks = ();

my $str = "\#!/usr/bin/perl -w\n\# This file was automatically generated. Do not edit.";
$content =~ s/^[^\n\r]*/$str/s;

$content =~ s/\#\#\#LOOP\s+WITH\s+(.*?)\s+FROM\s+([0-9]+)\#\#\#(.*?)\#\#\#END\s+LOOP\#\#\#/replacement("$2","$#definitions","$3","$1");/esg;

$content =~ s/\#\#\#LOOP\s+FROM\s+([0-9]+)\#\#\#(.*?)\#\#\#END\s+LOOP\#\#\#/replacement("$1","$#definitions","$2","");/esg;

$content = replacement(0,0,"$content",'');

print OUTFILE "$content";

close(*OUTFILE);
close(*INFILE);

exit(0);
