#!perl -w
# coded using EditPlus v2.12 (76)
# March, 2005 geoff mclane
# Sep 2006 - update
# Orignal output was the whole file as one paragraph, using <br> to divide lines
# Add option to use <pre [class="cd"]>...</pre> formating

use strict;
use Cwd;

my $M_VERSION = "0.2";
my $start_time = time();
my $verbose = 0;
my $verb2 = 0;
my $out_file = "temp.$0.htm";
my @input_files = ();
my $file_lines = 0;
my @files = ();
my @file_list = ();
my $WHITE_PATTERN = "^[ \t]*\$";
my $tab_stg = '&nbsp;&nbsp; ';
my $in_file = '';
my $check_out = 0;
my $use_pre = 1;	# default to ON
my $doc_type = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"'."\n".
'"http://www.w3.org/TR/html4/loose.dtd">'."\n";

print "$0: Started on " . localtime($start_time) . "...\n";
my $dir = getcwd();
print "Running in $dir ...\n";
### just for fun get_dir_list($dir);

parse_arguments(@ARGV);

die "$0: no input files found or specified\n" if ! @input_files;

# pre-process
foreach my $inf (@input_files) {
	if (-f $inf) {
		print "File: $inf ok\n";
	} else {
		die "ERROR: Can not locate file [$inf] ... check command ...\n";
	}
}

$in_file = $input_files[0];	# get the FIRST
init_out_file($out_file, $in_file); # abort, if no create ...

# show count in the array ...
print "Adding $#input_files lines to file $out_file.\n" if $verbose;

foreach $in_file (@input_files) {
 do_this_file($out_file, $in_file);
}

end_out_file($out_file);

print "Done $out_file on " . localtime(time()) . ".\n";

system($out_file);

exit(0);

sub get_dir_list
{
    my $name = shift;
	# put all files in the current directory in @files:
	# opendir(THEDIR, ".") || die("Couldn't open current directory\n");
	opendir(THEDIR, $name) || die("Couldn't open current directory\n");
	@files = readdir(THEDIR);
	closedir(THEDIR);
	my $f_cnt = 0;
	my $d_cnt = 0;
	print "Found " . $#files . " files and folders ...\n";
	foreach my $dfile (@files) {
	 if ( -d $dfile ) {
		 # if ($dfile eq '.' || $dfile eq '..') or
		 if ($dfile =~ '^\.$' || $dfile =~ '^\.\.$') {
			 # do nothing with DOT and DOUBLE DOT
		 } else {
		  $d_cnt++;
		  print "$dfile <DIR>\n" if $verb2;
		 }
	 } else {
	  $f_cnt++;
	  my $ff = $name . '\\' . $dfile;
	  # $ff =~ s/\//\\/g; # set DOS path separators ...
	  $ff =~ s/\\/\//g; # set *nix path separators ...
	  my $sb = dirname($ff);
	  $ff =~ s/\//\\/g; # set DOS path separators ...
	  $sb =~ s/\//\\/g; # set DOS path separators ...
	  print "$dfile dos [$ff] [$sb] " if $verb2;
	  if ($f_cnt == 1) {
		  $sb =~ s/\\/\//g; # set *nix path separators ...
		  print "[$sb]" if $verb2;
	  }
	  print "\n" if $verb2;
	 }
	}

	print "Found " . $#files . " - folders = $d_cnt, files = $f_cnt ...\n";
}


