#!/usr/bin/env ccp4-python

import os, sys, glob

import libtbx.easy_mp

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

cpus = 40

def wrapper_proc(arg):
    d,cmd = arg
    os.chdir(d)
    os.system(cmd)

if __name__=='__main__':

    if len(sys.argv) > 1:
        proc_dirs = sorted([os.path.abspath(p) for p in sys.argv[1:] if os.path.exists(p)])
    else:
        proc_dirs = sorted([os.path.abspath(p) for p in glob.glob('./*') if os.path.isdir(p)])

    print 'Processing {} Directories'.format(len(proc_dirs))

    commands = []
    for d in proc_dirs:

        print 'Processing {}'.format(d)
        if os.path.exists(os.path.join(d,'refine.pdb')):
            continue
        else:
            commands.append((d,'giant.quick_refine program=phenix *.pdb *.mtz'))
            #os.system('giant.quick_refine params=phenix.params program=phenix *.cif *.pdb *.mtz')
            #
    print 'Running {} refinements'.format(len(commands))
    libtbx.easy_mp.pool_map(func=wrapper_proc, args=commands, processes=cpus)

