#!/usr/bin/perl -w

use strict;
use IO::Socket;
use Getopt::Std;
use Config;
use POSIX;
use Tk;
use Tk::DialogBox;
use Tk::LabEntry;
use Time::HiRes;
use QuizRPC qw(packargs unpackargs);
use Tk::widgets qw(ROText);

use constant CANVAS_WIDTH => 100;
use constant XS_YELLOW => "#FFCC33";
use constant TIMEBAR_WIDTH => 30;
use constant TIMEBAR_UPDATE => 50; # in milliseconds
use constant MAXCONTESTANTS => 4;

my($VERSION) = q$Revision: 1.64 $ =~ /: ([\d.]+)/;

my @vraagfiles = grep { !/^#/ && !/^$/ }
		 map { s/^\s+//; s/\s+$//; $_ }
		 split /\n/,
q{
vragen/quizvragen.txt
};

# put regexes for allowed IPs that can connect here
my @allowed_ip = (
    q/^194\\.109\\.0\\./,
    q/^194\\.109\\.12\\./,
);

use constant STATUSTIMEOUT => 4000;
use constant DEFAULTBEDENKTIJD => 5;

my $COPYING = <<COPYING;
		    GNU GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License.  The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language.  (Hereinafter, translation is included without limitation in
the term "modification".)  Each licensee is addressed as "you".

Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.

  1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.

You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.

  2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

    a) You must cause the modified files to carry prominent notices
    stating that you changed the files and the date of any change.

    b) You must cause any work that you distribute or publish, that in
    whole or in part contains or is derived from the Program or any
    part thereof, to be licensed as a whole at no charge to all third
    parties under the terms of this License.

    c) If the modified program normally reads commands interactively
    when run, you must cause it, when started running for such
    interactive use in the most ordinary way, to print or display an
    announcement including an appropriate copyright notice and a
    notice that there is no warranty (or else, saying that you provide
    a warranty) and that users may redistribute the program under
    these conditions, and telling the user how to view a copy of this
    License.  (Exception: if the Program itself is interactive but
    does not normally print such an announcement, your work based on
    the Program is not required to print an announcement.)

These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.

In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

  3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:

    a) Accompany it with the complete corresponding machine-readable
    source code, which must be distributed under the terms of Sections
    1 and 2 above on a medium customarily used for software interchange; or,

    b) Accompany it with a written offer, valid for at least three
    years, to give any third party, for a charge no more than your
    cost of physically performing source distribution, a complete
    machine-readable copy of the corresponding source code, to be
    distributed under the terms of Sections 1 and 2 above on a medium
    customarily used for software interchange; or,

    c) Accompany it with the information you received as to the offer
    to distribute corresponding source code.  (This alternative is
    allowed only for noncommercial distribution and only if you
    received the program in object code or executable form with such
    an offer, in accord with Subsection b above.)

The source code for a work means the preferred form of the work for
making modifications to it.  For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable.  However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.

If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.

  4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License.  Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.

  5. You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Program or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.

  6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.

  7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all.  For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.

If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

  8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded.  In such case, this License incorporates
the limitation as if written in the body of this License.

  9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

Each version is given a distinguishing version number.  If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation.  If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.

  10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission.  For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this.  Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
COPYING

my $WARRANTY = <<WARRANTY;
  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.

  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
WARRANTY

use vars qw($opt_p $opt_v);
getopts('p:v');
$opt_p ||= 1726;
$QuizRPC::DEBUG = 1 if $opt_v;

my $bedenktijd = DEFAULTBEDENKTIJD;

my %remote_cmd = (
    MYNAMEIS => \&client_name,
    ISAY => \&client_antw,
);

my $vraagnr = -1;
my $curvraagnr;
my $mw = MainWindow->new();
setup_menu();
my $status = '';
create_fonts();
setup_mw();
setup_text();
read_vragen();
setup_socket();
MainLoop;

my $client_menu;
my %client;

my @fonts;

sub create_fonts {
    return if @fonts;

    push @fonts,
	$mw->fontCreate(qw/C_results -family Helvetica -size 15/),
        $mw->fontCreate(qw/C_title -family Helvetica -size 15 -weight bold/),
        $mw->fontCreate(qw/C_error -family Helvetica -size 10 -weight bold/);
}

# Tk::Text widget
my $T;
# process bar
my($qtime, $qtime_canv, $qtime_rect);
my($results_frame, @results, $show_answ, $default_show_answ);
my($answ_start_time);
my($vraag_but, $antw_but, $starttijd_but, $juisteantw_but, $leeg_but);

