#!/usr/bin/perl -s
# Author : Volodymyr M. Lisivka <lvm_ukr@yahoo.com>
# License: GNU General Pubic License
# Version: 0.2.0

if($h || $help)
{
 print "Usage: yank2html [-h] [-s] [-f=filename] [file1]...\n";
 print "\nOptions:\n";
 print "  -h   This message.\n";
 print "  -s   Split output. Print one file to STDOUT and second to STDERR.\n";
 print "  -f   Name of second file for linking (\"texts.html\").\n";
 print "\nExamples:\n";
 print " yank2html <in.xml >out.html\n";
 print " yank2html in.xml >out.html\n";
 print " yank2html -s in.xml >out.html 2>texts.html\n";
 print " yank2html -s -f=blabla.html in.xml >out.html 2>blabla.html\n";
 exit 0;
}

my $textBlocksCounter=1;
$f="texts.html" if(!$f);

print <<HTML_END;
<html>
 <head>
 <title>Yank2HTML output</title>
 </head>
<body>
<form>
HTML_END
if($s)
{
print STDERR <<HTML_END;
<html>
 <head>
 <title>Yank2HTML output</title>
 </head>
<body>
HTML_END
}
while(<>){
 s/\&\#([0-9]*);/pack("C",$1)/ge;
 if(/<Node/){
  print "<ul><li>\n";
  
  if(/Type="TodoNote"/){
    /Todo="([01])"/ && print "<input type='checkbox' ".(($1==1)?"checked":"").">\n";
#    /Priority="([0-9]*)"/ && print "Priority: $1\n";
#    /Deadline="(.*?)"/ && print "Deadline: $1\n";
#    /Complete="([0-9]*)"/ && print "Complete: [ $1% ]\n";
    /Complete="([0-9]*)"/ && $1!=0 && print "[ $1% ]\n";
  }elsif(/Type="CheckNote"/){
    /Todo="([01])"/ && print "<input type='checkbox' ".(($1==1)?"checked":"").">\n";
  }else{ #TextNote
  }
 } 
 /<Title>(.*?)<\/Title>/ && print "<b>$1</b>\n";
 
 if(/<Text>/ && !(/<Text><\/Text>/)){
  if($s)
  {
   print "<a href=\"$f#$textBlocksCounter\">[$textBlocksCounter]</a>";
   print STDERR "<a name=\"$textBlocksCounter\"><b>$textBlocksCounter</b></a><pre>\n";
   $textBlocksCounter++;
  }else
  {
   print "<br><pre>\n";
  }
  my $text=$_;
  while(!(/<\/Text>/)){
   $_=<>;
   $text.=$_;
  };
  
  $text=~/<Text>(.*)<\/Text>/s;
  
  if($s)
  {
   print STDERR "$1</pre><hr>\n";
  }else
  {
   print "$1</pre>\n";
  }
 }
 
 /<\/Node>/ && print "</ul>\n";
}
 
print <<HTML_END;
</form>
</body>
</html>
HTML_END

if($s)
{
print STDERR <<HTML_END;
</body>
</html>
HTML_END
}