#!/usr/bin/env fslpython
#   Copyright (C) 2016 University of Oxford
#   SHBASECOPYRIGHT

from __future__ import print_function

import os
import subprocess
import sys

fsldir = os.getenv('FSLDIR')
scriptdir = fsldir + '/python/mist'
sys.path.append(scriptdir)

import mist_script

try:
    alldirs = mist_script.read_directories('mist_subjects')
except:
    print('Multimodal Image Segmentation Tool (MIST), part of FSL\n')
    print('Error: Unable to read list of subjects\n')
    print('Please refer to the FSL wiki for usage instructions')

    sys.exit(1)


with open('mist_out/mist_2a_jobs', 'w') as f:
    f.writelines('fslpython ' + scriptdir + '/mist_script.py fit ' + d + '\n' for d in alldirs)

with open('mist_out/mist_2b_jobs', 'w') as f:
    f.write('fslpython ' + scriptdir + '/mist_script.py maketables\n')

jida = subprocess.check_output([fsldir + '/bin/fsl_sub', '-T', '2800', '-l', 'mist_out/log', '-t', 'mist_out/mist_2a_jobs'])
subprocess.check_output([fsldir + '/bin/fsl_sub', '-T', '2800', '-l', 'mist_out/log', '-t', 'mist_out/mist_2b_jobs', '-j', str(jida.decode().split()[0])])

print('All jobs submitted')

