import struct
import math
import cairo


def h(v):
	v = int(v / 16)
	v = v * 0x11
	return v

def b(v):
	if(v > 120):
		return 1
	return 0

surface = cairo.ImageSurface.create_from_png("./arecibo.png")

MSX = 23 # message size x
MSY = 73

psX = surface.get_width()
psY = surface.get_height()
rowBytes = surface.get_stride()

print "stride %d (%d)" % (rowBytes,rowBytes / psX)
pixelBytes = rowBytes / psX

s = ""
d = ""

print "image size (%d,%d)" % (psX,psY)
data = surface.get_data()
for y in range(0,MSY):
	s += "// "
	d += "        "
	for x in range(0,MSX):
		px = int((x + 0.5) * psX / MSX)
		py = int((y + 0.5) * psY / MSY)
		print "get (%d,%d) from (%d,%d)" % (x,y,px,py)
		pixelParts = (struct.unpack_from("BBBB",data,py * rowBytes + px * pixelBytes))
		
		cB = h(pixelParts[0])
		cG = h(pixelParts[1])
		cR = h(pixelParts[2])

		k = b(cB) * 4 + b(cG) * 2 + b(cR)
		brightness = 10
		if(k == 0):
			brightness = 0
		hue = k;

		if(brightness > 0):
			s += "0123456789"[hue]
			d += "0x%1x%1x," % (brightness,hue)
		else:
			s += " "
			d += "0   ,"


		print pixelParts
#		print "%x" % (struct.unpack_from("I",data,py * rowBytes + px * pixelBytes)[0])
	s += "\n"
	d += "   // line %d\n" % (y)


print s

print "#define ARECIBO_WIDTH %d" % (MSX)
print "#define ARECIBO_HEIGHT %d" % (MSY)

print "const unsigned char areciboData[] = {\n" + d + "        0};\n"