sub setup_mw {
    # status bar on the bottom
    $mw->Label(qw/-relief ridge -background black -foreground white
	-justify left/, -textvariable => \$status)
	->pack(qw/-side bottom -fill x -anchor w/);

    # progress bar.
    $qtime_canv = $mw->Canvas(
        qw/-background black -borderwidth 0 -relief flat
        -takefocus 0 -highlightthickness 0/,
        -width => CANVAS_WIDTH,
    )->pack(qw/-side left -fill y/);

    # results frame.
    $results_frame = $mw->Frame(qw/-background black/)
        ->pack(qw/-side bottom -fill x/);

    # create text window
    $T = $mw->Scrolled('ROText',
	qw/-scrollbars oe -wrap word -setgrid 1/
    )->pack(qw/-side top -fill both -expand 1/);

    # XXX this collection of buttons is rather ugly
    my $control_frame = $mw->Frame(qw/-background black -foreground white/)
	->pack(qw/-side top/);
    $vraag_but = $control_frame->Button(-text => "Vraag",
	-command => \&volgende_vraag)->pack(qw/-side left -fill both/);
    $antw_but = $control_frame->Button(-text => "Antwoord",
	qw/-state disabled/,
	-command => \&antwoord)->pack(qw/-side left -fill both/);
    $starttijd_but = $control_frame->Button(-text => "Start\ntijd",
	qw/-state disabled/,
	-command => \&start_tijd)->pack(qw/-side left -fill both/);
    $control_frame->Checkbutton(-text => "Antwoorden\nprojecteren",
	qw/-relief raised/,
	-variable => \$show_answ,
	-selectcolor => XS_YELLOW,
	-command => \&refresh_results,
    )->pack(qw/-side left -fill both/);
    $juisteantw_but = $control_frame->Button(-text => "Juiste\nAntwoord",
	qw/-state disabled/,
	-command => \&juiste_antwoord)->pack(qw/-side left -fill both/);
    $leeg_but = $control_frame->Button(-text => "Scherm\nLeeg",
	qw/-state disabled/,
	-command => \&scherm_leeg)->pack(qw/-side left -fill both/);
}

sub reset_buttons {
    for my $but ( \($vraag_but, $antw_but, $starttijd_but, $juisteantw_but,
	$leeg_but) )
    {
	$$but->configure(qw/-state normal/);
    }
}

# timebar stuff. MOSTLY IDENTICAL TO SAME ROUTINES IN ./quiz (sloppy cut&paste
# programming)
my $qtime_h;

sub preptime {
    $qtime = 0;
   
    return "BUGGEROFF" if $qtime_rect;
    $qtime_h = $qtime_canv->height() - 4;
    $qtime_rect = $qtime_canv->createRectangle(2, 2,
        2 + TIMEBAR_WIDTH, 2 + $qtime_h, 
        -fill => XS_YELLOW, -outline => XS_YELLOW);
    "OK";
}

my $timesup;

sub runqtime {
    my $self = shift;
    my($bedenktijd, $endtime) = @_;

    if ( ! $qtime_rect ) {
        return "BUGGEROFF";
    }
    $timesup = 0;
    my $timeID;
    $timeID = $mw->repeat(TIMEBAR_UPDATE,
        sub {
            update_timebar($timeID, $bedenktijd, $endtime);
        }
    );
    update_timebar($timeID, $bedenktijd, $endtime);
    "OK";
}

sub update_timebar {
    my($timeID, $bedenktijd, $endtime) = @_;

    my $now = Time::HiRes::time;
    if ( $now > $endtime ) {
        # time is up! make sure we don't get here twice somehow.
        return if $timesup++;

        # remove rect.
        $qtime_canv->delete($qtime_rect);
        $qtime_rect = undef;

        $timeID->cancel();
	# enable juiste_antw button
	$juisteantw_but->configure(qw/-state normal/);
    }
    else {
        my $left = $endtime - $now;
        $left = 0 if $left < 0;
        $left = $bedenktijd if $left > $bedenktijd;
        # update rect
        $qtime_canv->coords($qtime_rect,
            2, 2 + ($bedenktijd - $left) / $bedenktijd * $qtime_h,
            2 + TIMEBAR_WIDTH, 2 + $qtime_h);
    }
}

# stuff to read questions
# list of lists. contents:
# [0] - vraag
# [1] - image or undef
# [2] - undef if can-reorder, correct answer otherwise (1..4). For can-reorder
#     correct answ is always answ1
# [3] - answ1
# [4] - answ2
# [5] - answ3
# [6] - answ4
# [7] - extra explanation, if any
my @vraag;

