# perl_xZkqqHx_iCmFiCfBiDgPiDeDiDgHiDfCiBfLiDgIiCpAjCmKiClHiCmGiJlLiCkPiCoJiPoKiNiHiCkKiCkAiCoIiCnMiClHiBeCiKpJjCgN_xHqqkZx_:_xZkqqHx_iBhFiDfMiBhG_xHqqkZx_
# _xZkqqHx_iCfBiDgPiDeDiDgHiDfCiBfLiDgIiCmNiDfCiDiBiDjDiDgHiImKjChFiCmJiMmAiCoJiClBiCmGiBeC_xHqqkZx_

$0 =~ /(.*)\.(.*)/;
$former = $1;
$latter = $2;
if ($latter =~ /^pl_(.+)$/) {
	$fdout = "$former".".$1";
} else {
	die "Bad suffix : .$latter\n";
}

open(FDIN, ${template}) || die "Cannot open ${template}\n";
open(FDOUT, ">${fdout}") || die "Cannot open ${fdout}\n";

print FDOUT << "EndOfMsg";
// _xZkqqHx_iClBiCmMiDhEiDeAiDeDiDiLiCmNiBeB_xHqqkZx_${template}_xZkqqHx_iBeB_xHqqkZx_$0_xZkqqHx_iBeB_xHqqkZx_generate.pl_xZkqqHx_iCmM_xHqqkZx_
// _xZkqqHx_iCfCiDhEiDeAiDeDiDiLiCkJiCoHiOkJjDkOjAlGjAkMiClDiCoKiClNiCoAiCmMiCmFiClHiBeCiPeDjAlDiCmNiBeBiClBiCmMiDhEiDeAiDeDiDiLiCmFiCmNiCmIiCkN_xHqqkZx_
// _xZkqqHx_iMlDiCmMiCfCiDhEiDeAiDeDiDiLiCmJiNhDiCmBiCmEiCkNiClOiClDiCkCiBeC_xHqqkZx_
EndOfMsg

while (<FDIN>)
{
	if (/#!begin!#/) {
		$block = "ON";
	} elsif (/#!end!#/) {
		while ($prg =~ /#<([^>]+)>#/)
		{
			$kk = eval $1;
			$prg =~ s/#<[^>]+>#/$kk/;
		}
		$_ = "";
		eval($prg);
		$block = "";
		$prg = "";
		$_ = &taber($_);
		print FDOUT;
	} elsif ($block) {
		$prg .= $_;
	} elsif (! $block) {
		while (/#<([^>]+)>#/)
		{
			$kk = eval $1;
			s/#<[^>]+>#/$kk/;
		}
		print FDOUT;
	}
}

close FDOUT;
close FDIN;

print "Succeed to create ${fdout}\n";

sub taber {
	local($l_orig) = @_;
	local($l_len, $l_tab, $l_spc, $l_mode, $l_i, $l_fromtab, $l_fromspc, $l_count, $l_nowc, $l_ret);
	$l_len = length($l_orig);
	$l_tab = 0;
	$l_spc = 0;
	$l_mode = "C";	#Char mode.
	for ($l_count = 0; $l_count < $l_len; $l_count++)
	{
		$l_nowc = substr($l_orig, $l_count, 1);
		if ($l_mode ne "S")	# Char mode.
		{
			if ($l_nowc eq " ")
			{
				$l_mode = "S";	# Space mode.
				$l_fromtab = $l_tab;
				$l_fromspc = $l_spc;
			}
		} elsif ($l_mode eq "S")	# Space mode.
		{
			if ($l_nowc ne " ")
			{
				$l_mode = "C";	# Char mode.
				$l_ret .= "\t" x ($l_tab - $l_fromtab);
				if ($l_tab == $l_fromtab)
				{
					$l_ret .= " " x ($l_spc - $l_fromspc);
				} else {
					$l_ret .= " " x $l_spc;
				}
			}
		}

		if ($l_nowc eq " ")
		{
			$l_spc++;
			if (4 <= $l_spc)
			{
				$l_tab += int($l_spc / 4);
				$l_spc = 0;
			}
		} elsif ($l_nowc eq "\t")
		{
			$l_tab++;
			$l_spc = 0;
			$l_ret .= $l_nowc;
		} elsif ($l_nowc eq "\n")
		{
			$l_tab = 0;
			$l_spc = 0;
			$l_ret .= $l_nowc;
		} else
		{
			$l_spc++;
			if (4 <= $l_spc)
			{
				$l_tab += int($l_spc / 4);
				$l_spc = 0;
			}
			$l_ret .= $l_nowc;
		}
	}

	$l_ret;
}
