# monopng.rb $ Revision: 1 $
# Copyright (C) 2007 Michitaka Ohno <elpeo@mars.dti.ne.jp>
# You can redistribute it and/or modify it under GPL2.

require 'zlib'

class MonoPNG
	
	def initialize( data, zoomlevel = 1 )
		@width = 0
		@height = 0
		@data = ""
		data = zoom( data, zoomlevel ) if zoomlevel > 1
		data.each do |line|
			s = line.strip.tr( '01', '10' )
			@width = s.length
			@height += 1
			@data << 0 << [s].pack( "B*" )
		end
	end

	def result
		r = ["89504e470d0a1a0a"].pack( "H*" )
		r << chunk( "IHDR", [@width, @height, 1, 0, 0, 0, 0].pack( "NNC*" ) )
		r << chunk( "IDAT", Zlib::Deflate.deflate( @data ) )
		r << chunk( "IEND" )
	end

	def run
		print result
	end

	private

	def zoom( data, level )
		r = ""
		data.each do |line|
			line.gsub!( /([01])/ ){ $1 * level }
			r << line * level
		end
		r
	end

	def chunk( type, data = "" )
		[data.length].pack( "N" ) + type + data + [Zlib.crc32( type + data )].pack( "N" )
	end
end
