#!/usr/bin/env ccp4-python

import os, sys, copy, re, glob

import libtbx.phil

from bamboo.wrappers.mlfsom import run_mlfsom, run_xia2
from bamboo import div_bar

bar = div_bar(30)

blank_arg_prepend = {'.pdb':'pdb='}

master_phil = libtbx.phil.parse("""
input {
    pdb = None
        .type = path
        .multiple = True
}
output {
    mlfsom_suffix = '-mlfsom'
        .type = str
    xia2_suffix = '-xia2'
        .type = str
}
mlfsom {
    n_images = 180
        .type = int
    osc = 1.0
        .type = float
    res_high = 2.0
        .type = float
    
}
options {
    run_data_processing = True
        .type = str
}
verbose = False
""")

def run(params):

    assert params.input.pdb, 'No PDB Files provided'

    for p in params.input.pdb:

        assert os.path.exists(p), 'PDB File does not exist: {}'.format(p)
        
        #===================================> 
        
        mlfsom_dir = os.path.splitext(p)[0] + params.output.mlfsom_suffix
        
        print('Running MLFSOM on {}. Putting final output in {}.'.format(p, mlfsom_dir))
        a,m = run_mlfsom(   pdb_file = p, 
                            res_h    = params.mlfsom.res_high, 
                            out_dir  = mlfsom_dir,
                            n_images = params.mlfsom.n_images,
                            osc      = params.mlfsom.osc   )

        #===================================> 
        
        if not params.options.run_data_processing: continue 

        #===================================> 
        
        xia2_dir = os.path.splitext(p)[0] + params.output.xia2_suffix
        
        print('Running xia2 on the MLFSOM data in {}'.format(xia2_dir))
        x = run_xia2(   img_dir = mlfsom_dir,
                        out_dir = xia2_dir  )

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

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)

