# included_subjects = included_subjects[3:]
# just test with first one!
# included_subjects = [included_subjects[1]]

for sub in included_subjects:
    # this is an example of getting the DICOM files as a list
    sequence_name = 't1_mp2rage_sag_p2_iso_UNI_Images'
    mr_study = db.get_studies(sub, modality='MR', unique=True)
    # if mr_study is not None:
    try:
        # This is a 2D list with [series_name, series_number]
        series = db.get_series(sub, mr_study[0], 'MR')
        # Change this to be more elegant: check whether any item in series
        # matches sequence_name
        try:
            T1_file_names = db.get_files(sub, mr_study[0], 'MR',
                                         series[sequence_name])

            input_dicom = T1_file_names[0]  # first DICOM file

            bash_script = ['#!/usr/bin/env bash']
            bash_script.append('#$ -S /bin/bash')  # for qsub

            # have to explicitly source bashrc (non-login shell)
            bash_script.append('source ~/.bashrc')
            bash_script.append("export FREESURFER_HOME=/usr/local/freesurfer")
            bash_script.append("source $FREESURFER_HOME/SetUpFreeSurfer.sh")
            # bash_script.append('use mne') # set paths
            bash_script.append('export SUBJECTS_DIR=' + subjects_dir)

            # bash_script.append('export SUBJECT=' + sub[:4])
for subj in included_subjects:
    output_folder_base = proj_path + "/scratch/maxfilter/" + analysis_name + "/" + subj
    check_path_exists(output_folder_base)
    for study in db.get_studies(subj, modality="MEG", unique=False):
        # make a neuromag-style folder structure!
        output_folder = output_folder_base + "/" + study[2:8]
        check_path_exists(output_folder)

        radius_head = None  # only once per study!
        for (session, sesnum) in db.get_series(subj, study, modality="MEG"):
            # Start with a fresh copy of the defaults
            mfp = mf_params_defaults.copy()
            session_output_files = []
            session_mfp = []  # NB: this is a list!!

            session_input_files = db.get_files(subj, study, modality="MEG", series=sesnum)
            for ii_raw, raw_fname in enumerate(sorted(session_input_files)):

                fnum_raw = "%02d" % ii_raw
                mfp["input_file"] = raw_fname

                if len(session_input_files) > 1:
                    output_name_base = output_folder + "/" + session + "-" + fnum_raw
                else:
                    output_name_base = output_folder + "/" + session

                if not "empt" in session.lower():  #### TYPO IN ONE SESSION NAME: emptRy!!
                    # change this to test existence of initial HPI measurement...
                    mfp["output_file"] = output_name_base + mf_fname_suffix + ".fif"
                    mfp["mv_hp"] = output_name_base + mf_fname_suffix + ".pos"
                    mfp["logfile"] = output_name_base + mf_fname_suffix + ".log"
# just test with first one!
included_subjects = [included_subjects[0]]

for sub in included_subjects:

    # this is an example of getting the DICOM files as a list
    sequence_name='t1_mprage_3D_sag'
    mr_study = db.get_studies(sub, modality='MR',unique=True)
    if not mr_study is None:
        # This is a 2D list with [series_name, series_number]
        series = db.get_series(sub, mr_study, 'MR',verbose=False)
    #### Change this to be more elegant: check whether any item in series
    #### matches sequence_name
        for ser in series:
            if sequence_name in ser:
                T1_file_names = db.get_files(sub, mr_study, 'MR',ser[1])

    input_dicom = T1_file_names[0] # first DICOM file

    bash_script = ['#!/usr/bin/env bash']
    bash_script.append('#$ -S /bin/bash') # for qsub
    
    # have to explicitly source bashrc (non-login shell)
    bash_script.append('source ~/.bashrc')
    bash_script.append('use mne') # set paths
    bash_script.append('export SUBJECTS_DIR='+subjects_dir)

    bash_script.append('export SUBJECT=' + sub)

    bash_script.append('recon-all -s ' + sub + ' -i ' + input_dicom + ' -all')
    # Can do some exit value checking too...
    output_folder_base = proj_path + '/scratch/maxfilter/' + analysis_name + '/' + subj
    check_path_exists(output_folder_base)
    for study in db.get_studies(subj, modality='MEG', unique=False):
        # make a neuromag-style folder structure!
        output_folder = output_folder_base + '/' + study[2:8]
        check_path_exists(output_folder)

        radius_head = None  # only once per study!
        for (session, sesnum) in db.get_series(subj, study, modality='MEG'):
            # Start with a fresh copy of the defaults
            mfp = mf_params_defaults.copy()
            session_output_files = []
            session_mfp = []  #NB: this is a list!!

            session_input_files = db.get_files(subj,
                                               study,
                                               modality='MEG',
                                               series=sesnum)
            for ii_raw, raw_fname in enumerate(sorted(session_input_files)):

                fnum_raw = "%02d" % ii_raw
                mfp['input_file'] = raw_fname

                if len(session_input_files) > 1:
                    output_name_base = output_folder + '/' + session + '-' + fnum_raw
                else:
                    output_name_base = output_folder + '/' + session

                if not 'empt' in session.lower(
                ):  #### TYPO IN ONE SESSION NAME: emptRy!!
                    # change this to test existence of initial HPI measurement...
                    mfp['output_file'] = output_name_base + mf_fname_suffix + '.fif'