#!/usr/local/bin/perl

use CGI;
$query = new CGI;
print $query->header;
&do_prompt($query);
&do_work($query);
&print_tail;

sub do_prompt {
    my($query) = @_;
    # define the types of calculations we'll offer
    my(@types) = ('count lines','count words','count characters');

    print <<END;
<H1>Word Counts</H1>
Select the <VAR>browse</VAR> button to choose a text file
to upload.  When you press the submit button, this script
will count the number of lines, words, and characters in
the file.
END
    ;

    # Start a multipart form.
    print
	$query->start_multipart_form,
	"Enter the file to process:",
	$query->filefield(-name=>'filename',
			  -size=>30),"<BR>",
	$query->checkbox_group(-name=>'count',
			       -values=>\@types,
			       -defaults=>\@types),"<P>",
	$query->reset,$query->submit(-label=>'Process File'),
	$query->end_form;
}

sub do_work {
    my($query) = @_;

   # Process the form if there is a file name entered
    if ($file = $query->param('filename')) {
	print "<HR>\n";
	print "<H2>$file</H2>\n";
	while (<$file>) {
	    $lines++;
	    $words += @words=split(/\s+/);
	    $characters += length($_);
	}
	grep($stats{$_}++,$query->param('count'));
	if (%stats) {
	    print "<STRONG>Lines: </STRONG>$lines<BR>\n" if $stats{'count lines'};
	    print "<STRONG>Words: </STRONG>$words<BR>\n" if $stats{'count words'};
	    print "<STRONG>Characters: </STRONG>$characters<BR>\n"
		if $stats{'count characters'};
	} else {
	    print "<STRONG>No statistics selected.</STRONG>\n";
	}
    }
}

sub print_tail {
    print <<END;
<HR>
Last modified 6 May 1996.
END
    ;
    print $query->end_html;
}