sub setup_text {
    $T->tagConfigure(qw/title -font C_title/);
    $T->tagConfigure(qw/vraag -lmargin1 1c -lmargin2 2c -foreground blue/);
    $T->tagConfigure(qw/current -relief raised -borderwidth 1 -foreground red/);
    $T->tagConfigure(qw/gehad -lmargin1 1c -lmargin2 2c/,
	-foreground => "#303080");
    $T->tagConfigure(qw/antwoord -lmargin1 3c -lmargin2 4c
	-relief raised -borderwidth 1/);
    $T->tagConfigure(qw/error -font C_error -foreground red/);

    $T->tagBind('vraag', '<ButtonRelease-1>',
	sub { setcurrentvraag($T->index('current')) }
    );
    $T->tagBind('vraag', '<Enter>',
	sub {
	    my $text = shift;
	    $text->configure(qw/-cursor hand2/);
	}
    );
    $T->tagBind('vraag', '<Leave>',
	sub {
	    my $text = shift;
	    $text->configure(qw/-cursor xterm/);
	}
    );
    $T->bind('<Key-Return>',
	sub { setcurrentvraag($T->index('insert')) }
    );
}

sub clear_vragen {
    @vraag = ();
    $T->delete('1.0', 'end');
}

sub read_vragen {
    # read files into $T and @vraag
FILE:
    for my $file ( @vraagfiles ) {
	open(FILE, $file) or die "cannot read $file: $!\n";
	print STDERR "FILE: $file\n" if $opt_v;
	my $hadtitle;
	my $thisq;
	my $thispar = '';
	while ( <FILE> ) {
	    s/\s+$//;
	    next if /^\s*#/;
	    # check for blank line
	    if ( /^\s*$/ ) {
		if ( length $thispar ) {
		    if ( ! $thisq ) {
			# start of question
			$thisq = {};
			if ( ! $hadtitle ) {
			    # no title yet, use filename
			    insert_title($file);
			    $hadtitle++;
			}
		    }
		    process_par($thisq, $thispar);
		    $thispar = '';
		}
		next;
	    }
	    # check for "ronde"
	    if ( /^Ronde:\s+(.*)/i ) {
		insert_title($1);
		$hadtitle++;
		next;
	    }
	    # check for separator.
	    if ( /^\*+$/ ) {
		if ( length $thispar ) {
		    if ( $thisq && keys %$thisq ) {
			# process last paragraph of question
			process_par($thisq, $thispar);
		    }
		    else {
			# no question yet => it's a title
			insert_title($thispar);
			$hadtitle++;
		    }
		    $thispar = '';
		}
		if ( $thisq && keys %$thisq ) {
		    # time to finish the question
		    finish_question($thisq);
		}
		#clear $thisq, to start fresh
		$thisq = undef;
		next;
	    }
	    # answer
	    # %balance (
	    if ( /^\s*([a-d1-4])\)\s*(\S.*)$/i ) {
		if ( length $thispar ) {
		    if ( ! $thisq ) {
			# start of question
			$thisq = {};
			if ( ! $hadtitle ) {
			    # no title yet, use filename
			    insert_title($file);
			    $hadtitle++;
			}
		    }
		    process_par($thisq, $thispar);
		    $thispar = '';
		}
		if ( ! $thisq->{QUES} ) {
		    insert_error("Antwoord zonder vraag!");
		    close FILE;
		    next FILE;
		}
		$thisq->{CURANSW} = lc $1;
		$thispar = $2;
		next;
	    }
	    # anything else is just paragraph text
	    if ( ! length $thispar ) {
		# remove leading spaces at start of paragraph
		s/^\s+//;
		$thispar = $_;
	    }
	    elsif ( /^\s+/ ) {
		# text continued after spaces needs a forced newline
		$thispar .= "\n$_";
	    }
	    else {
		# other continuation text is just appended.
		$thispar .= " " . $_;
	    }
	}
	if ( length $thispar ) {
	    process_par($thisq, $thispar);
	    $thispar = '';
	}
	if ( $thisq && keys %$thisq ) {
	    # time to finish last question
	    finish_question($thisq);
	}
	close(FILE);
    }
}

sub insert_title {
    my $title = shift;

    print STDERR "Title: $title\n" if $opt_v;
    $T->insert(end => "\n");
    $T->insert(end => "$title\n", 'title');
}

sub insert_error {
    my $error = shift;
    
    print STDERR "ERROR: $error\n" if $opt_v;
    $T->insert(end => "\n");
    $T->insert(end => "$error\n", 'error');
}

