#!/usr/bin/python
#
# Wrapper script around dcraw and G'MIC
#
# Copyright Claes Holmerson 2010, GPL licensed (see COPYING for details)
#

import sys
import os
import subprocess
import argparse

GMICRAW_HOME = sys.path[0]
CAMERA_PROFILE = os.path.join(GMICRAW_HOME, 'Profiles', 'Camera', 'icc-profiles-canon-eos400d', 'canon_eos400d_faithful.icc')
GMIC_EXTENSION = os.path.join(GMICRAW_HOME, 'gmicext.gmic')    

dcraw_profiles = { 
    'standard' : {
        'dcraw_flags' : { 'linearity' : '-6', 
                        'whitebalance': '-w',
                        'logging': None,
                        'whitelevel': '-W'},
        'dcraw_options' : { '-n' : '50', 
                          '-k': '272',
                          '-p': CAMERA_PROFILE}
        }
    }


def main(argv=None):
    if argv is None:
        argv = sys.argv
        
    start_of_gmic_args = argv.index('-i')
    dcraw_args_iter = iter(argv[1:start_of_gmic_args])
    gmic_args = argv[start_of_gmic_args + 2:]
    raw_file = argv[start_of_gmic_args + 1]
    
    dcraw_args = []

    dcraw_profile_name = dcraw_args_iter.next()
    dcraw_profile = dcraw_profiles.get(dcraw_profile_name, 'standard')
    dcraw_flags = dcraw_profile['dcraw_flags']
    dcraw_options = dcraw_profile['dcraw_options']

    # Use same option names as dcraw uses
    while True:
        try:
            dcraw_arg = dcraw_args_iter.next()

            if dcraw_arg == '-h':
                dcraw_flags.append(dcraw_arg)
            elif dcraw_arg == '-v':
                dcraw_flags['logging'] = dcraw_arg
            elif dcraw_arg == '-a' or dcraw_arg == '-w':
                dcraw_flags['whitebalance'] = dcraw_arg
            elif dcraw_arg == '-A':
                dcraw_flags['whitebalance'] = ('-r '+ dcraw_args_iter.next() + ' ' + dcraw_args_iter.next() + 
                 ' ' + dcraw_args_iter.next() + ' ' +dcraw_args_iter.next())
            elif dcraw_arg == '-r':
                dcraw_flags['whitebalance'] = ('-r '+ dcraw_args_iter.next() + ' ' + dcraw_args_iter.next() + 
                 ' ' + dcraw_args_iter.next() + ' ' +dcraw_args_iter.next())
            if dcraw_arg == '-6' or dcraw_arg == '-4':
                dcraw_flags['linearity'] = dcraw_arg
            elif dcraw_arg == '-W':
                dcraw_flags['whitelevel'] = dcraw_arg
            elif dcraw_arg == '+W': # Non-standard option to disable auto whitelevel
                dcraw_flags['whitelevel'] = ''
            elif dcraw_arg == '-S':
                dcraw_options[dcraw_arg] = dcraw_args_iter.next()
            elif dcraw_arg == '-H':
                dcraw_options[dcraw_arg] = dcraw_args_iter.next()
            elif dcraw_arg == '-p':
                dcraw_options[dcraw_arg] = dcraw_args_iter.next()
            elif dcraw_arg == '+p': # Non-standard option to disable camera profile
                del dcraw_options['-p']
            elif dcraw_arg == '-o':
                dcraw_options[dcraw_arg] = dcraw_args_iter.next()
            elif dcraw_arg == '-K':
                dcraw_options[dcraw_arg] = dcraw_args_iter.next()
            elif dcraw_arg == '-k':
                dcraw_options[dcraw_arg] = dcraw_args_iter.next()
            elif dcraw_arg == '-n':
                dcraw_options[dcraw_arg] = dcraw_args_iter.next()
            elif dcraw_arg == '-b':
                dcraw_options[dcraw_arg] = dcraw_args_iter.next()
            elif dcraw_arg == '-m':
                dcraw_options[dcraw_arg] = dcraw_args_iter.next()
            elif dcraw_arg == '-i':
                dcraw_options[dcraw_arg] = dcraw_args_iter.next()
        except StopIteration:
            break

    dcraw_args = []

    for option, value in dcraw_options.iteritems():
            dcraw_args.append(option)
            dcraw_args.append(value)
    for flag in dcraw_flags.itervalues():
        if not flag is None:
            dcraw_args.append(flag)

    processImage(raw_file, dcraw_args, gmic_args)

def processImage(raw_file, dcraw_args, gmic_args):
    
    dcraw_command = ['dcraw']
    dcraw_command.extend(dcraw_args)
    dcraw_command.extend([ '-c', raw_file])
    gmic_command = ['gmic', '-m', GMIC_EXTENSION, '-.ppm']
    gmic_command.extend(gmic_args)

    print str(dcraw_command)
    print str(gmic_command)
    dcraw_exe = subprocess.Popen(dcraw_command, stdout=subprocess.PIPE)
    gmic_exe = subprocess.Popen(gmic_command, stdin=dcraw_exe.stdout, stdout=subprocess.PIPE)
    print("Processing")
    output = gmic_exe.communicate()[0]
    

if __name__ == "__main__":
    try:
        sys.exit(main())
#    except Exception, e:
#        print ("An error occurred")
#        sys.exit(1)
    except KeyboardInterrupt:
        print "Interrupted"
        sys.exit(1)
