#!/usr/bin/perl -w
use strict;
use English;
use CGI::Debug;
use CGI;
my $q = new CGI;

print "Content-type: text/html\n\n";

&explain and exit unless $q->param('user_id');
&save_answer if $q->param('question_id');

&show_next_question or &say_thank_you;

exit;
######################

sub say_thank_you
  {
    print &parse_write( file => 'done.tmpl');
  }

sub explain
  {
    print &parse_write(file => 'explain.tmpl', 
		       values => {
				  user_id => $PROCESS_ID,
				 },
		      );
  }

sub show_next_question
  {
    open QUESTIONS, "questions.txt" or die $!;
    my ( $record );
    while(<QUESTIONS>)
      {
	@{$record}{'nr','question','from','to'} = split /\s*;\s*/;
	last if $record->{nr} > $q->param('question_id');
      }
    return undef if $record->{nr} == $q->param('question_id');
    
    $record->{'user_id'} = $q->param('user_id');
    print &parse_write( file => 'show.tmpl',
			values => $record,
		      );

  }

sub save_answer
  {
    my $grade   = $q->param('grade')   || "";
    my $comment = $q->param('comment') || "";
    my $enc_com = $q->escape($comment);

    open DATA, ">>data/resp_".$q->param('user_id') or die $!;
    print DATA join("; ", $q->param('question_id'), $grade, $enc_com), "\n";
    close DATA;
  }


sub parse_write
  {
    my( %args ) = @_;
    my $text = "";
    my $values = ();
    if( exists $args{'file'} )
      {
	open FILE, $args{'file'} or die $!;
	$text = join("", <FILE>);
      }
    elsif( exists $args{'string'} )
      {
	$text = $args{'string'};
      }
    else
      {
	die "parse_write called without string";
      }
    
    if( ref $args{'values'} eq 'HASH' )
      {
	$values = $args{'values'};
      }

    no strict 'refs';
    $text =~ s/^---DO (\w+)---\s*(.*)$/&{$1}($2,$values)/mge;
    # Execute the function refered by the first match
    
    
    $text =~ s/\$(\w+)/$values->{$1}/ge;
    return $text;
  }

sub rows
  {
    my( $string, $values ) = @_;
    my $text = "";
    open QUESTIONS, "questions.txt" or die $!;
    foreach my $row (<QUESTIONS>) {
      if ( $row ) {
	@{$values}{'nr', 'question'} = split(/\s*;\s*/, $row);
	# This means that  $values->{'question'} holds the second part, etc...

	$text .= &parse_write( values => $values,
			       string => $string,
			     );
      }
    }
    close QUESTIONS;
    return $text;
  }

sub grade
  {
    my( $string, $values ) = @_;
    
    if( $values->{'from'} )
      {
	return $string;
      }
    else
      {
	return "";
      }
  }
