#!/usr/bin/perl -w
use strict;
use warnings;
use utf8;
use open qw(:std :utf8);

$| = 1;

# Filter_3_02_replace_replacements.pl
# 2010-04-04
# Wolfgang Schmidle

# what does it do?
# input
# output

require $ENV{'ECHO_SCRIPTS_DIR'} . "/share/common_functions.pl";
consoleStatus('Evaluating replacements file.');
my $filtername = "Filter_3_02_replace_replacements.pl";

my %replacements = ();


# text input

my @text;
while(<>) { push @text, $_; }


# evaluate and remove the "replacements" block

my $inReplacements = 0;

my @context = getInputContext();

#kt foreach (@text) {
#	last if m!<pb[ ^]!;	
foreach (@context) {
	if (m!replacements:!) { 
		$inReplacements = 1; 
		$_ = "";
		next;
	}
	if ($inReplacements) {
		if (m!^ *$!) {
			$_ = "";
			last;
		}
		if (m!/([^/]+)/ *= */([^/]+)/!) {
			$replacements{$1} = $2;
			$_ = "";
			next;
		}
		unless (m!([^ ]+) *= *([^ \n]+)!) { 
			#kt die "$filtername: misformed replacement instruction:\n$_\n";
			consoleWarn('$filtername: misformed replacement instruction:\n$_\n'); 
		}
		$replacements{$1} = $2;
		$_ = "";
	}
}


# go through the text

foreach (@text) {
	foreach my $key (keys %replacements) {
		s!$key!$replacements{$key}!g;
	}
}


# text output

# print @text;
printInOutputTextFile(@text);
consoleStatus('Finished.');

# TO DO:
# <!?> --> <!> soll funktionieren: mache es zu <\!\?> oder zu <\x{0021}\x{003F}>
