#!/opt/iphone/bin/perl
print "Content-type: text/html\n\n";  
%data = &read_data();		      

$header = "<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\"></head><body bgcolor=\"#FFFFFF\"><center><h1><br><br>순간의 기억...</h1><br>";
$footer = "<hr><p><p><p><h1><a href=\"http://127.0.0.1/cgi-bin/readmemo.cgi\"><b>저장된 메모보기</b></a></center>
</h1></body></html>";

$name =$data{"Name"};
$text =$data{"Text"};
$text =~ s/</&lt;/g;
$text =~ s/>/&gt;/g;
$date = &read_date();

&write_memofile;

print "$header <p><h2>저장되었습니다. *^^*</h2><p> $footer";

sub write_memofile {

  undef $/;
  open(FILE, "memofile.html");
     $memofile_contents = <FILE>;
  close(FILE);
  $/ = "\n";

  $text = "\n\n<b>\* $name \* </b> $date<p>\n<h2>$text</h2>\*\^\^\*<p>\n";

if($memofile_contents !~ /$header/){
   $memofile_contents = "$header\n$memofile_contents";
   }
if($memofile_contents !~ /$footer/){
   $memofile_contents = "$memofile_contents\n$footer";
   }

  $memofile_contents =~ s/$header/$header$text/g;

  open (FILE, ">memofile.html");
    print FILE "$memofile_contents";
  close(FILE);
}


sub read_date {

   @days = ('일','월','화','수','목','금','토');
   @months = ('1월','2월','3월','4월','5월','6월','7월',
              '8월','9월','10월','11월','12월');

   ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
   if ($hour < 10) { $hour = "0$hour"; }
   if ($min < 10) { $min = "0$min"; }
   if ($sec < 10) { $sec = "0$sec"; }
   $year = 1900 + $year;

   $date = "$months[$mon] $mday일($days[$wday],$year) $hour\:$min";
   $date;
}

sub read_data {
    local($string);
    if ($ENV{'REQUEST_METHOD'} eq 'GET') {
        $_ = $string = $ENV{'QUERY_STRING'};
	tr/\"~;/_/;
	$string = $_;
    }				
    else { read(STDIN, $string, $ENV{'CONTENT_LENGTH'});
        $_ = $string;
	$OK_CHARS='a-zA-Z0-9=&%\n\/_\-\.@';
	tr/\"~;/_/;
	$string = $_;
	   }
    @data = split(/&/, $string);
    foreach (@data) {
	split(/=/, $_);
	$_[0] =~ s/\+/ /g;
	$_[0] =~ s/%(..)/pack("c", hex($1))/ge;
	$data{"$_[0]"} = $_[1];
    }
    foreach (keys %data) {
	$data{"$_"} =~ s/\+/ /g;
	$data{"$_"} =~ s/%(..)/pack("c", hex($1))/ge;
    }
    %data;
}