#!/usr/bin/python

import sys
import os
import Image

def cook(imgdir, outdir):
    """Take imgdir and all the .x and .y files and produce new jpgs"""
    paths = [os.path.join(imgdir, img)
             for img in sorted(os.listdir(imgdir))
             if img.endswith(".jpg")]
    # only take ones with adjustments (special case the base one)
    paths = [paths[0]] + [path
             for path in paths[1:]
             if os.path.exists(path + ".x") and  os.path.exists(path + ".y")]
    print len(paths), "frames from", os.path.basename(paths[0]), "to", os.path.basename(paths[-1])
    x_offset = {}
    y_offset = {}
    # skip the first one, which is inherently "in the right place"
    # (but the code later is simpler if it's there)
    x_offset[paths[0]] = 0
    y_offset[paths[0]] = 0
    for path in paths[1:]:
        x_offset[path] = int(file(path + ".x").read().strip())
        y_offset[path] = int(file(path + ".y").read().strip())

    x_lower = min(x_offset.values())
    y_lower = min(y_offset.values())
    x_upper = max(x_offset.values())
    y_upper = max(y_offset.values())
    
    # assert 640x480 for now
    # step 1: make the composite...
    base_image = Image.new("RGB", (640 - x_lower + x_upper, 480 - y_lower + y_upper))
    blank_base_image = base_image.copy()
    print base_image.size
    for path in paths:
        img = Image.open(path)
        base_image.paste(img, (x_offset[path] - x_lower, y_offset[path] - y_lower))

    if not os.path.isdir(outdir):
        os.mkdir(outdir)
    base_image.save(os.path.join(outdir, "base.jpg"))

    # step 2: compose the pieces
    # base version:
    # for path in paths:
    #     img = Image.open(path)
    #     this_image = base_image.copy()
    #     this_image.paste(img, (x_offset[path] - x_lower, y_offset[path] - y_lower))
    #     this_image.save(os.path.join(outdir, os.path.basename(path)))
    # accumulator version:
    for path in paths:
        img = Image.open(path)
        blank_base_image.paste(img, (x_offset[path] - x_lower, y_offset[path] - y_lower))
        blank_base_image.save(os.path.join(outdir, os.path.basename(path)))



if __name__ == "__main__":
    cook(sys.argv[1], sys.argv[2])

