#!/usr/bin/perl -T

use strict;
use CGI;

# create a new form to display results
my $form = CGI->new();

# get the whole list of items
my @items = dataFromFile("regList.dat");

# get which boxes are checked
my @boxes = dataFromFile("checkedBoxes.dat");

#print the contents of the file
print $form->header;
print << "EndHead";

  <html>
    <head>
      <title>Registry List</title>
    </head>
    <body>
    <h1>Registry List</h1>
    <p>Thanks for visiting our registry and helping us prepare for our
       bundle of joy. If you purchase something for us from this list,
       please check it off and press "Submit" to update the list.
    <P>*** We will buy anything marked with "***" ourselves.
    <form name="checkList" action="saveChecks.cgi" method="post">
      <h3>The List</h3>
EndHead

# show which boxes were selected
my $count = 0;
my $checkCount = 0;


foreach my $item (@items) {
  if (substr($item, 0, 1) eq "<") {
    print "$item";
  } else {
    if (@boxes[$checkCount] == $count) {
      print "<input type='checkbox' name='box' value=$count checked> ",
	"$item<br>";
      ++$checkCount;
    } else {
      print "<input type='checkbox' name='box' value=$count> ",
	"$item<br>";
    }
  }
  ++$count;
}

# close that html
print << "EOF";
      <br>
      <input type="submit" value="Submit">
    </form>
  </body>
</html>
EOF

# open the data file and return the results
sub dataFromFile {
  my ($filename) = @_;

  #open the file for reading
  open(INF, $filename) or
    dienice("Couldn't open $filename for reading: $!\n");

  # get which boxes are checked
  my @data = <INF>;

  #close the file
  close(INF);

  # return the data
  return @data;
}

# die nicely, making sure no data is lost, and print an error message
sub dienice {
  my($msg) = @_;
  print $form->header( "text/html" ),
    $form->start_html( -title	=> "Error"),
      $form->h2( "Error"),
	$form->end_html;
  print $msg;
  exit;
}

