#! /usr/bin/ruby -Ks
$KCODE = "SJIS"
################################################################################
# 󕶌Ɍ`̃eLXgt@Cxhtml`ɐ`XNvg
# txt2html.pl Rev. 1.13ɍ쐬
#
# ̓eLXg̑O ShiftJIS (CodePage 932) sR[hCRLF (CR,LF݂̂łv)
# O̓C[Wt@CAhtmlꕶ&xxx;֕ύX
#
# Useage
#    ao2xhtml.rb ̓eLXgt@C
#    ohtmlt@C͓̓eLXgt@C.txt.xhtmlɒu
#
#	2007/08/30	Xpz{p
#		Accent̏
#		̐K\[-@-]ƁA3`4܂Ŋg
#		sjis(2004)  utfϊ sconvɐ؂ւ
#		Ŏn܂LOɑΉ
#	2007/09/06	Xpz{p
#		WinłŁA̓t@C݂ȂƂAxEBho悤
#		WinłŁAiconvǂݍ܂ȂȂ悤
#	2007/09/09	Xpz{p
#		cT|[g
#		cspanŎ悤ɕύX
#	2007/09/10	Xpz{p
#		Ԃ牺Cfg̎~XC
#		JX^X^CV[gKpATAT_rAborder-top-styleŕ\悤
#		瑾EΆ`őEΑ̏I@LɑΉ
#	2007/09/13	Xpz{p
#		Ant̊JnAĨWbNύX
#		c蒍L邽߂̃X^CV[gC		
#		c蒍L̓AϊłȂOĹȂ悤C
#
#
require "rbconfig"
$os = "Mac" if (/darwin/ =~ Config::CONFIG['build_os'])
$os = "Win" if (/mswin32/ =~ Config::CONFIG['build_os'])
require "jcode"
require 'iconv' if ($os == "Mac")
################################################################################
myRequirePath = ""
thisAppPath = ""
if (/\.app/ =~ ARGV[0])
	thisAppPath = ARGV.shift
	thisAppPath += '/'
	$standalone = true
	$config_path = thisAppPath.sub(/\/[^\/]*?\.app/, '') + 'ao2xhtml.conf'
else
	$standalone = false
	if ($Exerb)
		$config_path = ExerbRuntime.filepath.sub(ExerbRuntime.filename, '') + './ao2xhtml.conf'
	else
		$config_path = './ao2xhtml.conf'
	end # if exerb
end # if #standalone
myRequirePath = thisAppPath + "Contents/Resources/" if thisAppPath != ""
require "Win32API" if ($os == "Win")
require "#{myRequirePath}./ku2utf8table.rb"
require "#{myRequirePath}./sconv"
# 萔`
# html t@C猩O摜t@C̑Έʒuiimg ^OŎgj
GaijiDir     = %|../../../gaiji|; 
	# X^CV[g
StyleSheet = '<link rel="stylesheet" type="text/css" href="../../default.css" />'
	# W3C r^O`
RubiLeft		= '<ruby><rb>'
RubiCenter	= '</rb><rp>i</rp><rt>'
RubiRight		= '</rt><rp>j</rp></ruby>'
# K\萔`
	# s
EmptyLine 		= Regexp.new("^$")
Kunoji			= Regexp.new("^_")
DakutenKunoji	= Regexp.new("^_")
Strong			= Regexp.new("(.+)mu\1v.*?T_n")
Underline		= Regexp.new("(.+)mu\1v.*?n")

################################################################################
# O[oϐ`

section = 0
$burasageindent = false
$indent = false
$kunoji = 0
$dakutenkunoji = 0
$chuki = 0
$boten = 0
$bosen = 0
$noprint = 0
$accent = 0
$newjis = 0
	# encoding  'Shift_JIS'  'utf-8'
	# OAϊꍇ utf-8ɂKvB
$encoding = 'utf-8'
	# browser_ie true  falseB true(is IE)ƃr^ÕX^C𐶐Ȃ
$browser_ie = false
	# ie_tate true  falseB true(c)Əcp̃X^C𐶐
$ie_tate = true
$custom_stylesheet = true
	# ݒt@Cɂ $encoding ` $custom_stylesheet̏㏑
begin
	open($config_path, "r") do |config|
		while line = config.gets
			eval line
		end # while gets
	end # open 
rescue Errno::ENOENT
end # open configure Exception

$tate_open_tag = ''
$tate_close_tag = ''
$style_block = ''
$implicitclosetag = ""
$opentag = ""
$subs = Array.new
$jisage_item = "left"
$jiage_item = "right"
if (($browser_ie == true) && ($ie_tate == true))
	$jisage_item = "top"
	$jiage_item = "bottom"
end # tage
################################################################################
# Tu[``
	# enc_print?͓ك\bhANXփ\bhǉɕύX
	# (t@C̘Â)
class File
	def enc_print(str)
		if ($encoding == 'utf-8')
			self.print str.sj2utf8
		else
			self.print str
		end # if $encoding == 'utf-8'
		

