#! /usr/bin/python


import Image, sys,math
from random import random

bgcolor = [0.2, 0.2, 0.2]


def make_circle(radius, cx, cy, color):
    def f(x,y):
        if (x-cx)*(x-cx) + (y-cy)*(y-cy) < radius*radius:
            return color, True
        return bgcolor, False
    return f


def distort(x,y):
    xp,yp = x-0.5,y-0.5
    r2 = xp*xp + yp*yp
    theta = 10*r2*math.pi
    sintheta = math.sin(theta)
    costheta = math.cos(theta)
    xr = 0.5 + xp*costheta - yp*sintheta
    yr = 0.5 + xp*sintheta + yp*costheta
    return (xr,yr)


if len(sys.argv) != 5:
    print 'usage:', sys.argv[0], 'width height spp outfile'
    sys.exit(-1)

width = int(sys.argv[1])
height = int(sys.argv[2])
numsamples = int(sys.argv[3])
filename = sys.argv[4]

im = Image.new("RGB", (width, height))
pix = []

objects = [make_circle(0.2, 0.33, 0.33, [1.0, 0.0, 0.0]),
           make_circle(0.2, 0.66, 0.66, [0.0, 1.0, 0.0])
           ]

n = numsamples*numsamples
deltaX = 1.0 / width
deltaY = 1.0 / height
dx = deltaX / numsamples
dy = deltaY / numsamples
y = 1.0 - deltaY
for row in range(0, height):
    x = 0.0
    for col in range(0, width):
        value = [0.0, 0.0, 0.0]
        for i in range(0, numsamples):
            for j in range(0, numsamples):
                sampleX = x + dx*(j+random())
                sampleY = y + dy*(i+random())
                sampleX,sampleY = distort(sampleX, sampleY)
                hitany = False
                for f in objects:
                        sampleValue,hitany = f(sampleX, sampleY)
                        for k in range(0,3):
                            value[k] += sampleValue[k]
                        if hitany:
                           break;
        pixval = (int(255.0*value[0]/n), int(255.0*value[1]/n), int(255.0*value[2]/n))
        pix.append(pixval)
        x = x + deltaX
    y = y - deltaY

im.putdata(pix, 1, 0)
im.save(filename)