#!/usr/bin/perl

$current_dir = `pwd`;
chop($current_dir);
chdir $current_dir or die "can not change directory!!";;

$in_file = "$ARGV[0]".".html";
$out_file = "$ARGV[0]".".php";

open(IN,"<$in_file") or die "open:$in_file  $!";
open(OUT,">$out_file") or die "open:$out_file  $!";

$nl=1;
$div=0;
while(<IN>){
    chomp;

    if($nl==1 && /^$/){
	$nl++;
	next;
    }
    
    #----- 先頭行の処理 -----
    if(/<table class="side_main" cellspacing="0">/){
	print OUT '<?php',"\n";
	print OUT 'mb_http_output("EUC_JP");',"\n";
	print OUT 'mb_internal_encoding("EUC_JP");',"\n";
	print OUT "\n";
	print OUT 'printf("<table class=\"side_main\" cellspacing=\"0\">\n");',"\n";
	$nl++;
	next;
    }

    #----- <div>の行の処理 -----
    if(/\s*<div.*/){
	$div=1;
	$_=&trim($_);
	printf OUT "printf(\'$_";
	if(/.+<\/div>/){
	    printf OUT "');"."\n";
	    $div=0;
	}
	next;
    }

    if(/.+<\/div>/){
	$_=&trim($_);
	printf OUT "$_');"."\n";
	$div=0;
	next;
    }

    #----- #ifの行の処理 -----
    if(/\s*<!--\#if expr*/){
	@oneline = split(/[\s+\t+\"+=+]/,$_);
	foreach(@oneline){
	    if(/\$\w+/){
		printf OUT "if($_){\n";
	    }
	}
	next;
    }

    #----- #elseの行の処理 -----
    if(/\s*<!--\s*\#else\s*/){
	printf OUT '}else{'."\n";
	next;
    }

    #----- #endifの行の処理 -----
    if(/\s*<!--\s*\#endif\s*/){
	printf OUT '}'."\n";
	next;
    }

    #----- コメント行の処理 -----
    if(/<!--.*-->/){
	$_=&trim($_);
	printf OUT "// $_";
	next;
    }

    #----- その他のhtmlの行の処理 -----
    if(/\s*<\w*.*>/ && $div==0){
	$_=&trim($_);
	printf OUT "printf('$_');\n";
	next;
    }
    
    #----- どれにもマッチしなかった場合 ------
    $_=&trim($_);
    if($div==0){
	printf OUT "$_\n";
    }else{
	printf OUT "$_";
    }
    $nl++;
}

close IN;
close OUT;

exit;

sub trim{
    my $val = $_[0];
    $val =~ s/^\s*(.*?)\s*$/$1/;
    return $val;
}
