#!/usr/bin/perl
#
# FHTML.PL
# Copyright (C) 1997 John Watson
# e-mail: john@watson-net.com
#
# -----About-----
# Formats and indents html source code and writes a new file with
# the results. It makes code generated by some wysiwyg html editors
# easier to read for humans.
#
# Note:
#   This program uses spaces to do indents so it can add a lot of
#   bytes to the file size.  Might change to tabs although in that case
#   you lose fine-grain control over the amount of space indented.
#
# The latest copy of this script and documentation can be obtained from
# http://www.watson-net.com/
#
# -----History-----
# 2.3	September 2, 1997 Added the option to use tabs instead of
#		spaces for indenting (-t).  Also changed $tags variable so
#       that "</td" are no longer put on new lines.  This was done
#       because "</td>" by itself looks funny plus the extra white
#       space created by the new line was creating page layout
#       problems.
#
# 2.2  August 13, 1997 Another change to formatting.  Added code
#       to remove trailing spaces from lines.
#
# 2.1	August 11, 1997 Changed formatting againg.  Was
#		experiencing some problems with script tags.  The
#       script would sometimes be corrupted by the old routines where
#       the begin script tag and the end script tag were being put
#       on new lines by themselves.  This version just ignores the
#       entire line.
#
#		Added code to replace (C) with &copy; and (R) with &reg; (-c)
#		NOTE: this could cause problems if you use those literals within
#       quotes or tags.  If so, don't use the -c option. :)
#
# 2.0   Cleaned up code
#       Changed formatting code
#       Made formatting more flexible through $tags variable
#
# 1.1   Changed formatting code
#
# 1.0   April 23, 1997 First release
#
# -----Distribution-----
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

require "newgetopt.pl";

srand();

$progname = $0;
$progname =~ s@(.*?)(/|\\)@@ig;

$generate = '<meta name="GENERATOR" content="FHTML.PL HTML FORMATTER">';
$credit = <<EOT;
FHTML.PL HTML Formatter 2.3 John Watson (john\@watson-net.com)
Copyright (C) 1997 John Watson
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License.
This program comes with absolutely no warranty.
EOT

# defaults
$amount = 0;
$replace = 0;
$lower = 0;
$upper = 0;
$quiet = 0;
$convert = 0;
$usetabs = 0;

# tags to format
$tags = "<html|</html|<body|</body|<head|</head|<title";
$tags .= "|<isindex|<link|<meta|<!doctype";
$tags .= "|<table|<tr|<th|<td|</th|</tr|</table|<caption";
$tags .= "|<thead|</thead|<tbody|</tbody";
$tags .= "|<p|<br|<blockquote|<hr|<center|</center|<div|</div";
$tags .= "|<col|<colgroup";
$tags .= "|<marquee|</marquee";
$tags .= "|<style|</style";
$tags .= "|<h1|<h2|<h3|<h4|<h5|<h6";
$tags .= "|<ul|</ul|<ol|</ol|<dl|</dl|<li|<dt|<dd|<dir|</dir|<menu|</menu";
$tags .= "|<map|<area|</map";
$tags .= "|<base|<basefont|<bgsound";
$tags .= "|<object|<applet|<param|</object|</applet|<embed|</embed";
$tags .= "|<frameset|<frame|<noframes|</noframes|</frame|</frameset";
$tags .= "|<form|</form|<input|<select|<option|</select|<textarea";

$tagindent = "<table|<tr|<td";
$tagindent .= "|<select|<form";
$tagindent .= "|<frameset";
$tagindent .= "|<ul|<ol|<dl|<dir|<menu|<map";

$tagunindent = "</table|</tr|</td";
$tagunindent .= "|</select|</form";
$tagunindent .= "|</frameset";
$tagunindent .= "|</ul|</ol|</dl|</dir|</menu|</map";

# get options
NGetOpt('n:i','r','l','u','q','h','t','todo');

# to do
if ($opt_todo) {
    print <<EOT;
$credit

To do list:
    Everything's done?  Everything's DONE!  Actually, it's kind of hacky.
    I'll probably rewrite it.
EOT
    exit;
}

# get input files
@files = @ARGV;

# if not input files display usage
if ($#files+1 <= 0 || $opt_h) {
    usage();
    exit(0);
}

# amount to indent
if (defined($opt_n) && $opt_n >= 0) { $amount = $opt_n; }

# amount to indent
if (defined($opt_t)) { $usetabs = 1; }

# replace original file
if ($opt_r) { $replace = 1; }

# convert tags to lower-case
if ($opt_l) { $lower = 1; }

# convert tags to upper-case
if ($opt_u) { $upper = 1; }

# convert literals to HTML
if ($opt_c) { $convert = 1; }

# quiet mode
if ($opt_q) { $quiet = 1; }

if (!$quiet) { print "$credit\n\nProcessing...\n"; }