=begin
		if $encoding == 'Shift_JIS'
				# ʋ_R[h\img^Oւ̕ϊ
			$subs.each do |mtch|
				str.gsub!(/ʋ_#{mtch}_/, kuten2png(mtch))
			end # each
			self.print(str)
		elsif $encoding == 'utf-8'
			sav = $KCODE
			$KCODE = 'u'
			begin
				str = str.sj2utf8
#				str = Iconv.conv('UTF-8', 'SJIS', str)
			rescue
STDERR.printf("error Iconv error raised\n")
			ensure
					# unicode̖ߍ݂͂ōsB
					# ʋ_R[h̊Yւ̕ϊ
				$subs.each do |mtch, rep|
					match = "ʋ_#{mtch}_".sj2utf8
					str.gsub!(/#{match}/, "\\1#{rep}")
				end # each
				self.print(str)
				$subs = Array.new
			end
			$KCODE = sav
		end # if# encoding
=end
	end # def

	def enc_printf(fmt, *param)
		if $encoding == 'Shift_JIS'
			self.printf(fmt, *param)
		elsif $encoding == 'utf-8'
			str = sprintf(fmt, *param)
			sav = $KCODE
			$KCODE = 'u'
			begin
				str = str.sj2utf8
			rescue
			ensure
				self.print(str)
			end
			$KCODE = sav
		end # if# encoding
	end # def
end # class File

def output(li, stream)
	if ($noprint == 1)
	elsif ($burasageindent)
		if (EmptyLine =~ li)
			stream.enc_print "<br />\n"
		else
#			stream.enc_print sprintf("%s%s%s\n", $opentag, li, "</div>")
			stream.enc_print sprintf("%s%s%s\n", $opentag, li, "</div>")
		end # EmptyLine
	else
		if ((/<br \/>$/ =~ li) || (/<\/p>$/ =~ li) || (/<\/div>$/ =~ li) || (/<div.*?>$/ =~ li))
			stream.enc_print "#{li}\n"
		else
			stream.enc_print "#{li}<br \/>\n"
		end # if close tag
	end # if noprint
end # def output

def hyouki(stream)
		# u\Lɂāv𗧂Ă
	stream.enc_print %|<br />\n</div>\n<div class="notation_notes">\n<hr />\n<br />\n\Lɂ<br />\n<ul>\n|
		# t@C`ɂ
	stream.enc_print "\t<li>̃t@C W3C  XHTML1.1 ɂ`ō쐬Ă܂B</li>\n"
		# ͎Ғɂ
	if ($cyuki == 1)
		stream.enc_print "\t<li>mcńA͎҂ɂ钍\LłB</li>\n"
	end # if cyuki
		# ̎_ɂ
	if (($kunoji == 1) && ($dakutenkunoji == 1) && ($encoding == 'Shift_JIS'))
		stream.enc_print "\t<li>u̎_v́u^_vŁAu_t̎_v́u^_vŕ\܂B</li>\n";
	elsif (($kunoji == 1)  && ($dakutenkunoji == 0) && ($encoding == 'Shift_JIS'))
		stream.enc_print "\t<li>u̎_v́u^_vŕ\܂B</li>\n"
	elsif (($kunoji == 0) && ($dakutenkunoji == 1) && ($encoding == 'Shift_JIS'))
		stream.enc_print "\t<li>u_t̎_v́u^_vŕ\܂B</li>\n"
	end # if kunoji

		# VJISɂ
	if (($newjis == 1) && ($encoding == 'utf-8'))
		stream.enc_print "\t<li>JIS X 0213ɂ镶̕\UnicodeZbggĂ邽߁AWindowsł̓CIAMac OSXł̓qMm̑ΉtHgłǂ݉B</li>\n"
	end
	# JIS X 0213 ɂ
	if (($newjis == 1) && ($encoding == 'Shift_JIS'))
		stream.enc_print "\t<li>u̎_v̂JIS X 0213ɂ镶́A摜Ėߍ݂܂B</li>\n";
	end # if JIS X 0213 ɂ
	# ̃ANZgɂ
	if ($accent == 1)
		stream.enc_print "\t<li>ANZgtéAhtml̃}[NAbvLɂĕ\LĂ܂B</li>\n";
	end # if ̃ANZgɂ

	# T_ATނɂ
	if (($boten == 1) || ($bosen == 1))
		stream.enc_print "\t<li>T_T_AT̕t́A\ɂ܂B</li>\n";
	end # if T_ATނɂ
	stream.enc_print "</ul>\n"
	stream.enc_print "</div>\n"
end # def hyouki

def tate(str)
	str.gsub(/(.)/, '<span dir="ltr">\\1</span>')
end #def tate

def gaiji(code, desc="")
	$newjis = 1
	if ($encoding == 'Shift_JIS')
		men,ku,ten = code.split("-")
			# descriptionaltɎc悤ɂB(pushƂdescstripĒǉj
		tag = sprintf(%!<img src="%s/%1d-%02d/%1d-%02d-%02d.png" alt="%s" class="njis" />!, 
				GaijiDir, men, ku.to_i, men, ku.to_i, ten.to_i, desc)

		return kuten2png(code, desc)
	else
		return code.ku2sj
	end # if
end # def gaiji

def kuten2png(code, desc="")
	men,ku,ten = code.split("-")
		# descriptionaltɎc悤ɂB(pushƂdescstripĒǉj
	tag = sprintf(%!<img src="%s/%1d-%02d/%1d-%02d-%02d.png" alt="%s" class="njis" />!, 
			GaijiDir, men, ku.to_i, men, ku.to_i, ten.to_i, desc)

	return tag;
end # def kuten2png

def strong(li)
	$boten = 1
	li.gsub!(/(.+)mu\1vɖT_n/, %q|<strong class="SESAME_DOT">\1</strong>|)
	li.gsub!(/(.+)mu\1vɔS}T_n/, %q|<strong class="WHITE_SESAME_DOT">\\1</strong>|)
	li.gsub!(/(.+)mu\1vɊۖT_n/, %q|<strong class="BLACK_CIRCLE">\1</strong>|)
	li.gsub!(/(.+)mu\1vɔۖT_n/, %q|<strong class="WHITE_CIRCLE">\1</strong>|)
	li.gsub!(/(.+)mu\1vɍOpT_n/, %q|<strong class="BLACK_UP-POINTING_TRIANGLE">\1</strong>|)
	li.gsub!(/(.+)mu\1vɔOpT_n/, %q|<strong class="WHITE_UP-POINTING_TRIANGLE">\1</strong>|)
	li.gsub!(/(.+)mu\1vɓdۖT_n/, %q|<strong class="BULLSEYE">\1</strong>|)
	li.gsub!(/(.+)mu\1vɎւ̖ږT_n/, %q|<strong class="FISHEYE">\1</strong>|)
end # def strong

def underline(li)
	$bosen = 1
	li.gsub!(/(.+)mu\1vɖTn/,  %q|<em class="underline_solid" style="text-decoration: underline; line-style: solid">\1</em>|)
	li.gsub!(/(.+)mu\1vɓdTn/,  %q|<em class="underline_double" style="text-decoration: underline; line-style: double">\1</em>|)
	li.gsub!(/(.+)mu\1vɍn/,  %q|<em class="underline_dotted" style="text-decoration: underline; line-style: dotted">\1</em>|)
	li.gsub!(/(.+)mu\1vɔjn/,  %q|<em class="underline_dashed" style="text-decoration: underline; line-style: dashed">\1</em>|)
	li.gsub!(/(.+)mu\1vɔgn/,  %q|<em class="underline_wave" style="text-decoration: underline; line-style: wave">\1</em>|)
end # def underline

def rubybouten(li)
	def bouten(str, type)
		str.gsub(/(.)/, %|<ruby><rb>\\1</rb><rt class="dot">#{type}</rt></ruby>|)
	end # def bouten
	$boten = 1
	if ($encoding == 'utf-8')
		li.gsub!(/(.+)mu\1vɖT_n/){bouten($1, "]")}
		li.gsub!(/(.+)mu\1vɔS}T_n/){bouten($1, "\")}
		li.gsub!(/(.+)mu\1vɊۖT_n/){bouten($1, "")}
		li.gsub!(/(.+)mu\1vɔۖT_n/){bouten($1, "")}
		li.gsub!(/(.+)mu\1vɍOpT_n/){bouten($1, "")}
		li.gsub!(/(.+)mu\1vɔOpT_n/){bouten($1, "")}
		li.gsub!(/(.+)mu\1vɓdۖT_n/){bouten($1, "")}
		li.gsub!(/(.+)mu\1vɎւ̖ږT_n/){bouten($1, "Z")}
	else
		li.gsub!(/(.+)mu\1vɖT_n/){bouten($1, "R")}
		li.gsub!(/(.+)mu\1vɔS}T_n/){bouten($1, "R")}
		li.gsub!(/(.+)mu\1vɊۖT_n/){bouten($1, "")}
		li.gsub!(/(.+)mu\1vɔۖT_n/){bouten($1, "")}
		li.gsub!(/(.+)mu\1vɍOpT_n/){bouten($1, "")}
		li.gsub!(/(.+)mu\1vɔOpT_n/){bouten($1, "")}
		li.gsub!(/(.+)mu\1vɓdۖT_n/){bouten($1, "")}
		li.gsub!(/(.+)mu\1vɎւ̖ږT_n/){bouten($1, "")}
	end # if encoding
end # def strong

def rubybousen(li)
	def bousen(str, type)
		str.gsub(/(.)/, %|<ruby><rb>\\1</rb><rt class="line">#{type}</rt></ruby>|)
	end # def bouten
	$bosen = 1
	li.gsub!(/(.+)mu\1vɖTn/, %|<span class="bousen">\\1</span>|)
	li.gsub!(/(.+)mu\1vɓdTn/, %|<span class="double">\\1</span>|)
	li.gsub!(/(.+)mu\1vɍn/, %|<span class="sasen">\\1</span>|)
	li.gsub!(/(.+)mu\1vɔjn/, %|<span class="hasen">\\1</span>|)
	li.gsub!(/(.+)mu\1vɔgn/){bousen($1, "``")}
end # def underline

def begin_indent
	$indent = true
	$implicitclosetag = "</div>\n"
end #def begin_indent

def end_indent
	$indent = false
	$burasageindent = false
	$implicitclosetag = ""
end #def end_indent

def begin_burasage_indent
	$burasageindent = true
	$indent = true
	$implicitclosetag = ""
end #def begin_burasage_indent

def end_burasage_indent
	$burasageindent = false
	$indent = false
	$implicitclosetag = ""
end #def end_burasage_indent

def burasage(li)
	burasagecyuki = li.dup
	marginleft = "0"
	textindent = "0"

	burasagecyuki.tr!('PQRSTUVWXO', '1234567890')
	if (/Vt/ =~ burasagecyuki)
		burasagecyuki.match(/܂Ԃ(\d*)/)
		marginleft = $1
		textindent = "-" + $1
	else
		burasagecyuki.match(/(\d*)A܂Ԃ(\d*)/ || /(\d*)A܂Ԃ(\d*)/)
		marginleft = $2
		textindent = "-" + ($2.to_i - $1.to_i).to_s
	end # if burasagecyuki
		# Ԃ炳CfgԂI܂ŁAes̖` <div> ̂ŁAO[oȕϐ $opentag ɒl
	$opentag = %|<div class="burasage" style="margin-#{$jisage_item}: #{marginleft}em\; text-indent: #{textindent}em\;">|
	$noprint = 1

	return	"" # L̂͏B
end # def burasage

def jisage(li)
	line = li.dup
	$indent = true
	line.tr!('PQRSTUVWXO', '1234567890')
	line.tr!('OlܘZZ', '1234567890')
	line.gsub!(/(\d)\(\d)/, '\1\2')
	line.gsub!(/(\d)\/, '\10')
	line.gsub!(/\(\d)/, '1\1')
	line.gsub!(/\/, '10')
	/(\d*)(?:)/ =~ line	
	charlength = $1.dup
	jisage_tag = %|<div class="jisage_#{charlength}" style="margin-left: #{charlength}em; margin-top: #{charlength}em">|

	return jisage_tag
end # def jisage

def chitsuki(li)
	line = li.dup
	$indent = true
	line.tr!('PQRSTUVWXO', '1234567890')
	line.tr!('OlܘZZ', '1234567890')
	line.gsub!(/(\d)\(\d)/, '\1\2')
	line.gsub!(/(\d)\/, '\1' + '0')
	line.gsub!(/\(\d)/, '1\1')
	line.gsub!(/\/, '10')
	charlength = "0"
	if (/n\D*(\d*)/ =~ line)
		charlength = $1.dup
	end # if 
	chitsuki_tag = %|<div class="chitsuki_#{charlength}" style="text-align:right; margin-right: #{charlength}em; margin-bottom: #{charlength}em">|
	return chitsuki_tag
end # def chitsuki

def chyuuou
	chyuuou_tag = %|<div class="cyuuou" style="text-align:center;">|

	return chyuuou_tag
end # def chyuuou

def explicitlyclose
	if ($indent)
		unless ($burasageindent)
			$implicitclosetag = "</div>\n"
		else
			$burasageindent = false
		end # burasage
	end # indent
end # def explicitlyclose

def noFileError
  message_box = Win32API.new('user32', 'MessageBoxA', 'LPPI', 'I')
  message_box.call(0, 'ϊt@ChbOhbvĂ', 'txt2html', 0)
end

def endProcess
  message_box = Win32API.new('user32', 'MessageBoxA', 'LPPI', 'I')
  message_box.call(0, 'ϊI܂', 'txt2html', 0)
end
################################################################################
# C[`

if ((ARGV.size == 0) && ($os == "Win"))
	noFileError
	exit
end

ARGV.each do |textFile|
		# Ώۃt@C̍쐬
	if $standalone
		htmlFile = Iconv.conv('UTF8-MAC', 'SJIS', Iconv.conv('SJIS', 'UTF8-MAC', textFile).sub(/\.txt$/, '.html'))
	else
		htmlFile = textFile.sub(/\.txt$/, '.html')
	end # if
		# t@C̏
	open(textFile) do |intext|
	open(htmlFile, "w") do |outhtml|	
			# ŏ̓̕wb_[iiAҖȂǁj
		isheader = 1
		endofheader = nil
		header = Array.new()
	
		while intext.gets
			chop
				# img^O̐K
			gsub!(/(<img.*?)>/, '\1 />')
			gsub!(/<\/img>/, '>')
				# 󎚂Ȃꏈŝ߂̏
			$noprint = 0
			if (isheader == 1)
						# s΁AŃwb_[I
				if (~EmptyLine || ~/^\-+$/)
					endofheader = 1
				else	# sȊO̓rׂĎŕϐɊi[
					gsub!(/b/, '')
					gsub!(/s.*?t/, '')
					if (intext.lineno > 2 && (~/$/ || /^/))
						expricittranslator = $_
					elsif (intext.lineno > 2 && ~/Z/)
						editor = $_
					else
						header << $_
					end # if 
				end # if EmptyLine
					# sƂōsɉČ`𔻒f
				if (isheader && endofheader)	# 2sA1sڂ薼A2sڂҁBi薼^ҁj
					if (header.size == 2)
						title = header[0]
						author = header[1]
					elsif (header.size == 3)		# 3sA1sڂ薼A3sڂҁi薼^^ҁj
						title = header[0]
						subtitle = header[1]
						author = header[2]
					elsif (header.size == 4)		# 4sA1sڂ薼A3sڂҁA4sڂҁi薼^薼^ҁ^ҁj
						title = header[0]
						original_title = header[1]
						author = header[2]
						unless (expricittranslator)
							translator = header[3]
						end # if expricittranslator
					else												# 6sA1sڂ薼A5sڂҁA6sڂҁi薼^^薼^^ҁ^ҁj
						title = header[0];
						subtitle = header[1];
						original_title = header[2];
						original_subtitle = header[3];
						author = header[4];
						unless (explicittranslator)
							translator = header[5];
						end # if explicittranslator
					end # if header.size
	
					unless (translator)
						translator = expricittranslator if expricittranslator
					end # if empty translator
			
						# <body> ̃^O`ƂƂɁA<title> s\z
					author_tag = sprintf("<h2 class=\"author\">%s</h2>\n", author)
					title_metatag = sprintf("<title>%s", author)
					if (translator)
						translator_tag = sprintf("<h2 class=\"translator\">%s</h2>\n", translator)
						title_metatag = title_metatag + sprintf(" %s", translator)
					end # unless
					title_tag = sprintf("<h1 class=\"title\">%s</h1>\n", title)
					title_metatag = title_metatag + sprintf(" %s", title)
					if (subtitle)
						subtitle_tag = sprintf("<h2 class=\"subtitle\">%s</h2>\n", subtitle)
						title_metatag = title_metatag + sprintf(" %s", subtitle)
					end # unless subtitle
					if (original_title)
						original_title_tag = sprintf("<h2 class=\"original_title\">%s</h2>\n", original_title)
						title_metatag = title_metatag + sprintf(" %s", original_title)
					end # unless original_title
					if (original_subtitle)
						original_subtitle_tag = sprintf("<h2 class=\"original_subtitle\">%s</h2>\n", original_subtitle)
						title_metatag = title_metatag + sprintf(" %s", original_subtitle)
					end # unless original_title
					if (editor)
						editor_tag = sprintf("<h2 class=\"editor\">%s</h2>\n", editor)
						title_metatag = title_metatag + sprintf(" %s", editor)
					end # unless original_title
	
					title_metatag = title_metatag + "</title>"
	
						# ̃[v̓wb_[ubNʂȂ悤
					isheader = 0
	
						# o
						# wb_[́uҖ@i@iZҖȂǁjvƋL
					if ($custom_stylesheet == true)
						if ($browser_ie == true)
							if ($ie_tate == true)
								$tate_open_tag = '<div class="tate">'
								$tate_close_tag = '</div>'
								$style_block = <<__STYLE__
	<style type="text/css">
	<!--
		body {
			margin: 8% 10%;
			direction:rtl;
			overflow-x:scroll;
			overflow-y:auto;
		}

		div, h1, h2 {
			line-height: 150%;
		}

		div.tate {
			direction:ltr;
			writing-mode:tb-rl;
		}

		span.notes {
			font-size: 60%;
		}

		img.njis {
			width: 1em;
			height: 1em;
			margin: 0%;
		}

		rt.dot {
		  text-align: center !important;
		  font-size:50% !important;
		}

		rt.line {
		  text-align: center !important;
		  font-size:50% !important;
		}

		span.bousen {
			border-top-style:solid;
		}

		span.double {
			border-top-style:double;
		}

		span.sasen {
			border-top-style:dotted;
		}

		span.hasen {
			border-top-style:dashed;
		}

		span.namisen {
			border-top-style:dashed;
		}
	-->
	</style>
__STYLE__
							else
								$tate_open_tag = ''
								$tate_close_tag = ''
								$style_block = <<__STYLE__
	<style type="text/css">
	<!--
		body {
			margin: 8% 10%;
		}

		div, h1, h2 {
			line-height: 150%;
		}

		span.notes {
			font-size: 60%;
		}

		img.njis {
			width: 1em;
			height: 1em;
			margin: 0%;
		}

		rt.dot {
		  text-align: center !important;
		  font-size:50% !important;
		}

		rt.line {
		  text-align: center !important;
		  font-size:50% !important;
		}

		span.bousen {
			border-top-style:solid;
		}

		span.double {
			border-top-style:double;
		}

		span.sasen {
			border-top-style:dotted;
		}

		span.hasen {
			border-top-style:dashed;
		}

		span.namisen {
			border-top-style:thin dotted;
		}
	-->
	</style>
__STYLE__
							end # ie_tate
						else
							$tate_open_tag = ''
							$tate_close_tag = ''
							$style_block = <<__STYLE__
	<style type="text/css">
	<!--
		body {
			margin: 8% 10%;
		}

		div, h1, h2 {
			line-height: 150%;
		}

		span.notes {
			font-size: 60%;
		}

		img.njis {
			width: 1em;
			height: 1em;
			margin: 0%;
		}

		:root ruby {
		  display:inline-table !important;
		  text-align: center !important;
		  white-space:nowrap !important;
		  text-indent:0 !important;
		  margin:0 !important;
		  vertical-align:-20% !important;
		  line-height:1.2 !important;
		}

		ruby>rb,ruby>rbc {
		  display:table-row-group !important;
		  line-height:1.2 !important;
		}

		ruby>rt,ruby>rbc+rtc {
		  display:table-header-group !important;
		  font-size:40% !important;
		  line-height:1.2 !important;
		  letter-spacing:0 !important;
		}

		ruby>rbc+rtc+rtc {
		  display:table-footer-group !important;
		  font-size:40% !important;
		  line-height:1 !important;
		  letter-spacing:0 !important;
		}

		rbc>rb,rtc>rt {
		  display:table-cell !important;
		  letter-spacing:0 !important;
		}
		
		rp {
		  display:none !important;
		}

		rt.dot {
		  text-align: center !important;
		  font-size:50% !important;
		}

		rt.line {
		  text-align: center !important;
		  font-size:50% !important;
		}

		span.bousen {
			border-top-style:solid;
		}

		span.double {
			border-top-style:double;
		}

		span.sasen {
			border-top-style:dotted;
		}

		span.hasen {
			border-top-style:dashed;
		}

		span.namisen {
			border-top-style:thin dotted;
		}
	-->
	</style>
__STYLE__
						end # browser_ie
					end # if custom stylesheet
					outhtml.enc_print <<__HEADER__
<?xml version="1.0" encoding="#{$encoding}"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
	"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" >
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=#{$encoding}" />
	<meta http-equiv="content-style-type" content="text/css" />
	#{StyleSheet}
	#{title_metatag}
	<link rel="schema.DC" href="http://purl.org/dc/elements/1.1/" />
	<meta name="DC.Creator" content="#{author}" />
	<meta name="DC.Publisher" content="󕶌" />
	<meta name="DC.language" content="ja" />
	#{$style_block}
</head>
<body>#{$tate_open_tag}
#{title_tag}#{subtitle_tag}#{original_title_tag}#{original_subtitle_tag}#{author_tag}#{translator_tag}#{editor_tag}<div class="main_text">
__HEADER__
				end # if header && no header
				redo if (~/^\-+$/)
			end # if header
		
			###############################
			# `̒LQɓAo𒲂ׂ
			# ---- s̑O section == 0ALQ 1A{ 2
			if (~/^\-+$/)
				section += 1
				gsub!(/^\-+$/, '')
			end # if section
	
			###############################
			# ȏ
			# ĽȂAȉ̏sBL($section== 1͈̔) ͂΂폜
			if (section != 1 && isheader != 1)
					# ANZgL
				acc = Hash.new("")
				acc2 = Array.new
				scan(/k[-A-Za-z\s!&\',\.\/\(\)_:?@\\^`~=\#$%\*]*?l/) do |str|
					rep = str.gsub(Accents){AccentTable[$1]}
					acc[str] = rep.gsub(/[kl]/, '')
					acc2.push(Regexp.escape(str))
				end # scan
				gsub!(Regexp.new('(' + acc2.join("|") + ')')){acc[$1]} if (acc.size != 0)

					# VJIS\L
					# ނoĂ\̂ŁAȂȂ܂
				gsub!(/(m[^mn]*?)([12]\-\d{1,2}\-\d{1,2})([^mn]*?n)/){gaiji($2)}
=begin
				while (~/(m[^mn]*?)([12]\-\d{1,2}\-\d{1,2})([^mn]*?n)/)
					last_match = $1 + $2 + $3
					code = $2.dup
					gsub!(/#{last_match}/, "ʋ_#{code}_")
					if (($encoding == 'utf-8'))
						$subs.push([code, Ku2Unc[code]])
					else
						$subs.push(code)
					end # if
					$newjis = 1
				end # VJIS\L 
=end

					# ꕶAc̏
					# ^Oɂc̏
				gsub!(/(.+)mu\1v͎cn/){tate($1)}	# v
				gsub!(/(.+)mu\1v͏cn/, '<span dir="ltr">\1</span>')	# v
					# ނoĂ\̂ŁAȂȂ܂
				gsub!(/(.+mu\1v͉[P|]A)([12]\-\d{1,2}\-\d{1,2})(n)/){gaiji($2)}
=begin
				while (~/(.+mu\1v͉[P|]A)([12]\-\d{1,2}\-\d{1,2})(n)/)
					last_match = $1 + $2 + $3
					code = $2.dup
					gsub!(/#{last_match}/, "ʋ_#{code}_")
					if ($encoding == 'utf-8')
						$subs.push([code, Ku2Unc[code]])
					else
						$subs.push(code)
					end # if
				end # while
=end
					# ނoĂ\̂ŁAȂȂ܂
#				gsub!(/(.+mu\1v͏cA)([12]\-\d{1,2}\-\d{1,2})(n)/){gaiji($2)}
=begin
				while (~/(.+mu\1v͏cA)([12]\-\d{1,2}\-\d{1,2})(n)/)
					last_match = $1 + $2 + $3
					code = $2.dup
					gsub!(/#{last_match}/, "ʋ_#{code}_")
					if ($encoding == 'utf-8')
						$subs.push([code, Ku2Unc[code]])
					else
						$subs.push(code)
					end # if
				end # ꕶAc̏
=end
					# LȌ --2007/08/30 Xpz{p
					# AŎn܂()_^Ȃŏ
				gsub!(/(m.*?A)([12]\-\d{1,2}\-\d{1,2})(n)/){gaiji($2)}
					# _J^Jȉ@(sɓقȂRgŏƃAEgȀꍇ͏Ɠwhileŉ񂷗lɉKv)
					# 1ނȂ̂ŁA1sɂs΂悢
				if (~/(J)(m1-7-82n)?/)
					last_match = $&.dup
					code = "1-7-82"
					gsub!(/#{last_match}/, gaiji(code))
				end # 
					# 1ނȂ̂ŁA1sɂs΂悢
				if (~/(J)(m1-7-83n)?/)
					last_match = $&.dup
					code = "1-7-83"
					gsub!(/#{last_match}/, gaiji(code))
				end # 
					# 1ނȂ̂ŁA1sɂs΂悢
				if (~/(J)(m1-7-84n)?/)
					last_match = $&.dup
					code = "1-7-84"
					gsub!(/#{last_match}/, gaiji(code))
				end # 
					# 1ނȂ̂ŁA1sɂs΂悢
				if (~/(J)(m1-7-85n)?/)
					last_match = $&.dup
					code = "1-7-85"
					gsub!(/#{last_match}/, gaiji(code))
				end # _J^Jȉ

					# ̎_oǂAu\Lɂāv̂߂ɋLĂ
				if (~Kunoji)
					$kunoji = 1
					gsub!(Kunoji, "") unless ($encoding == 'Shift_JIS')
				end # if ̎
				if (~DakutenKunoji)
					$dakutenkunoji = 1
					gsub!(DakutenKunoji, "") unless ($encoding == 'Shift_JIS')
				end # if ̎
					# ꂽij
					# T_̏
				if (~/(.+)mu\1v.*?T_n/)
					if ($custom_stylesheet == true)
						rubybouten($_)
					else
						strong($_)
					end # if cutstom_style_sheet
				end # if Bousenn
					# T̏
				if (~/(.+)mu\1v.*?n/)
					if ($custom_stylesheet == true)
						rubybousen($_)
					else
						underline($_)
					end # if cutstom_style_sheet
				end # if Bousenn

					# {̃}}L
				gsub!(/(.+)mu\1vɁu(.+?)v̒Ln/,"#{RubiLeft}\\1#{RubiCenter}\\2#{RubiRight}")
					# 
				gsub!(/(.+)mu\1v͕Ԃ_n/, "<small><sub>\\1</sub></small>")
					# V`̕Ԃ_L
				gsub!(/m([OlܘZ\㒆bVnl]+?)n/, "<small><sub>\\1</sub></small>")
					# `̌P_艼L
				gsub!(/(.+)mu\1v͌P_艼n/, "<small><sup>\\1</sup></small>")
					# V`̌P_艼L
				gsub!(/mi(.+?)jn/, "<small><sup>\\1</sup></small>")

					###### nt
					# ntI
#				if (~/m.*?n.*?܂.*?n/ or ~/mŒn.*?In/)
					# 0.13 ꎞIȏH@ŒnIɓꂳ΂P߂̃}b`j
					# ruby̍ŒZṽoOH
				if (~/m[^n]*n[^n]*܂[^n]*n/ or ~/mŒn.*?In/)
					last_match = $1
					gsub!(/#{last_match}/, '</div>')
					end_indent
				end # if ntI
					# 1siȍ~ntjw肳ꂽꍇ
				if (~/mn.*?グn/)
					last_match = $&.dup
						# ȑOɎŃ^OJĂ($implicitclosetag)
					sub!(/#{last_match}/, $implicitclosetag + chitsuki(last_match))
					$_ = $_ + '</div>'	# g^O
					end_indent			# (΁A)O܂ł̃CfgI
				end # sɎw肳ꂽꍇ
					# sɑ΂Ēntw肳ꂽꍇ
				if (~/m(ȍ~|ȉ|).*?ntn/ || ~/m(ȍ~|ȉ|).*?n.*?グn/ || ~/m(ȍ~|ȉ|).*?.*?n.*?.*?n/ || ~/m(ȍ~|ȉ|).*?s.*?.*?n/ || ~/m(ȍ~|ȉ|).*?n.*?.*?n/)
					last_match = $&.dup
					gsub!(/#{last_match}/, '')
					$opentag = chitsuki(last_match)
						# ȑOɎŃ^OJĂ($implicitclosetag)
					$_ = $implicitclosetag + $opentag + $_
					begin_indent	# CfgJn
				#end  # sɑ΂Ēntw肳ꂽꍇ
					# sɒL̂ꍇÂPsintj
				elsif (~/m.*?ntn$/ || ~/m.*?n.*?グn$/ || ~/m.*?.*?n.*?.*?n$/ || ~/m.*?s.*?.*?n$/ || ~/m.*?n.*?.*?n$/)
					last_match = $&.dup
					sub!(/#{last_match}/, '')
					$opentag = chitsuki(last_match)
						# ȑOɎŃ^OJĂ($implicitclosetag)
					$_ = $implicitclosetag + $opentag + $_ + '</div>'
					end_indent
				# end # sɒL̂ꍇ
					# sȊOBL̑Oŉs͂B̍s͎
				elsif (~/m.*?ntn/ || ~/m.*?n.*?グn/ || ~/m.*?.*?n.*?.*?n/ || ~/m.*?s.*?.*?n/ || ~/m.*?n.*?.*?n/)
					last_match = $&.dup
						# ȑOɎŃ^OJĂ($implicitclosetag)
					sub!(/#{last_match}/, $implicitclosetag + chitsuki(last_match))
					$_ = $_ + '</div>'	# g^O
					end_indent
				end # sȊOBL̑Oŉs͂
	
					###### 
					# sɒL̂ꍇ
				if (~/mn$/)
					last_match = $&.dup
					$implicitclosetag = ""
					gsub!(/#{last_match}/, '')
						# ȑOɎŃ^OJĂ($implicitclosetag)
					sub!(/#{last_match}/, $implicitclosetag + chitsuki(last_match))
					$_ = $implicitclosetag + $opentag + $_ + '</div>' # g^O
					end_indent
				# end # sɒL̂ꍇ
					# sȊOBL̑Oŉs͂
				elsif (~/mn/)
					last_match = $&.dup
						# ȑOɎŃ^OJĂ($implicitclosetag)
					sub!(last_match, $implicitclosetag + chyuuou)
					$_ = $_ + '</div>'	# g^O
					end_indent
				end # sȊOBL̑Oŉs͂

					###### 
					# Ԃ牺CfgJn̏ꍇ
				if (~/m.*?܂Ԃ.*?n/)
					last_match = $&.dup
						# ȑOɎŃ^OJĂ($implicitclosetag)
					gsub!(/m.*?܂Ԃ.*?n/, $implicitclosetag + burasage(last_match))
					begin_burasage_indent
				end # Ԃ牺CfgJn̏ꍇ
					# sɎw肳ꂽꍇ
				if (~/m̍s.*?n/ || ~/mV.*?n/)
					last_match = $&.dup
						# ȑOɎŃ^OJĂ($implicitclosetag)
					sub!(/#{last_match}/, $implicitclosetag + jisage(last_match))
					$_ = $_ + '</div>'	# g^O
					end_indent
				end # sɎw肳ꂽꍇ
					# I
				if (~/m.*?.*?܂.*?n/ || ~/m.*?.*?I.*?n/)
					last_match = $&.dup
					sub!(/#{last_match}/, $implicitclosetag )	# sĂ͂Ȃ̂ŁA</div>sv
						#@̍s͈󎚂Ȃ
					$noprint = 1 if ($implicitclosetag == "")  # ^OKvȂΉsȂ
					end_indent
				end # I
					# Jn
					# ̐K\ԓKp͈͂L̂ŁAԍŌ
				if (~/(m.*[^n]*?n)/)
					last_match = $&.dup
						# Õ^OJĂ($implicitclosetag)
					sub!(/#{last_match}/, $implicitclosetag + jisage(last_match))
					begin_indent
				end # Jn
	
					# r
				gsub!(/(.+)m\1.*?tn/, '<sup>\1</sup>')
					# 蒍
					# <a name="footnote"> ͐lœ͂Kv
					#s/(.+)m\1͒߁n/<a href="#footnote">$1<\/a>/g;
				gsub!(/m犄蒍n/, '<span class="warichu">i')
				gsub!(/m.*?蒍In/, 'j</span>')

					# ̏
				gsub!(/(.+)mu\1v͑n/, %|<b>\\1</b>|)
				gsub!(/(.+)m瑾[^n]*?n/, %|<b>|)
				gsub!(/(.+)mőIn/, %|</b>|)
					# Α̂̏
				gsub!(/(.+)mu\1v͎Άn/, %|<i>\\1</i>|)
				gsub!(/(.+)mΑ[^n]*?n/, %|<i>|)
				gsub!(/(.+)mŎΑ̏In/, %|</i>|)

					###### ȑ
					# 탋rɊOL݂ꍇ́AꂪȂ܂ŁAJԂ
#				while (~/m.*?n(?:ʋ_\d-\d{1,2}-\d{1,2}_|[-꤁X]|m[^n]+n)*?s.+?t/)
				while (~/m.*?n(?:<img[^>]+>|[-@-X]|m[^n]+n)*?s.+?t/)
					gsub!(/()(m.+?n)((?:<img[^>]+>|[-@-X]|m[^n]+n)*?)(s.+?t)((?:m[^n]+n)*)/, "\\1\\3\\4\\5\\2")
				end # while
					# rɌLȂǂ̒L݂ꍇ́AřɈړ
				gsub!(/(s[^t]*?)(m[^n]*?n)([^t]*?t)/, "\\1\\3\\2")
					# ŁÂ܂ɉs
				gsub!(/(m.*?n)/, "<br />\n<br />\n\\1<br />\n<br />\n<br />")
				gsub!(/(m[|y[W].*?n)/, "<br />\n<br />\n<br />\n<br />\n<div class=\"pagenate\">\\1<\/div><br />")
					# Ãȑ
					# c_̏ꍇ
				gsub!(/b(.+?)s(.+?)t/, "#{RubiLeft}\\1#{RubiCenter}\\2#{RubiRight}")
					# uWYZTU[RSv̈[aozora:1902][aozora:1903]Q

					#  0213 摜 ѕԂ_
				gsub!(/((?:ʋ_\d-\d{1,2}-\d{1,2}_|[-@-XWYZ]|<su[^>]*?>[^>]+>)+?)s(.+?)t/, "#{RubiLeft}\\1#{RubiCenter}\\2#{RubiRight}")
					# pɃrꍇ
					# pXy[X┼pnCt͉z邱Ƃł
					# Ǔ_ɊւẮÂ
				gsub!(/((?:<img[^>]+>|[A-Za-z0-9#\-\&'\, ])+?)([\.\;\"\?\!\)]{0,2})s(.+?)t/, "#{RubiLeft}\\1\2#{RubiCenter}\\3#{RubiRight}")
					# Ђ炪ȂɃrꍇ
				gsub!(/([-TU]+?)s(.+?)t/, "#{RubiLeft}\\1#{RubiCenter}\\2#{RubiRight}")
					# J^JiɃrꍇ
				gsub!(/([@-[RS]+?)s(.+?)t/, "#{RubiLeft}\\1#{RubiCenter}\\2#{RubiRight}")
					# SpAt@xbgނɃrtꍇ
				gsub!(/([O-X`-y---ք@-`p-|fCD]+?)s(.+?)t/, "#{RubiLeft}\\1#{RubiCenter}\\2#{RubiRight}")

					# cĂ͎ҒŎ
				gsub!(/(m.*?n)/, "<span class=\"notes\">\\1<\/span>")
#				items = scan(/?m.*?n/)
#				items.each do |lm|
#					last_match = Regexp.new("(" + lm + ")")
#					gsub!(last_match, "<span class=\"notes\">\\1<\/span>")
#				end # each items
				if (~/m/)
					$chuki = 1
				end # if L
					# t@CɗAJnʒuɐ
				if (~/&`^{F/)
					if (indent == 1)
						impricitclosetag = "</div>\n"
					end # if indent
					$_ = "#{implicitclosetag}</div>\n<div class=\"bibliographical_information\">\n<hr />\n<br />\n#{$_}\n"
					the_end_is_near = 1
				end # if {
				if (the_end_is_near == 1)
						# {̃ZNVɉȏKvȂ炱ɓB
						# t@C̃^OÂ
					gsub!(/(info\@aozora.gr.jp)/, "<a href=\"mailto:\\1\">\\1</a>")
					gsub!(/󕶌Ɂi\(http:\/\/www.aozora.gr.jp\/\)j/, "<a href=\"\\1\">#{$&}</a>")
				end # if the_end_is_near
					# Ssڈȍ~̈ʓIȏo
				output($_, outhtml)
					# 50sɐiR\[ɏo
				if (intext.lineno % 50 == 0)
					STDERR.print "+"
				end # each 50 lines
			end # 
	
		end # while intext
			# t@CɁu\Lɂāvt
		hyouki(outhtml)
			# t@C̃tb^[
		outhtml.enc_print "#{$tate_close_tag}<\/body>\n<\/html>\n"
		STDERR.print "\ndone\n"
	end # open HTMLFile
	end # open TextFile
end # each infile

if ($os == "Win")
	endProcess
	exit
end
