#!/perl
# very SIMPLE text to perl

use strict;
my $WHITE_PATTERN2 = "^[ \t\n\r]*\$"; # spacey if ($var =~ /$WHITE_PATTERN2/o ) { ...}
my $tab_stg = '&nbsp;&nbsp;&nbsp;'; # replace tabs, with 3 spaces
my $verb2 = 0;
my $logfil = 'templog.txt';

my $infile = shift || '.';
my $outfil = shift || 'tempout.htm';
my ($OF, $IF, $LF);
my $name;
my $msg = '';
my ($line, $txt);
my $i = 0;
my ($cnt1, $cnt2);

if ($infile eq '.') { die "No input file given ...\n"; }

open $LF, ">$logfil" or die "Can NOT open LOG file $logfil!\n";

tolog ("$0 Started " . localtime(time()) . " ...\n");
if (! -f $infile) {
	die "Input file [$infile] NOT FOUND! ...\n";
}

tolog ("Opening $infile ...\n");
open $IF, "<$infile" or die "Can not OPEN $infile!\n";
tolog ("Loading $infile ...\n");
my @lines = <$IF>; # slurp whole file, to an array of lines
close($IF);

open $OF, ">$outfil" or die "Can not create $outfil!\n";

add_html_head( $OF, $infile );
### add_html_tail($OF);

my $lncnt = @lines; # get count
tolog ("Processing $infile ... $lncnt lines\n");
my $lc = 0;
my $dnpara = 1;
my @lnbits;
my $chk;
## my $func;
prt ("<p>\n");
foreach $line (@lines) {
	$txt = $line;
	chomp $txt;
	if ($txt =~ /$WHITE_PATTERN2/o ) {
		$txt = "</p>\n<p>\n"; # CLOSE paragraph, and open
	} else {
		$txt = htmlise($txt);
		$txt .= "<br>\n"; # set new line
	}
	prt ($txt);
	$lc++;
}

tolog ("Processed $lc lines of $infile ... written to $outfil ...\n");
prt ("</p>\n");
add_html_tail($OF);
close($OF);
 system $outfil;
# system $logfil;

sub prt {
	tolog (@_);
	print $OF @_;
}

sub add_html_head {
	my ($fh, $hdr) = @_;
	print $fh <<"EOF";
<html>
<head>
<title>$hdr</title>
</head>
<body>
<h1 align="center">$hdr</h1>
EOF

}

sub add_html_tail {
	my ($fh) = @_;
	print $fh <<"EOF";
</body>
</html>
EOF

}

sub tolog {
	print @_;
	print $LF @_;
}


sub htmlise {
	my ($txt) = @_;
	# convert to HTML
	$txt =~ s/\t/$tab_stg /g; # substitute TAB characters
	$txt =~ s/"/&quot;/g; # sub double quotes
	$txt =~ s/\</&lt;/g; # sub less than tag beginning
	$txt =~ s/\>/&gt;/g; # and html/xml tag ending
	my $ln = length($txt); # get the final length
	if (substr ($txt, 0, 1) eq ' ') { # if starts with a space
		my $sps = 0;
		my $nbs = '&nbsp;';
		for ($sps = 1; $sps < $ln; $sps++) {
			if (substr ($txt, $sps, 1) ne ' ') {
				last;
			}
			$nbs .= '&nbsp;' if $sps > 1;
		}
		$sps-- if $sps > 1; # back off last space, if more than 1
		tolog ("Replacing $sps with [$nbs] ...\n") if $verb2;
		$txt =~ s/ {$sps}/$nbs/; # replace (N) spaces with '&nbsp; x N
		if ($verb2) {
			my (@vals) = split;
			while (@vals) {
				my ($vc) = shift (@vals);
				tolog ("[$vc] ");
			}
			tolog ("\n");
		}
	} # if it was space beginning

	#if ($func) {
	#	$txt = $func->($txt);
	#}
	#$txt .= "<br>\n";
	return $txt;
}
