
use Carp;
#sub CgiDie {
#  local (@msg) = @_;
#  &CgiError (@msg);
#  confess @msg;
#}

sub DEBUG {0;}

sub dprintuser
{
    my ($sock, $user) = @_;

    my $id = get_reviewer_id( $sock, $user );
    my $name = get_reviewer_name( $sock, $id );
    
    print "<p><span style='background-color:#DDFFDD'>user: $user ($id/$name)\n";
    print "admin: " . ( is_admin( $sock, $user ) ? 'yes' : 'no' );
    print "\neditor: " . ( is_editor( $sock, $user ) ? 'yes' : 'no' );
    print "</span>\n";
}


sub dprintsql
{
    print "<pre style='background-color:#DDFFDD'><b>$_[0]</b>\n$_[1]\n</pre>"; 
}

sub dprinthash
{
    my $h = shift;
    print "<p><span style='background-color:#DDFFDD'>";
    foreach my $k ( keys( %{$h} ) ) {
        print "$k: ";
        ref( $h->{$k} ) =~ /ARRAY/ and do {
            dprintarrayshort($h->{$k});
            next;
        };
                
        print "$h->{$k}\n";
    }
    print "</span>";
}

sub dprintarrayshort
{
    my $a = shift;
    my $t = '[';
    foreach my $k ( @{$a} ) {
        print "$t$k";
        $t = '|';
    }
    print "]\n";
}

sub report_error
{
    my $iserror  = shift;

    open SENDMAIL, "|sendmail vecerka\@cmp.felk.cvut.cz" and do
    {
        print SENDMAIL "subject:ECCV software " . 
            ( $iserror ? "error\n" : "warning\n" );
        my ($s,$m,$h,$D,$M,$Y) = localtime(time);
        
        print SENDMAIL "generated $Y-$M-$D $h:$m:$s\n";
        print SENDMAIL "\n";
        print SENDMAIL @_;

        print SENDMAIL "-- input ---------------------------\n";
        foreach my $key (sort keys(%input)) {
            print SENDMAIL "$key: $input{$key}\n";
        }

        print SENDMAIL "-- ENV -----------------------------\n";
        foreach my $key (sort keys(%ENV)) {
            print SENDMAIL "$key: $ENV{$key}\n";
        }
        print SENDMAIL "\n";
        close SENDMAIL;
    };

    if( $iserror )
    {
        print "<p>The error report has been automatically sent to the
    administrator. The error will be fixed as soon as possible.";
    }
}

sub stack_trace
{
    my $t = '';
    my $i = 0;
    my ($p, $f, $l, $s);

    while( my ($p, $f, $l, $s) = caller( $i ) )
    {
        $t = "[$i] $s at $f:$l\n$t";
        ++ $i;
    }
    $t;
}


BEGIN
{
    $SIG{'__WARN__'} = sub { 

        if( DEBUG() ) {
            $cgi_lib::headerout or 
                print "content-type:text/html\n\n";
            print "<h1 style=\"color:red\">Internal warning</h1>\n";
            print "<pre>", stack_trace(), @_, "</pre>"; 
        }
        else
        { report_error( 0, stack_trace(), @_ ); }
    };

   $SIG{'__DIE__'} = sub { 
       $cgi_lib::headerout or 
           print "content-type:text/html\n\n";
       print "<h1 style=\"color:red\">Internal error</h1>\n";

       if( DEBUG() ) { print "<pre>", stack_trace(), @_, "</pre>"; }
       else { report_error( 1, stack_trace(), @_ ); }
       exit;
   };
}

1;
