use strict;

sub main($);
sub convert($);

my $dir = ".";

if( $#ARGV >= 0 ) {
	$dir = $ARGV[ 0 ];
}

main( $dir );

sub main($)
{
	my ($dir) = @_;
	
	opendir DIR, $dir;
	my @files = readdir DIR;
	closedir DIR;

	foreach my $file( sort (@files ) ) {
		if( ( $file ne ".." and $file ne "." ) and $file =~ /\.html$/ ) {
			convert( $dir . "/" . $file );
		}
	}
}

sub convert($)
{
	my ($file) = @_;
	my $tmp = $file . ".tmp";
	
	print $file, "\n";
	open IN, $file;
	open OUT, ">$tmp";
	
	my $state = 0;
	my $indent = 0;
	
	my $ch;
	while( defined( $ch = getc( IN ) ) ) {
		if( $state == 0 ) {
			if( $ch eq '<' ) {
				$state = 1;
			}
			else {
				print OUT $ch;
			}
		}
		elsif( $state == 1 ) {
			if( $ch eq 's' ) {
				$state = 2;
			}
			elsif( $ch eq '/' ) {
				$state = 8;
			}
			else {
				$state = 0;
				print OUT "<";
				print OUT $ch;
			}
		}
		elsif( $state == 2 ) {
			if( $ch eq 'p' ) {
				$state = 3;
			}
			else {
				$state = 0;
				print OUT "<s";
				print OUT $ch;
			}
		}
		elsif( $state == 3 ) {
			if( $ch eq 'a' ) {
				$state = 4;
			}
			else {
				$state = 0;
				print OUT "<sp";
				print OUT $ch;
			}
		}
		elsif( $state == 4 ) {
			if( $ch eq 'n' ) {
				$state = 5;
			}
			else {
				$state = 0;
				print OUT "<spa";
				print OUT $ch;
			}
		}
		elsif( $state == 5 ) {
			if( $ch eq '>' ) {
				$state = 0;
				$indent++;
			}
		}
		elsif( $state == 8 ) {
			if( $ch eq 's' ) {
				$state = 9;
			}
			else {
				$state = 0;
				print OUT "</";
				print OUT $ch;
			}
		}
		elsif( $state == 9 ) {
			if( $ch eq 'p' ) {
				$state = 10;
			}
			else {
				print OUT "</s";
				$state = 0;
				print OUT $ch;
			}
		}
		elsif( $state == 10 ) {
			if( $ch eq 'a' ) {
				$state = 11;
			}
			else {
				$state = 0;
				print OUT "</sp";
				print OUT $ch;
			}
		}
		elsif( $state == 11 ) {
			if( $ch eq 'n' ) {
				$state = 12;
			}
			else {
				$state = 0;
				print OUT "</spa";
				print OUT $ch;
			}
		}
		elsif( $state == 12 ) {
			if( $ch eq '>' ) {
				$state = 0;
			}
		}
	}
	close IN;
	close OUT;

	my $bak = $file . ".bak";
	unlink( $bak );
	rename( $file, $bak );
	rename( $tmp, $file );
}
