english = true;

if english == true then
	source = 'dvioute.rtf';
	index = 'dvioute.cnt';
	outputdir = 'htmle';
else
	source = 'dviout.rtf';
	index = 'dviout.cnt';
	outputdir = 'html';
end
hhc = 'dviout.hhc';


#line = '{\ul プロパティーシート}{\v IDH_JPROPERTY}({\ul Property Sheets}{\v IDH_PPSHEETS})\line';
#line.gsub!(/(\{[^{}]*\})\{\\v ([A-Z0-9_]*)\}/,'<a href="\2.html">\1</a>');
#puts line
#while line.gsub!(/\{\\([a-z0-9]*)([\\ <][^{}]*)\}/,'<span class="\1">{\2}</span>') do
#	puts line;
#end;
#while line.gsub!(/(<span.*>)\{(.*)\}(<\/span>)/,'\1\2\3') do
#	puts line
#end
#puts line;
#exit(0);


HEAD=<<EOF
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ja">
<head>
<meta HTTP-EQUIV="Content-type" CONTENT="text/html; charset=Shift_JIS">
<meta http-equiv="Content-script-type" content="text/javascript">
<meta http-equiv="Content-style-type" content="text/css">
<link rel="contents" href="./index.html">
<title><%= title %></title>
<link rel=stylesheet type="text/css" href="./css/main.css">
</head>
<body>
EOF

FOOT=<<EOF
</body>
</html>
EOF


HHCHEAD=<<EOF
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<HTML>
<HEAD>
</HEAD><BODY>
<OBJECT type="text/site properties">
	<param name="ImageType" value="Folder">
</OBJECT>
EOF

HHCFOOT=<<EOF
</BODY></HTML>
EOF


$KCODE='sjis';

require 'fileutils';
require 'pathname';
require 'erb';


FileUtils.makedirs(outputdir);


c = (IO.read(source).gsub(/&/,'&amp;')).gsub(/</,'&lt;').gsub(/>/,'&gt;').split('\par\page');
contents = {};
footnotes = {};

c.each{|l|
	/^[^\n]*\{\\footnote ([A-Z0-9_]*)\}/ =~ l;
	file = $1;
	if $1 == nil then
#		puts l;
#		puts "\n\n";
	else
		l.scan(/\{\\footnote ([^{}]*)\}/).each{|f|
#			p "#{f}, #{file}";
			footnotes[f] = file;
		}
		contents[file] = {'body'=>l, 'footnote'=>true};
	end
}

# .cntから目次生成
m = (IO.read(index).gsub(/&/,'&amp;')).gsub(/</,'&lt;').gsub(/>/,'&gt;').split("\n");
m.uniq!();
level = 0;
doc = "";
m.each{|l|
	wfile = (/^([0-9]) (.*?)=(.*)$/ =~ l);
	if wfile then lstr = $1;title = $2;file = $3; end
	if wfile == nil then
		nofile = (/^([0-9]) (.*?)$/ =~ l);
		if nofile then lstr = $1;title = $2;file = ""; end
	end
	if wfile or nofile then
		file.upcase!();# 何故小文字があるのだろう？
		if lstr.to_i() > level then
			doc = doc + ("<ul>\n" * (lstr.to_i() - level));
		elsif lstr.to_i() < level then
			doc = doc + ("</ul>\n" * (level - lstr.to_i()));
		end
		level = $1.to_i();
		if (contents.key?(file) == true) or (nofile) then
			if nofile == nil then contents[file]['footnote'] = false; end;
			if wfile then
				doc = doc + "<li><object type=\"text/sitemap\"><param name=\"Name\" value=\"#{title}\"><param name=\"Local\" value=\"#{file}.html\"></object>\n";
			else
				doc = doc + "<li><object type=\"text/sitemap\"><param name=\"Name\" value=\"#{title}\"><param name=\"ImageNumber\" value=\"1\"></object>\n";
			end
		else
			puts ".cnt内のトピック「#{title}」は実体がない気がする．";
		end
	end
}
doc.gsub!(/^([^\n]*)<param name="ImageNumber([^\n]*)\n\1<param name="Local([^\n]*)<\/object>$/m,'\1<param name="Local\3<param name="ImageNumber" value="1"></object>');

