#!/usr/bin/perl
use CGI;
use CGI::Carp qw(fatalsToBrowser);
my $query = new CGI;
my %input = map { $_ => $query->param($_) } $query->param;
my $sub2go   = $input{state} || "default";
print "Content-Type: text/html\n\n\n";

eval {
  # now do the real work
  &$sub2go;
};
if ($@) {
  print $@;
}

sub default {
  print qq(
<html>
 <body bgcolor="#ffffff">
  <h3>Upload file</h3>
  <form name=upload action="$me" method="post" enctype="multipart/form-data" >
   <input type=hidden name=state value="upload">
   <input type=file name=file size=40>
   <br>
   <input type=submit name=submit value="upload this file">
  </form>
  <p><a href=".">back</a></p>
 </body>
</html>
  );
}

sub upload {
    my $fh = $input{file};
    $input{file} =~ s(^.:.*\\)(); # remove windows path, if any
    open FILE, "> $input{file}" or die "Could not create/overwrite $input{file} $!\n";
    binmode FILE;
    my $bytesread;
    while ($bytesread=read($fh,$buffer,1024)) {
        print FILE $buffer;
    }

    close FILE;

    print qq(
<html>
 <body bgcolor="#ffffff">
  <p>upload of $fh complete.</p>
  <p><a href=".">back</a></p>
 </body>
</html>
    );
}
