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

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


if(  $q->param('file') )
{
    &view_resp( $q->param('file') );
}
elsif( $q->param('group') )
{
    &view_files( $q->param('group') );
}
else
{
    &view_groups;
}

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

sub view_groups
{
    print "<h1>Grupper</h1>\n";
    foreach(sort glob 'data/grupp_*')
    {
	print "<p><a href=view_result.cgi?group=$_>$_</a>\n";
    }
}

sub view_files
{
    my( $group ) = @_;

    print "<h1>Inkomna svar</h1>\n";
    foreach(sort glob "$group/resp_*")
    {
	print "<p><a href=view_result.cgi?file=$_>$_</a>\n";
    }
}

sub view_resp
  {
    my( $file ) = @_;
    my @question = &get_questions;

    print "<h1>$file</h1>\n";

    open FILE, $file or die $!;
    while(<FILE>)
    {
	next unless my($nr, $grade, $enc_ques ) = split /\s*;\s*/;
	my $question = $q->escapeHTML($q->unescape( $enc_ques ));

	print "<h2>$nr: ", $question[$nr]{question},"</h2>\n";
	if( $question[$nr]{from} )
	{
	    print "<p><small>",$question[$nr]{from},"-",$question[$nr]{to},": $grade</small>\n";
	}
	print "<p>$question\n";
    }
    
}


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 get_questions
{
    my @question;
    open QUESTIONS, "questions.txt" or die $!;
    foreach my $row (<QUESTIONS>) 
    {
	if ( $row ) 
	{
	    my($nr, $question, $from, $to) = split(/\s*;\s*/, $row);
	    
	    $question[$nr] = { question => $question,
			       from     => $from,
			       to       => $to,
			   };
	}
    }
    close QUESTIONS;
    return @question;
}

