#! /usr/bin/env python

import sys
from math import *
from mpz import mpz

# Calculate the position of the triangle on the page.
mm = 72 / 25.4
wd = 210*mm
ht = 297*mm
marg = 10*mm
triht = (wd / 2 - marg) * tan (60 / (180 / pi))
left = (marg, (ht - triht) / 2)
top = (0.5 * wd, ht - left[1])
right = (wd - marg, left[1])

# The number of rows of Pascal's Triangle to use and the number of colors.
cs = 4
nr = cs ** 4
lttriht = (top[1] - left[1]) / nr
lttriside = (right[0] - left[0]) / nr

# The color palette.
cols = ((0.9, 0.95, 1),
        (0.3, 0.6, 0),
        (0.65, 0, 0.55),
        (0.1, 0.45, 0.8))
#cols = ((0.1, 0.85, 1),
#        (0.2, 0.8, 1),
#        (0.3, 0.75, 1),
#        (0.4, 0.7, 1),
#        (0.5, 0.65, 1),
#        (0.6, 0.6, 1),
#        (0.7, 0.55, 1),
#        (0.8, 0.5, 1),
#        (0.9, 0.45, 1),
#        (1, 0.4, 1))

# A function to fill in a polygon.
def fill (p, c):
   print cols[c][0], cols[c][1], cols[c][2], "setrgbcolor newpath"
   print p[0][0], p[0][1], "moveto"
   for pn in p[1:]:
      print pn[0], pn[1], "lineto"
   print "closepath fill"

# Generate the necessary factorials.
fact = [mpz (1)];
for i in xrange (1, nr):
   fact.append (i * fact[i - 1])

# Calculate the binomial (N K).
def binom (n, k):
   return fact[n] / (fact[k] * fact[n - k])

# Calculate the value in Pascal's Triangle at the coordinates (x,y).
def pasc (x, y):
   return binom (x + y, x);


print "%!"


for x in xrange (0, nr):
   for y in xrange (0, nr):
      row = x + y
      if row < nr:
         irow = nr - row - 1
         l = (top[0] + 0.5 * lttriside * (x - y - 1), left[1] + lttriht * irow)
         r = (l[0] + lttriside, l[1])
         t = (l[0] + 0.5 * lttriside, l[1] + lttriht)
         fill ((l, r, t), int (pasc (x, y) % cs))


print "showpage"
