#!/usr/bin/env python
"""
Part of RuG/L04
Translate an ordinary RGB map, created with 'maprgb', into an interpolated RGB map
"""

__author__ = "Peter Kleiweg"
__version__ = "0.12"
__date__ = "2008/12/18"

#| imports

#import cgitb; cgitb.enable(format = 'text')

import os, re, sys

#| ps code

header = """
%% influence parameters
/parA 1 def   %% positive
/parP 10 def   %% positive or zero
/parQ 100 def   %% positive or zero

%% grid resolution
/DX 5 def
/DY DX def

%% box area that should be painted
/BBox [ %(x1)i %(y1)i %(x2)i %(y2)i ] def
"""

interpolate = """
/contrast {
    /ex exch def
    parA 3 div ex mul ex mul ex mul
    parA parP mul ex mul ex mul sub
    parA parP mul parP mul ex mul add
    parQ ex mul add
} bind def
/DDX DX 1 add def
/DDY DY 1 add def
BBox 0 get DX BBox 2 get {
    /X exch def
    BBox 1 get DY BBox 3 get {
        /Y exch def
        /RED 0 def
        /GREEN 0 def
        /BLUE 0 def
        /BOTTOM 0 def
        0 1 NR {
            PP exch get
            aload pop
            /b exch def
            /g exch def
            /r exch def
            /p exch def
            pop pop pop
            /y exch def
            /x exch def
            p 256 and 0 ne {
                /D x X sub dup mul
                    y Y sub dup mul
                    add .5 exp
                    dup 2 lt { pop 2 } if
                    contrast def
                1 D div
                dup BOTTOM add /BOTTOM exch def
                dup r mul RED add /RED exch def
                dup g mul GREEN add /GREEN exch def
                b mul BLUE add /BLUE exch def
            } if
        } for
        RED BOTTOM div
        GREEN BOTTOM div
        BLUE BOTTOM div
        SETCOLOR
        X DX 2 div sub
        Y DY 2 div sub
        DDX DDY
        rectfill
    } for
} bind for

"""

#| main

if sys.argv[1:]:
    lines = open(sys.argv[1], 'r').readlines()
else:
    lines = sys.stdin.readlines()

for line in lines:
    if line.startswith('%%BoundingBox:'):
        x1, y1, x2, y2 = [int(x) for x in line.split()[1:5]]
        x1 -= 5
        y1 -= 5
        x2 += 5
        y2 += 5
        break

state = 0
PPlen = 0
for line in lines:
    if state == 0:
        if line.startswith('/PP '):
            state = 1
    elif state == 1:
        if line.startswith('] def'):
            break
        else:
            PPlen += 1
polys = [False] * PPlen
for line in lines:
    m = re.match(r'(\d+)\s+mark', line)
    if m:
        polys[int(m.group(1))] = True


state = 0
PPidx = 0
for line in lines:
    if state == 0:
        sys.stdout.write(line)
        if re.match(r'\s*\d+\s+dict\s+begin', line):
            sys.stdout.write(header % vars())
            state = 1
    elif state == 1:
        sys.stdout.write(line)
        if line.startswith('/PP '):
            state = 2
    elif state == 2:
        if line.startswith('] def'):
            sys.stdout.write(line)
            state = 3
        else:
            if polys[PPidx]:
                a = line.split()
                sys.stdout.write('  ' + ' '.join(a[:-5]) + ' 256 or ' + ' '.join(a[-5:]) + '\n')
            else:
                sys.stdout.write(line)
            PPidx += 1
    elif state == 3:
        if line.startswith('/poly '):
            sys.stdout.write(interpolate)
            state = 4
        else:
            sys.stdout.write(line)
    elif state == 4:
        if line.startswith('grestore'):
            sys.stdout.write(line)
            state = 5
    elif state == 5:
        sys.stdout.write(line)