sub process_par {
    my($q, $par) = @_;

    # ignore any junk not part of a question.
    if ( ! $q ) {
	print STDERR "Ignored junk:\n$par\n" if $opt_v;
	insert_error("$par\n");
    }
    elsif ( $q->{CURANSW} ) {
	# some answer given
	$q->{ANSW}{$q->{CURANSW}} = $par;
	delete $q->{CURANSW};
    }
    elsif ( $q->{ANSWIS} ) {
	# extra stuff after correct answer
	$q->{COMMENT} .= "\n" if $q->{COMMENT};
	$q->{COMMENT} .= $par;
    }
    elsif ( ! $q->{QUES} ) {
	$q->{QUES} = $par;
    }
    elsif ( ! exists $q->{ANSW} ) {
	# no answer yet... could be image
	if ( $par =~ /^.*\.gif$/ ) {
	    $q->{IMG} = $par;
	}
	else {
	    # nope... just continuation of the question
	    $q->{QUES} .= "\n$par";
	}
    }
    elsif ( $par =~ /^Het\s+juiste\s+antwoord\s+is\s*:\s*([1-4a-d])\b/i ) {
	# store correct answer
	$q->{ANSWIS} = $1;
    }
    else {
	# anything else is an error. answers can't have multiple paragraphs.
	insert_error("Wat moet ik met deze troep: $par");
    }
}

sub finish_question {
    my $q = shift;

    unless ( exists $q->{QUES} && exists $q->{ANSWIS} ) {
	insert_error("Vraag niet compleet!");
	return;
    }
    my $rec = [];
    $rec->[0] = $q->{QUES};
    $rec->[1] = $q->{IMG} if exists $q->{IMG};
    if ( ! exists $q->{ANSW}{$q->{ANSWIS}} ) {
	insert_error("Juiste antwoord $q->{ANSWIS} niet in rijtje");
	return;
    }
    if ( $q->{ANSWIS} =~ /\d/ ) {
	# ordered answers
	$rec->[2] = $q->{ANSWIS};
	for my $antwnr ( 1 .. 4 ) {
	    if ( ! exists $q->{ANSW}{$antwnr} ) {
		insert_error("Antwoord $antwnr bestaat niet!");
		return;
	    }
	    $rec->[2 + $antwnr] = $q->{ANSW}{$antwnr};
	}
    }
    else {
	# reorderable-answers
	$rec->[3] = $q->{ANSW}{$q->{ANSWIS}};
	my $pos = 4;
	for my $antwnr ( 'a' .. 'd' ) {
	    next if $antwnr eq $q->{ANSWIS};
	    if ( ! exists $q->{ANSW}{$antwnr} ) {
		insert_error("Antwoord $antwnr bestaat niet!");
		return;
	    }
	    $rec->[$pos++] = $q->{ANSW}{$antwnr};
	}
    }
    # insert antw in table
    my $vraagnr = @vraag;
    push @vraag, $rec;
    $T->insert(end => "$q->{QUES}\n", ['vraag', "vraag-$vraagnr"]);
    print STDERR "$q->{QUES}\n" if $opt_v;
}

# stuff to select questions
my(@antw, $juiste_antw, @curantw, $curjuiste_antw);

sub clearvraag {
    return unless $vraagnr >= 0;
    # remove antwoorden
    $T->delete("antwoord.first", "antwoord.last") if $T->tagRanges("antwoord");
    # remove current "hot" vraag
    $T->tagRemove("current", "1.0", "end") if $T->tagRanges("current");
    $vraagnr = -1;
    @antw = ();
    $juiste_antw = 0;
}

# handmatig vraag uitgekozen?
my $manual_pick;

# this is called when you click on a question
sub setcurrentvraag {
    my $index = shift;

    my @tags = $T->tagNames($index);
    # make sure we do not reset on clicking on antwoord
    return if grep { /antwoord/ } @tags;
    clearvraag();
    my($vraagnrtag) = grep { /vraag-\d+/ } @tags;
    return unless $vraagnrtag;
    my($nr) = $vraagnrtag =~ /vraag-(\d+)/;
    $manual_pick = 1;
    setcurrentvraagnr($nr);
}

sub setcurrentvraagnr {
    clearvraag();

    $vraagnr = shift;

    my $vraagend = $T->index("vraag-$vraagnr.last - 1 chars");
    $T->tagAdd('current', "vraag-$vraagnr.first", $vraagend);
    # antwoorden bepalen
    $juiste_antw = 0;
    if ( $vraag[$vraagnr][2] ) {
	# non-reorderable
	@antw = @{$vraag[$vraagnr]}[3..6];
	$juiste_antw = $vraag[$vraagnr][2];
    }
    else {
	# reorder now
	@antw = ();
	my @org = @{$vraag[$vraagnr]}[3..6];
	while ( @org ) {
	    my $pos = int(rand @org);
	    push @antw, splice(@org, $pos, 1);
	    $juiste_antw = @antw if ( $pos == 0 && !$juiste_antw );
	}
    }
    # insert antwoorden
    $T->markSet(antwinsert => $vraagend);
    for my $antw ( @antw ) {
	$T->insert(antwinsert => "\n$antw", 'antwoord');
    }
    $T->markUnset('antwinsert');
}

