#!/usr/bin/env python

import os
import sys
import tempfile
from PIL import Image
import subprocess

def load_xcf(filename):
    proc = subprocess.Popen(["xcf2png", filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    
    (out, err) = proc.communicate()
    
    if proc.returncode != 0:
        raise Exception("error: failed to load %s:\n" % filename, err)
    else:
        (fd, name) = tempfile.mkstemp()
        os.write(fd, out)
        os.close(fd)

        img = Image.open(name)
        os.unlink(name)
        
        return img

def main(args):
    for filename in args:
        cutspec_filename = filename + '.cutspec'
        save_directory = os.path.dirname(filename)

        if not os.path.exists(cutspec_filename):
            print "Error: '%s' missing" % cutspec_filename
        else:
            # load cutspec the dirty and insecure way
            print "Loading: '%s'" % cutspec_filename

            cutspec_globals = {}
            cutspec_locals  = {}
            execfile(cutspec_filename, cutspec_globals, cutspec_locals)

            if not 'cutspec' in cutspec_locals:
                print "Error: Couldn't find definition of cutspec in %s" % (cutspec_filename)
            else:
                img = load_xcf(args[0])

                for (spec, out_filename) in cutspec_locals['cutspec']:
                    outfile = os.path.join(save_directory, out_filename)
                    img.crop(spec).save(outfile)
                    print "Converted %s to %s with cutspec %s" % (filename, outfile, spec)

if __name__ == "__main__":
    main(sys.argv[1:])

# EOF #

