# Mash David Roses jMemorize lesson into FR queue format.
#
# $ wget http://www.me.mtu.edu/~dcrose/hebrew.jml
# (or use a browser to download hebrew.jml to the current directory)
# $ ruby hebrew.rb <hebrew.jml >>queue.txt
#
# Much credit to David for compiling this database and making it freely available !
#
# Since FR does not have any right-justification, the text will be
# left-justified, but still reversed.
#
# comments to michael at the domain of landcroft dot co dot uk

require "rexml/document"
require "rexml/streamlistener"

$Name_map = {
	"All" => "Hebrew",
	"n." => "noun",
	"v. nif'al" => "nif'al",
	"v. hitpa'el" => "hitpa'el",
	"v. huf'al" => "huf'al",
	"v. hif'il" => "hif'il",
	"v. pi'el" => "pi'el",
	"v. pu'al" => "pu'al",
	"v. pa'al" => "pa'al",
	"Pron." => "pronoun",
	"q word" => "interrogative",
	"interj." => "interjection",
	"adv." => "adverb",
	"misc." => "other",
	"adj." => "adjective",
	"prep." => "preposition"
}

class Listener

	include REXML::StreamListener

	def initialize
		@id_stack = []
	end

	def tag_start(name, attributes)
		case name
		when "Lesson"
			# nothing
		when "Deck"
			$stdout.print "<category name=\"", @id_stack.join(" / "), "\">\n"
		when "Category"
			mapped_name = $Name_map[attributes["name"]]
			@id_stack.push(mapped_name != nil ? mapped_name : attributes["name"])
		when "Card"
			$stdout.print "<q>", attributes["Frontside"].split(//u).reverse.join, "</q>\n<a>", attributes["Backside"], "</a>\n"
		else
			warn "unknown tag <" + name + ">\n"
		end
	end

	def tag_end(name)
		case name
		when "Deck"
			$stdout.print "</category>\n"
		when "Category"
			@id_stack.pop
		end
	end

	def text(wording)
		if wording.gsub(/[ \n\r]/, "").length > 0 then
			warn "unexpected text \"" + wording + "\"\n"
		end
	end
end

REXML::Parsers::StreamParser.new($stdin, Listener.new).parse