# Menu on top
sub setup_menu {
    my $menu = $mw->Menu(qw/-type menubar/);
    $mw->configure(qw/-background black -foreground white/, -menu => $menu);

    my $file_menu = $menu->cascade(qw/-label ~File -tearoff 0/);
    $file_menu->command(-label => '~Reload vragen', -command => 
	sub { 
	    clear_vragen();
	    read_vragen();
	    reset_buttons();
	}
    );
    $file_menu->command(-label => "Reset ~Buttons",
	-command => \&reset_buttons
    );
    $file_menu->command(-label => '~Opties', -command => \&set_options);
    $file_menu->separator;
    $file_menu->command(-label => 'Quit', -command => \&exitquiz);

    $client_menu = $menu->cascade(
	qw/-label ~Client -tearoff 0 -state disabled/);

    my $help_menu = $menu->cascade(qw/-label ~Help -tearoff 0/);
    $help_menu->command(-label => 'About', -command => \&about);
}

sub volgende_vraag {
    if ( ! $manual_pick ) {
	if ( $T->tagRanges("antwoord") ) {
	    # er is iets geselecteerd...
	    setcurrentvraag($T->index("antwoord.last + 1 lines"));
	    if ( $vraagnr == -1 ) {
		$mw->bell();
		return;
	    }
	}
	else {
	    # niets geselecteerd => reject
	    $mw->bell();
	    return;
	}
    }
    if ( $vraagnr < 0 ) {
	$mw->bell();
	return;
    }
    $curvraagnr = $vraagnr;
    @curantw = @antw;
    $curjuiste_antw = $juiste_antw;
    $manual_pick = 0;
    $show_answ = $default_show_answ if defined $default_show_answ;
    print STDERR "Sending vraag $curvraagnr\n" if $opt_v;
    sendall("VRAAG " . packargs(
	[ $vraag[$curvraagnr][0], $vraag[$curvraagnr][1] ]) );
    sendall("PREPTIME");
    preptime();
    # change buttons around
    $antw_but->configure(qw/-state normal/);
    $leeg_but->configure(qw/-state disabled/);
    $T->tagAdd('gehad',
	"vraag-$curvraagnr.first", "vraag-$curvraagnr.first lineend");
}

sub antwoord {
    my $self = shift;

    if ( ! @curantw ) {
	print STDERR "In antwoord zonder \@antw!\n" if $opt_v;
	$mw->bell();
	return;
    }
    sendall("ANTW " . packargs(\@curantw));
    if ( $answ_start_time ) {
	start_tijd($self);
    }
    else {
	$starttijd_but->configure(qw/-state normal/);
    }
    $antw_but->configure(qw/-state disabled/);
    @curantw = ();
}

sub start_tijd {
    my $self = shift;

    my $endtime = Time::HiRes::time() + $bedenktijd;
    sendall("RUNQTIME " . join(" ", $bedenktijd, $endtime));
    runqtime($self, $bedenktijd, $endtime);
    $vraag_but->configure(qw/-state disabled/);
    $leeg_but->configure(qw/-state disabled/);
    $starttijd_but->configure(qw/-state disabled/);
}

sub juiste_antwoord {
    if ( ! $curjuiste_antw ) {
	$mw->bell();
	return;
    }
    sendall("CORRECT $curjuiste_antw");
    # calculate scores
    for my $cl ( keys %client ) {
	if ( $client{$cl}{ANTW} and
	    $client{$cl}{ANTW} == $curjuiste_antw )
	{
	    $client{$cl}{SCORE}++;
	    $client{$cl}{COMM}->commcmd("SETSCORE " . $client{$cl}{SCORE});
	}
	$client{$cl}{ANTW} = '';
	$client{$cl}{cANTW} = '';
    }
    refresh_results();
    $leeg_but->configure(qw/-state normal/);
    $vraag_but->configure(qw/-state normal/);
    $juisteantw_but->configure(qw/-state disabled/);
    $curjuiste_antw = 0;
}

sub scherm_leeg {
    sendall("CLEAR");
    $leeg_but->configure(qw/-state disabled/);
    $vraag_but->configure(qw/-state normal/);
}

sub client_antw {
    my($self, $antw) = @_;

    my $id = $self->getID;
    print STDERR "Client $id geeft antwoord $antw\n" if $opt_v;
    $client{$id}{ANTW} = $antw;
    $client{$id}{cANTW} = chr(96+$antw);
    refresh_results() if $show_answ;

    "OK";
}

