#!/usr/bin/env python
from PIL import Image
from sys import argv
from os import system
from math import sqrt, ceil

def put_pixel(char):
  if (char==' '):
    r=255
    g=0
    b=0
  elif (char== '	'):
    r=0
    g=255
    b=0
  elif (char=='\n'):
    r=0
    g=0
    b=255
  else:
    r=255
    g=255
    b=255

  return (r,g,b)

print
print "    Colorspace - decompile"
print
print "    Tool for \"decompiling\" whitespace program into the simpliest colorspace image"
print
print "(C) GNU GPLv2+ 2010 Sebastian Krzyszkowiak and Agata Kurczewska"
print "---------------------------------------------------------------"

if len(argv)<3:
  print "Usage: "+argv[0]+" file.ws result.png"
  exit(0)

chars = []
newdata = []

f = open(argv[1], "r")
i=0
for line in f.readlines():
  for char in line:
    if (char==' ') or (char=='\t') or (char=='\n'):
      chars.append(char)

n=int(ceil(sqrt(len(chars))))

for char in chars:
  newdata.append(put_pixel(char))
  i=i+1
f.close()

#print "n: " + str(n)
#print "i: " + str(i)
#print "len(chars): " + str(len(chars))
#print "len(data): " + str(len(data))
#print "len(newdata): " + str(len(newdata))

j=0
while (i<n*n):
  newdata.append((255-j,255-j,255-j))
  i=i+1
  j=j+2
  if (j>255):
    j=0

#print "len(newdata): " + str(len(newdata))

im = Image.new("RGB", (n,n))
im.putdata(newdata)
im.save(argv[2], "PNG")

print "Done."