sub parse_arguments {
 my @av = @_; # take it off the passed stack
 while (@av) {
	 my $a = shift @av; # get and move to next
	 if ($a eq '--version') {
		 print "$M_VERSION\n";
	 } elsif ($a eq '--help' || $a eq '--h' || $a eq '-h' || $a eq '-?') {
		 die "No help available! ;=))\nexcept reading the code here!\nTry -v, -o name, in_file etc ...";
	 } elsif ($a eq '--verbose' || $a eq '-v') {
		 print "Setting verbose.\n";
		 $verbose = 1;
	 } elsif ($a eq '-v2') {
		 print "Setting verbose 2.\n";
		 $verbose = 1;
		 $verb2 = 1;
	 } elsif ($a eq '--output' || $a eq '-o') {
		 die "$0: no argument given for option \`$a'\n" if ! @av; # require_argument(@av);
		 my $tmp = shift @av; # take next argument
		 if ($tmp ne $out_file) {
			 $check_out = 1;
			 $out_file = $tmp;
		 }
	 } elsif ((length($a) >= 2) && (substr($a,0,2) eq '-p') ) {
		 if (length($a) > 2) {
			 my $pa = substr($a,2);
			 if ($pa eq '-') {
				 $use_pre = 0; # off the feature
			 } elsif ($pa eq '+') {
				 $use_pre = 1; # ON the feature
			 } else {
				 die "$0: Errant -p command. Only -p+ for ON, and -p- for OFF allowed...\n";
			 }
		 } else {
			# just -p toggles the feature
			if ($use_pre) {
				$use_pre = 0;
			} else {
				$use_pre = 1;
			}
		 }
	 } elsif ($a =~ /^-/) {
		 die "$0: unrecognised option -- '$a'\nTry $0 --help for more information.\n";
	 } else {
		 print "Storing argument [$a].\n";
		 push(@input_files, $a);
	 }
 } # while arguments

 if (! @input_files) {
	 push(@input_files, 'F:\Gtools\tidyproj\diffs\tidycvs6.txt');
 }
}