sub about {
    my $d = $mw->DialogBox(-title => "About",
	-buttons => [qw/OK Copying Warranty/]);
    $d->add( Label => -text => <<ABOUT )->pack();
Quizmaster version $VERSION
Copyright (C) 2000 Jan-Pieter Cornet <johnpc\@xs4all.nl>

This quiz application comes with ABSOLUTELY NO WARRANTY;
for details click "Warranty" below.

This is free software, and you are welcome to redistribute it under
certain conditions; click "Copying" below for details.
ABOUT
    my $answ = $d->Show;
    if ( $answ eq "Copying" ) {
	show_text(COPYING => $COPYING);
    }
    elsif ( $answ eq "Warranty" ) {
	show_text(WARRANTY => $WARRANTY);
    }
}

sub show_text {
    my($title, $txt) = @_;

    my $d = $mw->DialogBox(-title => $title,
	-buttons => ["OK"]);
    my $t = $d->add( Scrolled => ROText =>
	qw/-relief flat -scrollbars oe/
    )->pack();
    $t->insert('end', $txt);
    $d->Show;
}

my $listen;

my $status_to;

sub set_status {
    $status = shift;
    $status_to->cancel() if $status_to;
    $status_to = $mw->after(STATUSTIMEOUT,
	sub { $status = ""; undef $status_to });
}

my $udpsock;

sub setup_socket {
    $listen = QuizRPC->server($mw, $opt_p, \&new_connection, \%remote_cmd)
	or die "Cannot create server socket: $!\n";
    $udpsock = IO::Socket::INET->new(qw/Proto udp/, LocalPort => $opt_p)
	or die "Cannot create udp socket: $!\n";
    setsockopt($udpsock, SOL_SOCKET, SO_BROADCAST, 1)
	or die "Cannot turn on broadcast flag: $!\n";
    QuizRPC::make_nonblocking($udpsock);
    $mw->fileevent($udpsock, readable => \&udp_identify);
    set_status('Listening on ' . $listen->getID());
}

sub udp_identify {
    my $buf;
    my $addr = recv($udpsock, $buf, 8192, 0);
    print STDERR "In udp_identify\n" if $opt_v;
    send($udpsock, "Quizmaster/$VERSION #" . scalar @vraag, 0, $addr);
    print STDERR "Sent udp reply\n" if $opt_v;
    my($port, $inet) = sockaddr_in($addr);
    set_status('UDP query from ' . inet_ntoa($inet) . ":$port");
}

sub connection_allowed {
    my $ip = shift;

    for my $allow ( @allowed_ip ) {
	return 1 if $ip =~ /$allow/;
    }
    set_status("Rejected connection from $ip");
    return 0;
}

sub new_connection {
    my($self, $id) = @_;

    # determine if $id is allowed to connect
    return unless connection_allowed($id);
    if ( ! keys %client ) {
	# no clients yet. enable client menu
	$client_menu->configure(qw/-state normal/);
    }
    set_status("Connection from $id");
    $client{$id}{COMM} = $self;
    $client{$id}{STATE} = 'connect';
    my $thismenu = $client_menu->cascade(-label => $id, -tearoff => 0);
    $thismenu->command(-label => "Set ~Name", -command =>
	[ \&set_client_name, $self, $id ]);
    $thismenu->command(-label => "Set ~Type", -command =>
	[ \&set_client_type, $self, $id ]);
    $thismenu->separator;
    $thismenu->command(-label => "~Kick", -command =>
	[ \&kick_client, $self, $id ]);
    print STDERR "In new_connection $id\n" if $opt_v;
    $self->commcmd("HELO Quizmaster $VERSION",
	[ \&client_in, $self, $id ]);

    return [ \&dead_client, $self, $id ];
}

sub client_in {
    my($self, $id, $cmd) = @_;

    $cmd eq "HELO" or
	return $self->dead_comm("Client insufficiently polite");
    $client{$id}{STATE} = 'ok';
}

sub kick_client {
    my($self, $id) = @_;

    if ( $client{$id}{STATE} eq "connect" || $client{$id}{STATE} eq "quit" ) {
	return $client{$id}{COMM}->dead_comm("*KICK*");
    }
    print STDERR "Giving client $id the boot\n" if $opt_v;
    $self->commcmd("QUIT");
    $client{$id}{STATE} = "quit";
}


sub client_name {
    my($self, $naam) = @_;

    my $id = $self->getID;
    print STDERR "Client $id heet $naam\n" if $opt_v;
    set_status("Client $id heet $naam");
    $client{$id}{NAAM} = $naam;
    refresh_results();
    "OK";
}