doc = HHCHEAD + doc + HHCFOOT;
File.open(Pathname(outputdir) + hhc,"w"){|fp|fp.puts(doc);}



contents.each_key{|file|
#	p file + "を処理中．"
	/\\b\\cf2 (.*?) \\plain\\fs20/ =~ contents[file]['body'];
	title = $1;
	contents[file]['body'].sub!(/\\b\\cf2 (.*?) \\plain\\fs20/,'<h1>\1</h1>');
# いくつか一時的に変換しておく：\plain→>><<>><<，\\→<<>><<>>，\{→<<<<>>>>，\}→>>>><<<<
	contents[file]['body'].gsub!(/\\plain/,'>><<>><<');
	contents[file]['body'].gsub!(/\\\\/,'<<>><<>>');
	contents[file]['body'].gsub!(/\\\{/,'<<<<>>>>');
	contents[file]['body'].gsub!(/\\\}/,'>>>><<<<');

# \par, \pardを削除してみる
	contents[file]['body'].gsub!(/\\pard?/,"");
# \keepnを削除してみる
	contents[file]['body'].gsub!(/\\keepn/,"");
# footnoteを削除してみる
	contents[file]['body'].gsub!(/.\{\\footnote [^{}]*\}/,"");
	contents[file]['body'].gsub!(/(\{[^{}]*\})\{\\v ([A-Z0-9_]*)\}/,'<a href="\2.html">\1</a>');
# \slN（行間スペース指定？）,\fsN（フォントサイズ指定）を削除してみる
	contents[file]['body'].gsub!(/\\(fs|sl)[0-9]+/,"");

	contents[file]['body'].gsub!(/\\line/,'<br>');

	while contents[file]['body'].gsub!(/\{\\([a-z0-9]*)([\\ <][^{}]*)\}/,'<span class="\1">{\2}</span>') do end;
#	while contents[file]['body'].gsub!(/(<span.*>)\{ ?(.*)\}(<\/span>)/,'\1\2\3') do end;
	contents[file]['body'].gsub!(/[\{\}]/,'');
	while contents[file]['body'].gsub!(/\\([a-z0-9]*) ?(.*?>><<>><<)/,'<span class="\1">\2</span>') do end;
	while contents[file]['body'].gsub!(/\\([a-z0-9]*)(.*?)$/,'<span class="\1">\2</span>') do end;

#	footnotes.each_key{|footnote|
#		p "footnote = #{footnote}, file = #{file}";
#		contents[file]['body'].gsub!(/#{footnote}/,'<a href="#{footnotes[footnote]}">#{footnote}</a>');
#	}

# \plainを削除してみる
	contents[file]['body'].gsub!(/>><<>><</,"");
# \\，\{，\}を戻す
	contents[file]['body'].gsub!(/<<>><<>>/,'\\');
	contents[file]['body'].gsub!(/<<<<>>>>/,'{');
	contents[file]['body'].gsub!(/>>>><<<</,'}');
	
# タグ開始直後/タグ終了直前の空白を消す．
	while contents[file]['body'].gsub!(/(<[^\/][^>]*>) /,'\1') do end;
	while contents[file]['body'].gsub!(/ <\//,'</') do end;
# スペースは&nbsp;に
#	while contents[file]['body'].gsub!(/^(([^<]*<[^>]*>)*)([^<]*) /,'\1\2&nbsp;') do end;
# 遅いので次で代用．大丈夫かは知らない．
	while contents[file]['body'].gsub!(/^(<[^>]*>)([^<]*) /,'\1\2&nbsp;') do end;
	while contents[file]['body'].gsub!(/^([^<]*) /,'\1&nbsp;') do end;
	
	File.open(Pathname(outputdir) + (file + '.html'),"w"){|fp|
		erb = ERB.new(HEAD);
		doc = erb.result(binding);
		doc = doc + contents[file]['body'];
		erb = ERB.new(FOOT);
		doc = doc + erb.result(binding);
		fp.puts(doc);
	}
}


