module REXML
	class Output
		def initialize real_IO, encoding="iso-8859-1"
			@output = real_IO
			case encoding
			when /^iso-8859-1$/i
				instance_eval "alias :encode :iso_8859_1"
			when /^utf-16$/i
				instance_eval 'alias :encode :utf_16'
			when /^unile$/i
				instance_eval 'alias :encode :unile'
			end
		end

		def <<( content )
			@output << encode( content )
		end

		def encode content
			content
		end
		
		def iso_8859_1 content
			array_utf8 = content.unpack('U*')
			array_enc = []
			array_utf8.each do |num|
				if num <= 0xFF
					array_enc << num
				else
					array_enc << ??
				end
			end
			array_enc.pack('C*')
		end

		def utf_16 content
			array_utf8 = content.unpack("U*")
			array_enc = []
			array_utf8.each do |num|
				if ((num>>16) > 0)
					array_enc << 0
					array_enc << ??
				else
					array_enc << (num >> 8)
					array_enc << (num & 0xFF)
				end
			end
			array_enc.pack('C*')
		end

		def unile content
			array_utf8 = content.unpack("U*")
			array_enc = []
			array_utf8.each do |num|
				if ((num>>16) > 0)
					array_enc << ??
					array_enc << 0
				else
					array_enc << (num & 0xFF)
					array_enc << (num >> 8)
				end
			end
			array_enc.pack('C*')
		end
	end
end
