#!/usr/bin/env ccp4-python

import os,glob,sys

import libtbx.phil
import libtbx.easy_mp

from bamboo.common.command import CommandManager

############################################################################

PROGRAM = 'multi.mtz.map_coefficients'

DESCRIPTION = """

"""

############################################################################

blank_arg_prepend = {'.mtz' : 'mtz='}

master_phil = libtbx.phil.parse("""
input {
    mtz = None
        .help = "input mtz file"
        .multiple = True
        .type = str
}
settings {
    cpus = 1
        .help = "number of cpus to use for processing"
        .type = int
}
""")

############################################################################

def wrapper_run(cmd):
    ret_code = cmd.run()
    if ret_code != 0:
        print '============================>'
        print 'Process returned with an error'
        print '============================>'
        cmd.print_settings()
        print '============================>'
        print cmd.output
        print '============================>'
        print cmd.error
        print '============================>'
    return ret_code

def run(params):

    cmds = []

    for m in params.input.mtz:
        p = m.replace('mtz','pdb')

        cmd = CommandManager('phenix.maps')
        cmd.add_command_line_arguments([p,m])
        cmd.print_settings()
        cmds.append(cmd)

    libtbx.easy_mp.pool_map(func=wrapper_run, args=cmds, processes=params.settings.cpus, chunksize=1)

############################################################################

if __name__=='__main__':
    from giant.jiffies import run_default
    run_default(
        run                 = run,
        master_phil         = master_phil,
        args                = sys.argv[1:],
        blank_arg_prepend   = blank_arg_prepend,
        program             = PROGRAM,
        description         = DESCRIPTION)
