#!/usr/bin/ruby -w

require 'rexml/document'
require 'MyoPyx'

class PyxListener 
	def initialize strip = false
		@doc = REXML::Document.new
		@stack = [@doc]
		@strip = strip
	end

	def start_element( name, attrs )
		@stack << REXML::Element.new(name)
		@stack[-1].add_attributes attrs
	end

	def end_element( name )
		c = @stack.pop
		#puts "Adding #{c.name} to #{@stack[-1].name}"
		@stack[-1] << c if @stack[-1]
	end

	def text( content ) 
		content = content + "\n"
		@stack[-1].add_text content unless @strip and content.strip==''
	end

	def write out
		@doc.write out
		out << "\n"
	end
end

output = $stdout
if ARGV.size < 1 or ARGV.size > 4
	puts "USAGE: #$0 [-s] <pyx_source> [output.xml]\n\t-s\tStrip blank lines"
	exit
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( strip )
pyx = MyoPyx.new
pyx.add_listener pl
pyx.parse( input )
pl.write output
