#!%PerlPath%
################################################################
# tdf2html.pl

use strict;
use lib qw(. %LibDir%);

use Getopt::Std;

use JConv;
use CGI::QueryString;
use CGI::Tools;
use JConv;

use TDS;
use TDS::System;
use TDS::Tdf::Parser;
use TDS::Tdf::Command;
use TDS::Renderer;
use TDS::Collection;
use TDS::AccessLog;
use TDS::Cache;
use TDS::Cookie;
use TDS::Mode;

#eval 'require q(conf.ph)';
#TDS::Initialize();

$TDS::AccessLog::EnableAccessLog = 0;
$TDS::Cookie::EnableCookie = 0;
$TDS::Cache::EnableCache = 0;
$TDS::Collection::AutoReplace = 1;
&TDS::Mode::SetMode('static');
$TDS::Tdf::Parser::ContinueLineByEscape = 1;

################################################################
my $is_cgi = $ENV{'REQUEST_URI'} ne '';

if ($is_cgi){
    SetDieHandler;
    print "content-type: text/html\n\n";
    my $file = param('file');
    die "permit only under diary_dir"
	if $file !~ m!^[A-Za-z0-9]! ||
	    $file =~ /\.\./;
    @ARGV = "$TDS::DirInfo::DiaryDir/$file";
}
	
my %opt;
getopts("s:t:", \%opt);

require "$opt{t}"
    if $opt{t};

my $parser = new TDS::Tdf::Parser;
my $title;

*jconv_tmp = mkjconv('auto', 'euc');

for (@ARGV){
#    die "permit only tdf file"
#	unless /\.tdf$/;
    open(F, $_) || die $_;
    while (<F>){
	jconv_tmp(\$_);
	$parser->Parse($_);
    }
    close F;
}
# print
#print STDERR "parse done.\n";

my $rend = new TDS::Renderer;
if ($opt{'s'}){
    $rend->filename($opt{'s'});
    $rend->Read;
} else {
    $rend->skelton(qq(<!--\#macro cmd="CONTENT" -->));
}

my $col = new TDS::Collection;
push(@{$col->diarys}, $parser);
print $rend->AsHTML($col);
