#!/usr/bin/perl -w
use strict;
use CGI;

my $pwd = `pwd`;
chop($pwd);
$pwd =~ /(.*\/)(.*)/;
my $class = $2;
my $title = "Materials Available for MATH $class"; ##-------- modify

my $tth='/usr/local/bin/tth';

## get the files
my $intro = "$pwd/intro.tex";
my $hypernews="$pwd/hypernews.tex";
my $first_day = "$pwd/1st-day.tex";
my $syllabus = "$pwd/syllabus.tex";

## update notes if not done
&update_notes;
my @notes = <$pwd/notes*.html>;

#### start CGI
my $query = new CGI;
my $todo = $query->param('todo') || "";

my %available_actions = (
			 'firstday',"Course Expectations",
			 'syllabus','Course Syllabus',
			 'notes',"Course handouts",
			 );

my @known_actions = keys %available_actions;
my @list = grep $todo, @known_actions;
my $first_time = 1;
unless ($query->param) {
  $first_time = 0;
}

unless (scalar @list > 0 ||
	$first_time eq 0) {
  exit;
}

print  $query->header, $query->start_html(-title=>$title);
### start output
if (! $query->param) {
  &print_intro;
}
&print_1st_day if $todo eq 'firstday';
&print_syllabus if $todo eq 'syllabus';
&print_notes if $todo eq 'notes';
print $query->hr;
&print_hyper;    
&print_selection;
print $query->end_html;


sub print_intro {print_file($intro)}
sub print_hyper {print_file($hypernews)};
sub print_1st_day {print_file($first_day)};
sub print_syllabus {print_file($syllabus)};
sub print_notes {
  if (scalar @notes == 0) {
    print "<STRONG> There are no available class handouts</STRONG><P>\n";
    return;
  }
  ## display a link to each notes:
  print + 
    "<STRONG> These are the available class handouts</STRONG><P>\n",
    "Click on the link to see the handout<P>\n";
  my $notes;
  &update_notes;
  foreach $notes (@notes) {
    $notes =~ /(notes-(.*))\.html/;
    my $notes = $1;
    my $msg = $2;
    print $query->a({-href=>"$notes.html"},"<em>$msg</em>");
    print "<P>\n";
  }
};

sub update_notes {
  my @tex_notes = <$pwd/notes-*.tex>;
  return unless scalar @tex_notes > 0;
  foreach (@tex_notes) {
    /(.*)\.tex/;
    my $name = $1;
    unless (-e "$name.html") {
      system("/usr/local/bin/tth < $_ > $name.html");
    }
  }
}

sub print_selection {
  print $query->startform;
  print "What do you wish to see? Please choose from the following:<P>\n";
  my @values = keys %available_actions;
  print $query->radio_group(-name=>'todo',
                             -values=>\@values,
                             -linebreak=>'true',
                             -labels=>\%available_actions);
  print $query->submit;
  print $query->endform;

}

sub tth {
  my $file = shift;
  my $switches = '-r';		# no header
  open (TTH,"$tth $switches <$file |" );
  my @text = <TTH>;
  return @text;
}
sub print_file {
  my $file = shift;
  if (-e $file) {
    my @text = tth($file);
    foreach (@text) {
      ## filter out tth
      print $_;
    }
  } else {
    print "<STRONG>There is no information available for $available_actions{$todo}</STRONG><P>\n";
  }

};