sub set_client_name {
    my($self, $id) = @_;

    my $naam = $client{$id}{NAAM};
    my $d = $mw->DialogBox(-title => "Zet de naam van client $id",
	-buttons => [qw/OK Cancel/]);
    $d->add(Label => -text => "Zet de naam van client $id")->pack();
    $d->add(LabEntry => -textvariable => \$naam, -width => 15,
	-label => "Naam:", -labelPack => [ -side => 'left'])->pack();
    my $answ = $d->Show;
    if ( $answ ne "OK" ) {
	print STDERR "DialogBox $answ\n" if $opt_v;
	return;
    }
    $client{$id}{NAAM} = substr($naam, 0, 15);
    $client{$id}{COMM}->commcmd("SETNAME $client{$id}{NAAM}");
    refresh_results();
}

# allow setting of:
# - $bedenktijd
# - default antwoorden_projecteren ($default_show_answ)
# - tijd start gelijk met antwoorden ($answ_start_time)
sub set_options {
    my($lbedenktijd, $lansw_start_time, $ldefault_show_answ);
    $lansw_start_time = $answ_start_time || 0;
    $ldefault_show_answ = defined $default_show_answ ?
	$default_show_answ : "undef";
    $lbedenktijd = $bedenktijd;

    my $d = $mw->DialogBox(-title => "Zet opties",
	-buttons => [qw/OK Cancel/]);
    $d->add(Label => -text => "Zet opties")->pack();
    $d->add(LabEntry =>
	-textvariable => \$lbedenktijd,
	qw/-width 5 -label Bedenktijd:/,
	-labelPack => [ -side => "left" ])->pack();
    $d->add(Checkbutton =>
	-variable => \$lansw_start_time,
	-text => "Knop `antwoord' start ook tijd",
	-selectcolor => XS_YELLOW,
    )->pack(qw/-side left/);
    $d->add(Radiobutton =>
	-variable => \$ldefault_show_answ,
	-value => "undef",
	-selectcolor => XS_YELLOW,
	-text => "Laat antwoord_projecteren staan",
    )->pack(qw/-side top/);
    $d->add(Radiobutton =>
	-variable => \$ldefault_show_answ,
	-value => 0,
	-selectcolor => XS_YELLOW,
	-text => "Zet antwoord_projecteren uit",
    )->pack(qw/-side top/);
    $d->add(Radiobutton =>
	-variable => \$ldefault_show_answ,
	-value => 1,
	-selectcolor => XS_YELLOW,
	-text => "Zet antwoord_projecteren aan",
    )->pack(qw/-side top/);
    my $answ = $d->Show;
    if ( $answ ne "OK" ) {
	print STDERR "DialogBox $answ\n" if $opt_v;
	return;
    }
    $bedenktijd = $lbedenktijd if $lbedenktijd =~ /^[.\d]+$/;
    $answ_start_time = $lansw_start_time;
    if ( $ldefault_show_answ eq "undef" ) {
	undef $default_show_answ;
    }
    else {
	$default_show_answ = $ldefault_show_answ;
    }
}

sub set_client_type {
    my($self, $id) = @_;

    my $naam = $client{$id}{NAAM} || $id;
    my $lscore = $client{$id}{SCORE} || 0;
    my $d = $mw->DialogBox(-title => "Zet type van client $naam",
	-buttons => [qw/OK Cancel/]);
    $d->add(Label => -text => "Zet type van client $naam")->pack(qw/-side top/);
    my $pos = $client{$id}{POS} || "Niet";
    # frame for radiobuttons
    my $left_fr = $d->add('Frame')
	->pack(qw/-side left -fill y/);
    # insert Label
    $left_fr->Label(-text => "Positie op display")->pack(qw/-side top/);
    for my $but ( "Niet", 1 .. MAXCONTESTANTS ) {
	my $state = "normal";
	if ( $but =~ /\d/ && $results[$but - 1] && $but ne $pos ) {
	    $state = "disabled";
	}
	$left_fr->Radiobutton(qw/-justify left/,
	    -selectcolor => XS_YELLOW,
	    -state => $state,
	    -text => $but,
	    -value => $but,
	    -variable => \$pos,
	)->pack(qw/-side top/);
    }
    my $isproj = $client{$id}{ISPROJ};
    # checkbutton project scores yes/no
    $d->add(Checkbutton =>
	-text => "Resultaten en scores\nweergeven (projector)",
	-selectcolor => XS_YELLOW,
	-variable => \$isproj,
    )->pack(qw/-side top/);
    $d->add(LabEntry =>
	-textvariable => \$lscore,
	qw/-width 5 -label Score:/,
	-labelPack => [ -side => 'left' ])->pack(qw/-side top/);
    my $answ = $d->Show;
    if ( $answ ne "OK" ) {
	print STDERR "DialogBox $answ\n" if $opt_v;
	return;
    }
    $client{$id}{ISPROJ} = $isproj;
    if ( $lscore =~ /^\d+$/ ) {
	$client{$id}{SCORE} = $lscore;
	$client{$id}{COMM}->commcmd("SETSCORE $lscore");
    }
    if ( ! $isproj ) {
	$client{$id}{COMM}->commcmd("NORESULT");
    }
    if ( ($client{$id}{POS}||"") ne $pos ) {
	# pos changed
	if ( $client{$id}{POS} ) {
	    # remove old position
	    $results[$client{$id}{POS} - 1] = undef;
	    if ( $pos eq "Niet" ) {
		# remove info frame on client
		$client{$id}{COMM}->commcmd("NOINFO");
		# and remove frame on local machine
		if ( $client{$id}{RESFRAME} ) {
		    remove_local_result($id);
		}
	    }
	}
	if ( $pos ne "Niet" ) {
	    # if position is new, enable info window
	    if ( !defined $client{$id}{POS} ) {
		$client{$id}{COMM}->commcmd("SHOWINFO");
	    }
	    # enable result frame on local machine
	    $client{$id}{POS} = $pos;
	    $results[$pos - 1] = $id;
	    make_local_result($id) if ! $client{$id}{RESFRAME};
	}
	else {
	    $client{$id}{POS} = undef;
	}
    }
    refresh_results();
}

