#!/bin/bash
# Wrapper for heudiconv.py conversion from Caltech-style DICOM to BIDS
# - Assumes data for each subject are in uncompressed tarballs within the DICOM directory provided
# - Creates participants.txt file in bids directory
# - Default DICOM and BIDS directories are ./dicom and ./bids
#
# USAGE: heudibids <DICOM Directory [./dicom]> <BIDS Directory [./bids]>
#
# AUTHOR : Mike Tyszka
# DATES  : 2017-04-05 JMT From scratch

if [ $# -lt 1 ]; then
    dcm_dir='./dicom'
else
    dcm_dir=$1
fi

if [ $# -lt 2 ]; then
    bids_dir='./bids'
else
    bids_dir=$2
fi

echo "Input DICOM Directory: ${dcm_dir}"
echo "Output BIDS Directory: $(bids_dir)"

# Locate heuristic python script
script_path=`dirname $0`
heuristic=${script_path}/caltech_bids_heuristic.py

for tarball in ${dcm_dir}/*.tar
do

    sid=`basename ${tarball%%.tar}`

    # Run heuristic conversion on supplied DICOM directory
    heudiconv -d "${dcm_dir}/%s.tar" -s ${sid} -o ${bids_dir} -f ${heuristic} -c dcm2niix

done

# Create participants.txt file
part_file=${bids_dir}/participants.txt
for part_dir in ${bids_dir}/*
do

    # Check for participants dicom.txt file (generated by heudiconv)
    dcm_file=${part_dir}/info/dicom.txt

    if [ -s ${dcm_file} ]
    then
        echo "${part_dir} has DICOM information"
    fi

done