foreach(@files) {
    @lines = ();
    @temp = ();
    
    $filein = $_;
    if ($replace) {
        $fileout = $filein;
    } else {
        $fileout = "$filein.out";
    }
    
    # first pass: read the file into memory
    open(i,"<$filein") || die "Can't open $_ ";
    while (!eof(i)) {
        $line = <i>;
        push @temp, $line;
    }
    close(i);
    splitlines();
    
    # second pass: put everything except non-formattable on single line
    if (!$quiet) { print "$_\n"; }

    $SCRIPT = 0;
    $COMMENT = 0;
    $PRE = 0;

    $temp = '';
    foreach(@lines) {
        $SCRIPT = 0 if ($line =~ m@(</script|%>)@ig);
        $COMMENT = 0 if ($line =~ m@(-->|</comment)@ig);
        $PRE = 0 if ($line =~ m@</pre>@ig);
        
        $line = $_;
        
        $SCRIPT = 1 if ($line =~ m@(<script|<%)@ig);
        $COMMENT = 1 if ($line =~ m@(<!--|<comment)@ig);
        $PRE = 1 if ($line =~ m@<pre@ig);

        if (!$SCRIPT && !$COMMENT && !$PRE) {
            # remove all tabs
            $line =~ s/\t//ig;
            
            # remove spaces just before or after an angle bracket
            $line =~ s/<\ /</ig;
            $line =~ s/\ >/>/ig;
            if ($line =~ />$/) {
                $temp .= $line;
            } else {
                $temp .= $line." ";
            }
        } else {
            $temp .= "\n".$line."\n";
        }
    }
    push @temp, $temp;
    splitlines();
    
    $SCRIPT = 0;
    $COMMENT = 0;
    $PRE = 0;

    # third pass: format tags
    foreach(@lines) {
        $SCRIPT = 0 if ($line =~ m@(</script|%>)@ig);
        $COMMENT = 0 if ($line =~ m@(-->|</comment)@ig);
        $PRE = 0 if ($line =~ m@</pre>@ig);
        
        $line = $_;
        
        $SCRIPT = 1 if ($line =~ m@(<script|<%)@ig);
        $COMMENT = 1 if ($line =~ m@(<!--|<comment)@ig);
        $PRE = 1 if ($line =~ m@<pre@ig);

        if (!$SCRIPT && !$COMMENT && !$PRE) {
            # remove extra whitespace
            $line =~ s/\ {2,}/\ /ig;

            # put tags on new lines
            $line =~ s@($tags)@\n$1@ig;

			# convert literals to HTML
			if ($convert) {
				$line =~ s@©@&copy;@ig;
				$line =~ s@®@&reg;@ig;
			}
			
            # uppercase/lowercase tags and convert literals
            if ($upper || $lower || $convert) {
                for($i=0; $i<length($line); $i++) {
                    $char = substr($line,$i,1);

                    if ($char eq '<') { $in = 1; }
	                if ($char eq '>') { $in = 0; }
    	            if ($char eq '"') {
        	            if ($quote) { $quote = 0; }
            	        else { $quote = 1; }
                	}

					# lower/upper- case tags
                    if ($in && !$quote) {
	                    substr($line,$i,1) = uc($char) if $upper;
    	                substr($line,$i,1) = lc($char) if $lower;
        	        }

					# convert (c) and (r) to &copy; and &reg;
        	        if (!$quote) {
        	        	# interesting... it's legal to assign a string to a character
        	        	# within a string.
        	        	if (ord($char) == 169) { substr($line,$i,1) = "&copy;"; }
        	        	if (ord($char) == 174) { substr($line,$i,1) = "&reg;"; }
        	        }
                }
            }
	    }
        push @temp, $line;
    }
    splitlines();

    # fourth pass: indent tags/remove trailing spaces
    $indent = 0;
    
    $SCRIPT = 0;
    $COMMENT = 0;
    $PRE = 0;

    foreach (@lines) {
        $SCRIPT = 0 if ($line =~ m@(</script|%>)@ig);
        $COMMENT = 0 if ($line =~ m@(-->|</comment)@ig);
        $PRE = 0 if ($line =~ m@</pre>@ig);
        
        $line = $_;
    
        $SCRIPT = 1 if ($line =~ m@(<script|<%)@ig);
        $COMMENT = 1 if ($line =~ m@(<!--|<comment)@ig);
        $PRE = 1 if ($line =~ m@<pre@ig);
        
        $spaces = "";
        if (!$SCRIPT && !$COMMENT && !$PRE) {
        	# remove trailing spaces
        	$line =~ s@(\ $)@@ig;
        	
            $indent -= $line =~ s@($tagunindent)@$1@ig;

			$spaces = "";
            for ($j=0; $j<$indent; $j++) {
                for ($k=0; $k<$amount; $k++) {
                    if ($usetabs) {
                    	$spaces .= "\t";
                	} else {
                		$spaces .= " ";
            		}
                }
            }
        }
        
        push @temp, $spaces.$line;
        
        if (!$SCRIPT && !$COMMENT && !$PRE) {
            $indent += $line =~ s/($tagindent)/$1/ig;
        }
    }
    splitlines();
    
    open (o, ">$fileout");
    foreach (@lines) { print o "$_\n"; }
    close(o);
}

exit;

sub splitlines {
    @lines = ();

    foreach(@temp) {
    	$line = $_;
    	if ($line eq "\n") {
			# This preserves blank lines in script and comments.
    		push @lines, " ";
    	} else {
	   		push @lines, split(/\n/, $line);
	   	}
   	}

    @temp = ();
}

sub usage {
    print <<EOT;
$credit
Usage: $progname [-options] filespec [filespec...]

    filespec is a filename or filename pattern (e.g. *.htm)
    -n       Number of tabs/spaces to indent (default: 0)
    -t       Uses tabs instead of spaces for indenting
    -r       Replace original with new file
    -l       Convert tags to lower-case
    -u       Convert tags to upper-case
    -c       Convert (C) -> &copy; and (R) -> &reg;
    -h       Help
    -todo    To do list
EOT
}