# make a local frame for displaying results
sub make_local_result {
    my $id = shift;

    my $pos = $client{$id}{POS};
    $client{$id}{SCORE} ||= 0;
    $client{$id}{RESFRAME} = $results_frame->Frame(
	qw/-relief ridge -background black -borderwidth 2/
    )->grid(qw/-row 0 -sticky nsew/, -column => $pos - 1);
    $results_frame->gridColumnconfigure($pos - 1, qw/-weight 1/);
    $client{$id}{RESFRAME}->Label(
	qw/-foreground white -background black -takefocus 0
	   -font C_results/,
	-textvariable => \$client{$id}{NAAM}
    )->pack(qw/-side top -expand 1/);
    $client{$id}{RESFRAME}->Label(
	qw/-foreground white -background black -takefocus 0
	   -font C_results/,
	-textvariable => \$client{$id}{SCORE},
    )->pack(qw/-side left -expand 1/);
    $client{$id}{RESFRAME}->Label(
	qw/-background black -takefocus 0 -font C_results/,
        -textvariable => \$client{$id}{cANTW},
        -foreground => XS_YELLOW,
    )->pack(qw/-side right -expand 1/);
}

sub remove_local_result {
    my $id = shift;

    $client{$id}{RESFRAME}->gridForget;
    delete $client{$id}{RESFRAME};
}

# send projected results to all clients asking for such
sub refresh_results {
    # search project clients
    my @projectcl = grep { $client{$_}{ISPROJ} } keys %client;
    return unless @projectcl;
    for (my $idx = 0; $idx < @results; $idx++) {
	my $id = $results[$idx];
	next unless $id;
	if ( ! exists $client{$id} ) {
	    $results[$idx] = undef;
	    next;
	}
	my $clref = $client{$id};
	my $args = packargs( [
	    $idx,
	    $clref->{NAAM} || substr($id, -15, 15),
	    $clref->{SCORE} || 0,
	    $show_answ ? $clref->{cANTW} || "" : ""
	] );
	for my $cl ( @projectcl ) {
	    $client{$cl}{COMM}->commcmd("SETRESULT $args");
	}
    }
}

my $exitafterlastclient;

sub dead_client {
    my($self, $id, $reason) = @_;

    my $dorefresh;
    my $err = "Error from client $id: $reason";
    set_status($err);
    print STDERR "$err\n";
    my $realmenu = $client_menu->cget('-menu');
    my $itemnr = $realmenu->index($id);
    if ( ! defined $itemnr ) {
	warn "Cannot find menu item $id\n";
	return;
    }
    print STDERR "Deleting item $itemnr from client_menu\n" if $opt_v;
    $realmenu->delete($itemnr);
    # delete client from results if necessary
    if ( $client{$id}{POS} ) {
	$results[$client{$id}{POS} - 1] = undef;
	remove_local_result($id);
	$dorefresh++;
    }
    delete $client{$id};
    if ( ! keys %client ) {
	# no more clients left, disable Client menu
	$client_menu->configure(qw/-state disabled/);
	exit if $exitafterlastclient;
    }
    refresh_results() if $dorefresh;
}

sub sendall {
    my $cmd = shift;
    my $cb = shift;

    for my $id ( keys %client ) {
	$client{$id}{COMM}->commcmd($cmd,
	    $cb ? [ $cb, $client{$id}{COMM}, $id ] : undef);
    }
}


my $beenhere;

sub exitquiz {
    exit if $beenhere++;
    exit if ! keys %client;
    $exitafterlastclient = 1;
    sendall("QUIT");
}
