#!/usr/bin/env python
#
# $Id: spatter-imagecomposer,v 1.1 2005/02/18 10:26:43 grosskur Exp $
#
# Copyright (C) 2003 Alan Grosskurth
#
# This file is part of Spatter.
#
# Spatter is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Spatter is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Spatter; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

import Image, ImageChops
import numarray, math
import sys, os, os.path, string


def image2array(im, final_type=numarray.Float):
    #if im.mode not in ('1', 'L', 'P', 'I', 'F'):
    #    raise ValueError, "can only convert single-layer images"
    if im.mode == 'L':
        type = numarray.UInt8
    elif im.mode == 'I;16':
        type = numarray.UInt16
    else:
        type = numarray.Float32

    a = numarray.fromstring(im.tostring(), type)
    a.shape = im.size[1], im.size[0]
    a = a.astype(final_type)
    return a

def array2image(a):
    if a.type() == numarray.UInt8:
        mode = 'L'
    elif a.type() == numarray.Float32:
        mode = 'F'
    else:
        raise ValueError, "unsupported image mode"
    return Image.fromstring(mode, (a.shape[1], a.shape[0]), a.tostring())

def print_usage():
    print 'Usage: spatter-imagecomposer -i cy3file:cy5file -o imagefile'

def main():
    if len(sys.argv) != 1 and len(sys.argv) != 3 and len(sys.argv) != 5:
        print_usage
        exit

    cy3_fname = ''
    cy5_fname = ''
    image_fname = ''
    if len(sys.argv) == 1:
        image_fname = sys.argv[1]
    elif len(sys.argv) == 3:
        if sys.argv[1] == "-i":
            [cy3_fname,cy5_fname] = sys.argv[2].split(':', 1)
        elif sys.argv[1] == "-o":
            image_fname = sys.argv[2]
        else:
            print_usage()
            exit
    elif len(sys.argv) == 5:
        if sys.argv[1] == "-i":
            [cy3_fname,cy5_fname] = sys.argv[2].split(':', 1)
            if sys.argv[3] == "-o":
                image_fname = sys.argv[4]
            else:
                print_usage();
                exit
        else:
            print_usage
            exit

    #print 'Generating combined image...'
    cy3 = Image.open(cy3_fname)
    cy5 = Image.open(cy5_fname)
    a3 = image2array(cy3)
    a5 = image2array(cy5)
    aout = numarray.sqrt(a3).astype(numarray.UInt8) \
           + numarray.sqrt(a5).astype(numarray.UInt8)
    out =array2image(aout)
    out.save(image_fname)
    #print 'Composed image saved as', image_fname

if __name__ == '__main__':
    main()
