#!/usr/bin/env python
"""
Usage:
    qc-scanlength <nifti> <output>

    <nifti>   full path to nifti file
    <output>  output.csv

If the output file already exists, this program appends to it. This way, it can
be used to generate a scan length report for many subjects.
"""
import os, sys
import csv
import logging
import nibabel as nib

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

def main(nifti, output):

    logging.info('Starting')

    try:
        data = nib.load(nifti)
    except:
        logger.error('ERROR: failed to open nifti file {}'.format(nifti))
        sys.exit(1)

    try:
        length = data.shape[3]
    except:
        length = 1

    if os.path.isfile(output):
        writeMode = 'a'
    else:
        writeMode = 'w'

    with open(output , writeMode) as csvfile:
        writer = csv.writer(csvfile, delimiter=',')
        writer.writerow([os.path.basename(nifti), length])

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