#!/Perl

print "Hello, World...\n";
my @excl = ("404.shtml","speed1.htm","test3.php","test4.php","test5.php","hits.php",
"phpinfo.php","popup1.htm");

my $in_dir = shift || die "ERROR: Must give input folder ...\n";
my $out_file = 'tempout2.txt';
my $OH;
open $OH, ">$out_file" || die "ERROR: Can NOT create output file ... aborting ...\n";

print "Processing directory $in_dir ...\n";

opendir( DIR, $in_dir) || die "ERROR: Can NOT open $in_dir ... aborting ...\n";
my @files = readdir(DIR);
closedir DIR;

print "Found ".scalar @files." items in the directory ...\n";
my $file;
my $filcnt = 0;
my @titles = ();
foreach $file (sort @files) {
	if (($file eq '.')||($file eq '..')) {
		next;
	}
	my $ff = $in_dir . '/' . $file;
	if ( -d $ff ) {
		#prt( "Ignore Directory $file ...\n");
	} else {
		if (is_my_file($file)) {
			my $tit = get_title($ff);
			if (length($tit) == 0) {
				$tit = $file;
			}
			push(@titles, "$tit|$file");
			### prt( "\$mypages[$filcnt] = \"$file|$tit\";\n");
			$filcnt++;
		} else {
			#prt( "IGNORE $file ...\n" );
		}
	}
}
prt( "Done list in FILE order ... now title order ...\n" );
my $fc = 0;
foreach $file (sort @titles) {
	prt( "\$mypages[$fc] = \"$file\";\n" );
	$fc++;
}
close $OH;

sub get_title {
	my ($f) = @_;
	open $IF, "<$f" or die "Can not OPEN $f! ... aborting ...\n";
	my @lines = <$IF>; # slurp whole file, to an array of lines
	close($IF);
	my $titln = '';
	my $intit = 0;
	foreach my $ln (@lines) {
		chomp $ln;
		if ($intit) {
			if ($ln =~ /<\/title>/i) {
				$titln .= ' '.$ln;
				$intit = 0;
			} else {
				$titln .= ' '.$ln;
			}
		} elsif ( $ln =~ /<title/i ) {
			if ($ln =~ /<\/title>/i) {
				$titln = $ln;
			} else {
				$titln = $ln;
				$intit = 1;  # stay here until end
			}
		} else {
			
		}
	}
	if (length($titln)) {
		# strip <title
		$pos = index(uc($titln),'<TITLE>');
		if ($pos != -1) {
			$titln = substr($titln, ($pos + 7));
			$pos = index(uc($titln), '</TITLE>');
			if ($pos > 0) {
				$titln = substr($titln,0, $pos);
			}
		}
	}
	while(length($titln)) {
		if (substr($titln,0,1) eq ' ') {
			$titln = substr($titln,1);
		} else {
			last;
		}
	}
	while (substr($titln,-1) eq ' ') {
		$titln = substr($titln,0, length($titln)-1);
	}
	return $titln;
}

sub is_my_file {
	my ($f) = @_;
	my $ret = 0;
	if ($f =~ /(.*)\.htm$/i) {
		$ret = 1;
	} elsif ($f =~ /(.*)\.html$/i) {
		$ret = 1;
	} elsif ($f =~ /(.*)\.shtml$/i) {
		$ret = 1;
	} elsif ($f =~ /(.*)\.php$/i) {
		$ret = 1;
	}
	if ($ret) {
		foreach my $f2 (@excl) {
			if (uc($f2) eq uc($f)) {
				$ret = 0;
				last;
			}
		}
	}
	return $ret;
}


sub prt {
	my ($m) = @_;
	print $m;
	print $OH $m;
}

