#!/usr/bin/env python
"""
Usage:
    qc-fbirn-dti <nifti> <bvec> <bval> <output_prefix> <accel>

Arguments:
    nifti:         4D nifti file of fbirn phantom
    bvec:          bvec file from fbirn phantom
    bval:          bval file from fbirn phantom
    output_prefix: full path to output prefix
    accel:         y/n, y=nyquist accelerated data [default=n]

Details:
    Compute an FA map of the input file, and then runs the included
    'analyze_dti_phantom.m' script on these data.

    Outputs:
        <output_prefix>_stats.csv
        <output_prefix>_SNR_each-b0.csv
        <output_prefix>_SNR_each-DWI.csv
        <output_prefix>_nyq_each-b0.csv
        <output_prefix>_PXShift.csv
        <output_prefix>_b0_diff-roi-noise-hist.jpg
        <output_prefix>_b0_noise-hist.jpg
        <output_prefix>_DWI_diff-roi-noise-hist.jpg
        <output_prefix>_DWI_noise-hist.jpg
        <output_prefix>_SNR_avg-std.jpg
        <output_prefix>_SNR_individual.jpg
        <output_prefix>_SNR_Nyq_eachb0.jpg
        <output_prefix>_FAvalues.jpg

    Depends on FSL & MATLAB.

    Designed by Sofia Chavez, 2014-2015.
    Code packaged and maintained by Joseph Viviano, 2016.
"""
import os, sys
import logging

import qcmon as qc
from qcmon.utilities import make_tmpdir

logging.basicConfig(level=logging.WARN, format="[%(name)s] %(levelname)s: %(message)s")
logger = logging.getLogger(os.path.basename(__file__))


@make_tmpdir
def main(nifti, bvec, bval, output_prefix, tmpdir=None, accel='n'):

    logging.info('Starting')

    # check input options
    if accel not in {'y', 'n'}:
        logger.error("ERROR: acceleration option must be 'y' or 'n', submitted '{}'".format(accel))
        sys.exit(1)

    if not os.path.isdir(os.path.dirname(os.path.abspath(output_prefix))):
        logger.error('ERROR: Output directory {} does not exist.'.format(os.path.dirname(os.path.abspath(output_prefix))))
        sys.exit(1)

    # preprocessing: make FA map
    qc.utilities.run('fslroi {nifti} {t}/tmp_b0.nii.gz 0 1'.format(nifti=nifti, t=tmpdir))
    qc.utilities.run('bet {t}/tmp_b0.nii.gz {t}/tmp_b0_bet.nii.gz -m -f 0.3 -R'.format(t=tmpdir))
    qc.utilities.run('dtifit -k {nifti} -m {t}/tmp_b0_bet_mask.nii.gz -r {bvec} -b {bval} -o {t}/dtifit'.format(
                                   nifti=nifti, t=tmpdir, bvec=bvec, bval=bval))

    fa = os.path.join('{}/dtifit_FA.nii.gz'.format(tmpdir))
    if not os.path.isfile(fa):
        logger.error('ERROR: Failed to calculate FA from {}'.format(nifti))
        sys.exit(1)

    matlabPath = os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir, 'assets/matlab')
    cmd = (r"addpath(genpath('{}')); analyze_dti_phantom('{}','{}','{}','{}','{}')".format(
                                              matlabPath, nifti, fa, bval, output_prefix, accel))
    qc.utilities.run('matlab -nodisplay -nosplash -r "' + cmd + '"')

if __name__ == '__main__':
    if len(sys.argv) == 6:
        main(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], accel=sys.argv[5])
    elif len(sys.argv) == 5:
        main(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
    else:
        print(__doc__)
