#!/usr/bin/ruby -w

require 'rexml/document'
require 'rexml/streamlistener'

class PyxListener 
	include REXML::StreamListener

	def initialize output, strip = false
		@output = output
		@strip = strip
	end

	def tag_start name, attrs
		@output << "(#{name}\n"
		attrs.each { |attr| @output << "A#{attr[0]} #{attr[1]}\n" }
	end

	def tag_end name
		@output << ")#{name}\n"
	end

	def text text
		text = text.split("\n")
		text.each { |line| 
			@output << "-#{line}\n" unless @strip and line.strip.size == 0
		}
	end
	
	def instruction name, content
		content.gsub!(/\n/, " ")
		name << "?#{name} #{content}\n"
	end
end

output = $stdout
if ARGV.size < 1 or ARGV.size > 4
	puts "USAGE: #$0 [-s] <xml_source> [output.pyx]\n\t-s\tStrip blank lines"
end
strip = false
if ARGV[0] == "-s"
	strip = true
	ARGV.shift
end
if ARGV.size == 2
	output = File.new( ARGV[1], "w+" )
end
input = File.new( ARGV[0] )

pl = PyxListener.new( output, strip )
REXML::Document.parse_stream input, pl