sub init_out_file {
    my ($out_name, $in_name) = @_;
    print "Creating $out_name\n";
    open(DSP, ">$out_name") || die "Can not create $out_name: $!\n";
    print "Writing to $out_name ...\n" if $verbose;
    $file_lines++;
	print DSP $doc_type;
    print DSP <<"EOF";

<html>

<head>
<title>$in_name to HTML</title>
<style type="text/css">
<!-- /* some style */
body { 
	background-image:url('cldsphp.jpg');
	margin: 0cm 1cm 0cm 1cm; }
h1 {
 background:#efefef;
 border-style: solid solid solid solid;
 border-color:#d9e2e2;
 border-width:1px;
 padding:2px 2px 2px 2px;
 font-size:200%;
 text-align:center;
}
.ctr { text-align: center; }
.a { color:red; }
.b { color:#006666; }
.c { color:blue; }
.d { color:#a52a2a; }
.e { color:#9400d3; }
.f { color:#666666; }
.o { color:#008b8b; }
.v { color:#a52a2a; }
.t { color:#006600; }
.cd {
  /* top, right, bottom, left */
  padding: 0px 10px 0px 10px;
  margin: 1px 10px 1px 10px;
  background: #f0f8ff;
  border-width: 1px;
  border-style: solid solid solid solid;
  border-color: #cccccc;
  width: 90%;
  font-family:"Courier New";
}
// -->
</style>
</head>

<body>

<h1>$in_name to HTML</h1>

<p class="ctr"><a href="index.htm">index</a></p>

EOF
	print DSP '<p>Generated ';
	print DSP scalar localtime(time());
	print DSP ", from <b>$in_name</b>, by <b>$0</b>, my Perl text-to-html \n";
	print DSP "<a href=\"http://geoffmclane.com/mperl/samples/index.htm\">'converter'</a></p>\n";
    print "Closing $out_name.\n" if $verbose;
    close(DSP);
}

sub end_out_file {
    my ($out_name, $in_name) = @_;
    print "Appending to $out_name\n" if $verbose;
    open(DSP, ">>$out_name") || die "Can not append to $out_name: $!\n";
    print "Writing to $out_name ...\n" if $verbose;
	print DSP "<p class=\"ctr\"><a href=\"index.htm\">index</a></p>\n";
	print DSP "</body>\n";
	print DSP '<!-- generated ';
	print DSP scalar localtime(time());
	print DSP ", from $in_name, by $0, my text-to-html converter - geoffmclane.com -->\n";
    print DSP <<"EOF";
</html>
EOF

    print "Closing $out_name.\n";
    close(DSP);
}


sub do_this_file {
    my ($out_name,$mfile) = @_;
    print "Opening, for append $out_name\n" if $verbose;
    open(DSP, ">>$out_name") || die "Can't append to $out_name: $!\n";
    print "Writing to $out_name ...\n" if $verbose;
    $file_lines++;
 	dsp_add_src(\*DSP, $mfile);
    close(DSP);
    print "Closed $out_name.\n" if $verbose;
}

sub dsp_add_src {
    my ($fh,$file) = @_;
	my $line_num = 0;
	my $dn_para = 0;
	my $tx = '';
	if (-f $file) {
		print "Reading $file ...\n";
		open(INF, $file) || die "Unable to open $file!\n";
		if ($use_pre) {
			print $fh '<pre class="cd">'."\n";
		}
	    while (<INF>) {
			$line_num++;
			#$_ .= "\n" unless substr ($_, -1, 1) eq "\n";
			chomp; # clear end of line
			my $ln = length;
			$tx = $_; # get the original line
			# if ( ! $ln || /$WHITE_PATTERN/o) {
			if ( /$WHITE_PATTERN/o ) {
				print "white [$_]$ln\n" if $verb2;
				if ( !$use_pre ) {
					print $fh "\</p\>\n" if $dn_para;
					$dn_para = 0;
				}
			} else {
				if (!$use_pre) {
					print $fh "\<p\>\n" if ! $dn_para;
					$dn_para = 1;
				}
				#chomp; # clear end of line
				#s/\t/&nbsp;&nbsp;&nbsp; /g;
				s/&/&amp;/g; # convert '&' to '&amp;'
				s/\t/$tab_stg /g; # substitute TAB characters
				s/"/&quot;/g; # sub double quotes
				s/\</&lt;/g; # sub less than tag beginning
				s/\>/&gt;/g; # and html/xml tag ending
				$ln = length; # get the final length
				if ($use_pre) {
					print $fh "$_\n"; # out the line
				} else {  # if ( !$use_pre ) {
					if (substr ($_, 0, 1) eq ' ') { # if starts with a space
						my $sps = 0;
						my $nbs = '&nbsp;';
						for ($sps = 1; $sps < $ln; $sps++) {
							if (substr ($_, $sps, 1) ne ' ') {
								last;
							}
							$nbs .= '&nbsp;' if $sps > 1;
						}
						$sps-- if $sps > 1; # back off last space, if more than 1
						print "Replacing $sps with [$nbs] ...\n" if $verb2;
						s/ {$sps}/$nbs/; # replace (N) spaces with '&nbsp; x N
						if ($verb2) {
							my (@vals) = split;
							while (@vals) {
								my ($vc) = shift (@vals);
								print "[$vc] ";
							}
							print "\n";
						}
					} # if it was space beginning
					print $fh "$_\<BR\>\n"; # out the line
				}
				print "sig [$_]$ln\n" if $verb2;
			}
		}
		if ($use_pre) {
			print $fh '</pre>'."\n";
		} else {
			print $fh "\</p\>\n" if $dn_para;
		}
		close(INF);
		print "Done $file ... $line_num lines ...\n";
	} else {
		print $fh "WARNING: Missed SOURCE [$file]\n";
		print "WARNING: Missed SOURCE [$file]\n";
	}
}

sub dirname { # passed a path, './dir1/dir2/file.name' returns './dir1/dir2/
my ($file) = @_;
my ($sub);
($sub = $file) =~ s,/+[^/]+$,,g;
$sub = '.' if $sub eq $file;
return $sub;
}

#if (substr ($_, 0, 1) eq ' ') {
#	my (@vals) = split;
#	while (@vals) {
#		my ($vc) = shift (@vals);
#		print "[$vc] ";
#	}
#	print "\n";
#}

1;
