#!/usr/local/bin/perl
# title - Print title of HTML or text file
# Copyright 2014 David Meyer <papa@sdf.org>  +JMJ
# (License and documentation at bottom of file.)

# Modules ###########################################################
use strict;
use warnings;
use Getopt::Std;

# Configuration #####################################################


# Globals ###########################################################


# Functions #########################################################

sub capitalize {
    my($x) = @_;
    my $init = substr($x, 0, 1);
    $init =~ tr/a-z/A-Z/;
    return $init . substr($x, 1, length($x));
}

sub capfname {
    my($file) = @_; 
    my @path = split '/', $file;
    my($name, $ext) = split '\.', $path[$#path];
    $name =~ s/_/ /g;
    my @word = split /\s/, $name;
    $word[0] = capitalize($word[0]);
    if ($#word > 0) {
	$word[$#word] = capitalize($word[$#word]);
	for my $n (1..$#word-1) {
	    if ($word[$n] !~ /^(a|an|the|in|to|by|with)$/i) {
		$word[$n] = capitalize($word[$n]);
	    }
	}
    }
    for my $w (@word[0..$#word-1]) {
	print "$w ";
    }
    print "$word[$#word]\n";
}

# Process arguments #################################################
#%options = ();
#getopts('', \%options);

# Main driver #######################################################

our $file = $ARGV[0];

$file =~ m![\w\.\$/]+! || die "invalid character in file name $file";

if ($file =~ /\.s?html?/i) {
    my $INF = open($file, 'i') || die "unable to open file $file";
    do {
	$_ = <$INF>;
    } until (eof($INF) || $_ =~ /\<title\>|\<h1\>/i);
    if (eof($INF)) {
	print capfname($file) . "\n";
    }
    else {
	$_ =~ s/\<[^\>]+\>//g;
	print $_;
    }
}
elsif ($file =~ /\.txt/i) {
    my $INF = open($file, 'i') || die "unable to open file $file";
    $_ = <$INF>;
    if (eof($INF)) {
	capfname($file);
    }
    else {
	$_ =~ s/-\*-.*-\*-//;
	$_ =~ s:/\*\s*::;
	$_ =~ s:\s*\*/::;
	$_ =~ s/^#\s*//;
	print $_;
    }
}
else {
    capfname($file);
}

exit 0

__END__

# Documentation #####################################################
=head1 NAME

template.pl - Perl script template (command line)

=head1 SYNOPSIS/USAGE

=head1 DESCRIPTION

Mark up code elements with C<>, file names with F<> (or C<> for
readability), command names with B<>. Also I<> for italics, U<> for
underline. Entities: E<lt> ('<'), E<gt> ('>').

=head1 OPTIONS

=item B<-o> I<value>, B<--option>=I<value>

=head1 RETURN VALUE

=head1 ERRORS

=head1 DIAGNOSTICS

=head1 EXAMPLES

=head1 ENVIRONMENT

=over 6

=item VARIABLE

Description of usage of environment variable C<VARIABLE>.

=back

=head1 FILES

=head1 BUGS, LIMITATIONS, AND CAVEATS

=head1 NOTES

=head1 AUTHOR

David Meyer <papa@sdf.org>

=head1 HISTORY

=head1 COPYRIGHT AND LICENSE

Copyright 201x David Meyer

=head1 SEE ALSO



# Emacs control #####################################################
#Local variables:
#mode: perl
#End: