#!/bin/tcsh -xef

echo "auto-generated by afni_proc.py, Mon Oct  7 17:25:42 2024"
echo "(version 7.79, Aug 30, 2024)"
echo "execution started: `date`"

# to execute via tcsh: 
#   tcsh -xef proc.sub-10785 |& tee output.proc.sub-10785
# to execute via bash: 
#   tcsh -xef proc.sub-10785 2>&1 | tee output.proc.sub-10785

# =========================== auto block: setup ============================
# script setup

# take note of the AFNI version
afni -ver

# check that the current AFNI version is recent enough
afni_history -check_date  7 Mar 2024
if ( $status ) then
    echo "** this script requires newer AFNI binaries (than  7 Mar 2024)"
    echo "   (consider: @update.afni.binaries -defaults)"
    exit
endif

# the user may specify a single subject to run with
if ( $#argv > 0 ) then
    set subj = $argv[1]
else
    set subj = sub-10785
endif

# assign output directory name
set output_dir = $subj.results

# verify that the results directory does not yet exist
if ( -d $output_dir ) then
    echo output dir "$subj.results" already exists
    exit
endif

# set list of runs
set runs = (`count_afni -digits 2 1 1`)

# create results and stimuli directories
mkdir -p $output_dir
mkdir $output_dir/stimuli

# copy stim files into stimulus directory
cp                                                                                                       \
    /data/NIMH_SSCC/rickr/UCLA.pamenc/AFNI/derivatives/AFNI_02_pamenc/sub-10785/timing/times.CONTROL.txt \
    /data/NIMH_SSCC/rickr/UCLA.pamenc/AFNI/derivatives/AFNI_02_pamenc/sub-10785/timing/times.TASK.txt    \
    $output_dir/stimuli

# copy anatomy to results dir
3dcopy                                                                                                 \
    /data/NIMH_SSCC/rickr/UCLA.pamenc/AFNI/derivatives/AFNI_01_SSwarper/sub-10785/anatSS.sub-10785.nii \
    $output_dir/anatSS.sub-10785

# copy template to results dir (for QC)
3dcopy                                                                             \
    /usr/local/apps/afni/current-py3/linux_rocky_8/MNI152_2009_template_SSW.nii.gz \
    $output_dir/MNI152_2009_template_SSW.nii.gz

# copy anatomical follower datasets into the results dir
3dcopy                                                                                                \
    /data/NIMH_SSCC/rickr/UCLA.pamenc/AFNI/derivatives/AFNI_01_SSwarper/sub-10785/anatU.sub-10785.nii \
    $output_dir/copy_af_anat_w_skull

# copy any -ROI_import datasets as ROI_import_LABEL
3dcopy                                                                              \
    /usr/local/apps/afni/current-py3/linux_rocky_8/APQC_atlas_MNI_2009c_asym.nii.gz \
    $output_dir/ROI_import_MNI_2009c_asym

# copy external -tlrc_NL_warped_dsets datasets
3dcopy                                                                                                      \
    /data/NIMH_SSCC/rickr/UCLA.pamenc/AFNI/derivatives/AFNI_01_SSwarper/sub-10785/anatQQ.sub-10785.nii      \
    $output_dir/anatQQ.sub-10785
3dcopy                                                                                                      \
    /data/NIMH_SSCC/rickr/UCLA.pamenc/AFNI/derivatives/AFNI_01_SSwarper/sub-10785/anatQQ.sub-10785.aff12.1D \
    $output_dir/anatQQ.sub-10785.aff12.1D
3dcopy                                                                                                      \
    /data/NIMH_SSCC/rickr/UCLA.pamenc/AFNI/derivatives/AFNI_01_SSwarper/sub-10785/anatQQ.sub-10785_WARP.nii \
    $output_dir/anatQQ.sub-10785_WARP.nii

# ============================ auto block: tcat ============================
# apply 3dTcat to copy input dsets to results dir,
# while removing the first 0 TRs
3dTcat -prefix $output_dir/pb00.$subj.r01.tcat      \
    /data/NIMH_SSCC/rickr/UCLA.pamenc/pamenc.class.60.links/sub-10785/func/sub-10785_task-pamenc_bold.nii.gz'[0..$]'

# and make note of repetitions (TRs) per run
set tr_counts = ( 242 )

# -------------------------------------------------------
# enter the results directory (can begin processing data)
cd $output_dir


# ---------------------------------------------------------
# QC: compute correlations with spherical ~averages
@radial_correlate -nfirst 0 -polort 4 -do_clean yes \
                  -rdir radcor.pb00.tcat            \
                  pb00.$subj.r*.tcat+orig.HEAD

# ---------------------------------------------------------
# QC: look for columns of high variance
find_variance_lines.tcsh -polort 4 -nerode 2        \
       -rdir vlines.pb00.tcat                       \
       pb00.$subj.r*.tcat+orig.HEAD |& tee out.vlines.pb00.tcat.txt

# ========================== auto block: outcount ==========================
# QC: compute outlier fraction for each volume
touch out.pre_ss_warn.txt
foreach run ( $runs )
    3dToutcount -automask -fraction -polort 4 -legendre                     \
                pb00.$subj.r$run.tcat+orig > outcount.r$run.1D

    # censor outlier TRs per run, ignoring the first 0 TRs
    # - censor when more than 0.05 of automask voxels are outliers
    # - step() defines which TRs to remove via censoring
    1deval -a outcount.r$run.1D -expr "1-step(a-0.05)" > rm.out.cen.r$run.1D

    # outliers at TR 0 might suggest pre-steady state TRs
    if ( `1deval -a outcount.r$run.1D"{0}" -expr "step(a-0.4)"` ) then
        echo "** TR #0 outliers: possible pre-steady state TRs in run $run" \
            >> out.pre_ss_warn.txt
    endif
end

# catenate outlier counts into a single time series
cat outcount.r*.1D > outcount_rall.1D

# catenate outlier censor files into a single time series
cat rm.out.cen.r*.1D > outcount_${subj}_censor.1D

# ---------------------------------------------------------
# check for potential 4095 saturation issues
foreach run ( $runs )
    3dTto1D -method 4095_warn -input pb00.$subj.r$run.tcat+orig             \
            |& tee -a out.4095_all.txt
end

# make a file showing any resulting warnings
awk '/warning/ {print}' out.4095_all.txt | tee out.4095_warn.txt

# get run number and TR index for minimum outlier volume
set minindex = `3dTstat -argmin -prefix - outcount_rall.1D\'`
set ovals = ( `1d_tool.py -set_run_lengths $tr_counts                       \
                          -index_to_run_tr $minindex` )
# save run and TR indices for extraction of vr_base_min_outlier
set minoutrun = $ovals[1]
set minouttr  = $ovals[2]
echo "min outlier: run $minoutrun, TR $minouttr" | tee out.min_outlier.txt

# ================================= tshift =================================
# time shift data so all slice timing is the same 
foreach run ( $runs )
    3dTshift -tzero 0 -quintic -prefix pb01.$subj.r$run.tshift \
             -tpattern alt+z2                                  \
             pb00.$subj.r$run.tcat+orig
end

# --------------------------------
# extract volreg registration base
3dbucket -prefix vr_base_min_outlier                           \
    pb01.$subj.r$minoutrun.tshift+orig"[$minouttr]"

# ================================= align ==================================
# for e2a: compute anat alignment transformation to EPI registration base
# (new anat will be current anatSS.sub-10785+orig)
# run (localized) uniformity correction on EPI base
3dLocalUnifize -input vr_base_min_outlier+orig -prefix  \
    vr_base_min_outlier_unif

align_epi_anat.py -anat2epi -anat anatSS.sub-10785+orig \
       -suffix _al_junk                                 \
       -epi vr_base_min_outlier_unif+orig -epi_base 0   \
       -epi_strip 3dAutomask                            \
       -anat_has_skull no                               \
       -giant_move -cost lpc+ZZ -check_flip             \
       -volreg off -tshift off

# ================================== tlrc ==================================

# nothing to do: have external -tlrc_NL_warped_dsets

# warped anat     : anatQQ.sub-10785+tlrc
# affine xform    : anatQQ.sub-10785.aff12.1D
# non-linear warp : anatQQ.sub-10785_WARP.nii

# ================================= volreg =================================
# align each dset to base volume, to anat, warp to tlrc space

# verify that we have a +tlrc warp dataset
if ( ! -f anatQQ.sub-10785+tlrc.HEAD ) then
    echo "** missing +tlrc warp dataset: anatQQ.sub-10785+tlrc.HEAD" 
    exit
endif

# register and warp
foreach run ( $runs )
    # register each volume to the base image
    3dvolreg -verbose -zpad 1 -base vr_base_min_outlier+orig                \
             -1Dfile dfile.r$run.1D -prefix rm.epi.volreg.r$run             \
             -cubic                                                         \
             -1Dmatrix_save mat.r$run.vr.aff12.1D                           \
             pb01.$subj.r$run.tshift+orig

    # create an all-1 dataset to mask the extents of the warp
    3dcalc -overwrite -a pb01.$subj.r$run.tshift+orig -expr 1               \
           -prefix rm.epi.all1

    # catenate volreg/epi2anat/tlrc xforms
    cat_matvec -ONELINE                                                     \
               anatQQ.sub-10785.aff12.1D                                    \
               anatSS.sub-10785_al_junk_mat.aff12.1D -I                     \
               mat.r$run.vr.aff12.1D > mat.r$run.warp.aff12.1D

    # apply catenated xform: volreg/epi2anat/tlrc/NLtlrc
    # then apply non-linear standard-space warp
    3dNwarpApply -master anatQQ.sub-10785+tlrc -dxyz 3                      \
                 -source pb01.$subj.r$run.tshift+orig                       \
                 -nwarp "anatQQ.sub-10785_WARP.nii mat.r$run.warp.aff12.1D" \
                 -prefix rm.epi.nomask.r$run

    # warp the all-1 dataset for extents masking 
    3dNwarpApply -master anatQQ.sub-10785+tlrc -dxyz 3                      \
                 -source rm.epi.all1+orig                                   \
                 -nwarp "anatQQ.sub-10785_WARP.nii mat.r$run.warp.aff12.1D" \
                 -interp cubic                                              \
                 -ainterp NN -quiet                                         \
                 -prefix rm.epi.1.r$run

    # make an extents intersection mask of this run
    3dTstat -min -prefix rm.epi.min.r$run rm.epi.1.r$run+tlrc
end

# make a single file of registration params
cat dfile.r*.1D > dfile_rall.1D

# ----------------------------------------
# create the extents mask: mask_epi_extents+tlrc
# (this is a mask of voxels that have valid data at every TR)
# (only 1 run, so just use 3dcopy to keep naming straight)
3dcopy rm.epi.min.r01+tlrc mask_epi_extents

# and apply the extents mask to the EPI data 
# (delete any time series with missing data)
foreach run ( $runs )
    3dcalc -a rm.epi.nomask.r$run+tlrc -b mask_epi_extents+tlrc             \
           -expr 'a*b' -prefix pb02.$subj.r$run.volreg
end

# warp the volreg base EPI dataset to make a final version
cat_matvec -ONELINE                                                         \
           anatQQ.sub-10785.aff12.1D                                        \
           anatSS.sub-10785_al_junk_mat.aff12.1D -I  > mat.basewarp.aff12.1D

3dNwarpApply -master anatQQ.sub-10785+tlrc -dxyz 3                          \
             -source vr_base_min_outlier+orig                               \
             -nwarp "anatQQ.sub-10785_WARP.nii mat.basewarp.aff12.1D"       \
             -prefix final_epi_vr_base_min_outlier

# create an anat_final dataset, aligned with stats
3dcopy anatQQ.sub-10785+tlrc anat_final.$subj

# record final registration costs
3dAllineate -base final_epi_vr_base_min_outlier+tlrc -allcostX              \
            -input anat_final.$subj+tlrc |& tee out.allcostX.txt

# --------------------------------------
# create a TSNR dataset, just from run 1
3dTstat -mean -prefix rm.signal.vreg.r01 pb02.$subj.r01.volreg+tlrc
3dDetrend -polort 4 -prefix rm.noise.det -overwrite pb02.$subj.r01.volreg+tlrc
3dTstat -stdev -prefix rm.noise.vreg.r01 rm.noise.det+tlrc
3dcalc -a rm.signal.vreg.r01+tlrc                                           \
       -b rm.noise.vreg.r01+tlrc                                            \
       -c mask_epi_extents+tlrc                                             \
       -expr 'c*a/b' -prefix TSNR.vreg.r01.$subj

# -----------------------------------------
# warp anat follower datasets (non-linear)
# warp follower dataset copy_af_anat_w_skull+orig
3dNwarpApply -source copy_af_anat_w_skull+orig                              \
             -master anat_final.$subj+tlrc                                  \
             -ainterp wsinc5 -nwarp anatQQ.sub-10785_WARP.nii               \
             anatQQ.sub-10785.aff12.1D                                      \
             -prefix follow_anat_anat_w_skull

# ---------------------------------------------------------
# QC: compute correlations with spherical ~averages
@radial_correlate -nfirst 0 -polort 4 -do_clean yes                         \
                  -rdir radcor.pb02.volreg                                  \
                  pb02.$subj.r*.volreg+tlrc.HEAD

# ================================== mask ==================================
# create 'full_mask' dataset (union mask)
foreach run ( $runs )
    3dAutomask -prefix rm.mask_r$run pb02.$subj.r$run.volreg+tlrc
end

# create union of inputs, output type is byte
3dmask_tool -inputs rm.mask_r*+tlrc.HEAD -union -prefix full_mask.$subj

# ---- create subject anatomy mask, mask_anat.$subj+tlrc ----
#      (resampled from tlrc anat)
3dresample -master full_mask.$subj+tlrc -input anatQQ.sub-10785+tlrc  \
           -prefix rm.resam.anat

# convert to binary anat mask; fill gaps and holes
3dmask_tool -dilate_input 5 -5 -fill_holes -input rm.resam.anat+tlrc  \
            -prefix mask_anat.$subj

# compute tighter EPI mask by intersecting with anat mask
3dmask_tool -input full_mask.$subj+tlrc mask_anat.$subj+tlrc          \
            -inter -prefix mask_epi_anat.$subj

# compute overlaps between anat and EPI masks
3dABoverlap -no_automask full_mask.$subj+tlrc mask_anat.$subj+tlrc    \
            |& tee out.mask_ae_overlap.txt

# note Dice coefficient of masks, as well
3ddot -dodice full_mask.$subj+tlrc mask_anat.$subj+tlrc               \
      |& tee out.mask_ae_dice.txt

# ---- create group anatomy mask, mask_group+tlrc ----
#      (resampled from tlrc base anat, MNI152_2009_template_SSW.nii.gz)
3dresample -master mask_epi_anat.$subj+tlrc -prefix ./rm.resam.group  \
           -input                                                     \
           /usr/local/apps/afni/current-py3/linux_rocky_8/MNI152_2009_template_SSW.nii.gz'[0]'

# convert to binary group mask; fill gaps and holes
3dmask_tool -dilate_input 5 -5 -fill_holes -input rm.resam.group+tlrc \
            -prefix mask_group

# note Dice coefficient of anat and template masks
3ddot -dodice mask_anat.$subj+tlrc mask_group+tlrc                    \
      |& tee out.mask_at_dice.txt

# ================================== blur ==================================
# blur each volume of each run
foreach run ( $runs )
    3dBlurInMask -preserve -FWHM 6 -Mmask mask_epi_anat.$subj+tlrc \
                 -prefix pb03.$subj.r$run.blur                     \
                 pb02.$subj.r$run.volreg+tlrc
end

# ================================= scale ==================================
# scale each voxel time series to have a mean of 100
# (be sure no negatives creep in)
# (subject to a range of [0,200])
foreach run ( $runs )
    3dTstat -prefix rm.mean_r$run pb03.$subj.r$run.blur+tlrc
    3dcalc -a pb03.$subj.r$run.blur+tlrc -b rm.mean_r$run+tlrc \
           -c mask_epi_extents+tlrc                            \
           -expr 'c * min(200, a/b*100)*step(a)*step(b)'       \
           -prefix pb04.$subj.r$run.scale
end

# ================================ regress =================================

# compute de-meaned motion parameters (for use in regression)
1d_tool.py -infile dfile_rall.1D -set_nruns 1                            \
           -demean -write motion_demean.1D

# compute motion parameter derivatives (just to have)
1d_tool.py -infile dfile_rall.1D -set_nruns 1                            \
           -derivative -demean -write motion_deriv.1D

# convert motion parameters for per-run regression
1d_tool.py -infile motion_demean.1D -set_nruns 1                         \
           -split_into_pad_runs mot_demean

# create censor file motion_${subj}_censor.1D, for censoring motion 
1d_tool.py -infile dfile_rall.1D -set_nruns 1                            \
    -show_censor_count -censor_prev_TR                                   \
    -censor_motion 0.3 motion_${subj}

# combine multiple censor files
1deval -a motion_${subj}_censor.1D -b outcount_${subj}_censor.1D         \
       -expr "a*b" > censor_${subj}_combined_2.1D

# resample any -ROI_import dataset onto the EPI grid
# (and copy its labeltable)

3dresample -master final_epi_vr_base_min_outlier+tlrc -rmode NN          \
           -input ROI_import_MNI_2009c_asym+tlrc                         \
           -prefix ROI_import_MNI_2009c_asym_resam

3drefit -copytables ROI_import_MNI_2009c_asym+tlrc                       \
    ROI_import_MNI_2009c_asym_resam+tlrc
3drefit -cmap INT_CMAP ROI_import_MNI_2009c_asym_resam+tlrc

# note TRs that were not censored
# (apply from a text file, in case of a lot of censoring)
1d_tool.py -infile censor_${subj}_combined_2.1D                          \
           -show_trs_uncensored space                                    \
           > out.keep_trs_rall.txt
set ktrs = "1dcat out.keep_trs_rall.txt"

# ------------------------------
# run the regression analysis
3dDeconvolve -input pb04.$subj.r*.scale+tlrc.HEAD                        \
    -censor censor_${subj}_combined_2.1D                                 \
    -ortvec mot_demean.r01.1D mot_demean_r01                             \
    -polort 4                                                            \
    -num_stimts 2                                                        \
    -stim_times_AM1 1 stimuli/times.CONTROL.txt 'dmBLOCK'                \
    -stim_label 1 CONTROL                                                \
    -stim_times_AM1 2 stimuli/times.TASK.txt 'dmBLOCK'                   \
    -stim_label 2 TASK                                                   \
    -jobs 8                                                              \
    -tout -x1D X.xmat.1D -xjpeg X.jpg                                    \
    -x1D_uncensored X.nocensor.xmat.1D                                   \
    -errts errts.${subj}                                                 \
    -x1D_stop                                                            \
    -bucket stats.$subj


# if 3dDeconvolve fails, terminate the script
if ( $status != 0 ) then
    echo '---------------------------------------'
    echo '** 3dDeconvolve error, failing...'
    echo '   (consider the file 3dDeconvolve.err)'
    exit
endif


# display any large pairwise correlations from the X-matrix
1d_tool.py -show_cormat_warnings -infile X.xmat.1D |& tee out.cormat_warn.txt

# display degrees of freedom info from X-matrix
1d_tool.py -show_df_info -infile X.xmat.1D |& tee out.df_info.txt

# -- execute the 3dREMLfit script, written by 3dDeconvolve --
tcsh -x stats.REML_cmd 

# if 3dREMLfit fails, terminate the script
if ( $status != 0 ) then
    echo '---------------------------------------'
    echo '** 3dREMLfit error, failing...'
    exit
endif


# create an all_runs dataset to match the fitts, errts, etc.
3dTcat -prefix all_runs.$subj pb04.$subj.r*.scale+tlrc.HEAD

# --------------------------------------------------
# create a temporal signal to noise ratio dataset 
#    signal: if 'scale' block, mean should be 100
#    noise : compute standard deviation of errts
3dTstat -mean -prefix rm.signal.all all_runs.$subj+tlrc"[$ktrs]"
3dTstat -stdev -prefix rm.noise.all errts.${subj}_REML+tlrc"[$ktrs]"
3dcalc -a rm.signal.all+tlrc                                             \
       -b rm.noise.all+tlrc                                              \
       -expr 'a/b' -prefix TSNR.$subj


# --------------------------------------------------
# compute TSNR stats for dset labels: brain, MNI_2009c_asym

compute_ROI_stats.tcsh                                                   \
    -out_dir    tsnr_stats_regress                                       \
    -stats_file tsnr_stats_regress/stats_auto_brain.txt                  \
    -dset_ROI   mask_epi_anat.$subj+tlrc                                 \
    -dset_data  TSNR.$subj+tlrc                                          \
    -rset_label brain                                                    \
    -rval_list  1

compute_ROI_stats.tcsh                                                   \
    -out_dir    tsnr_stats_regress                                       \
    -stats_file tsnr_stats_regress/stats_auto_MNI_2009c_asym.txt         \
    -dset_ROI   ROI_import_MNI_2009c_asym_resam+tlrc                     \
    -dset_data  TSNR.$subj+tlrc                                          \
    -rset_label MNI_2009c_asym                                           \
    -rval_list  ALL_LT

# ---------------------------------------------------
# compute and store GCOR (global correlation average)
# (sum of squares of global mean of unit errts)
3dTnorm -norm2 -prefix rm.errts.unit errts.${subj}_REML+tlrc
3dmaskave -quiet -mask mask_epi_anat.$subj+tlrc                          \
          rm.errts.unit+tlrc > mean.errts.unit.1D
3dTstat -sos -prefix - mean.errts.unit.1D\' > out.gcor.1D
echo "-- GCOR = `cat out.gcor.1D`"

# ---------------------------------------------------
# compute correlation volume
# (per voxel: correlation with masked brain average)
3dmaskave -quiet -mask mask_epi_anat.$subj+tlrc                          \
          errts.${subj}_REML+tlrc > mean.errts.1D
3dTcorr1D -prefix corr_brain errts.${subj}_REML+tlrc mean.errts.1D


# create fitts from REML errts
3dcalc -a all_runs.$subj+tlrc -b errts.${subj}_REML+tlrc -expr a-b       \
       -prefix fitts.$subj\_REML

# create ideal files for fixed response stim types
1dcat X.nocensor.xmat.1D'[5]' > ideal_CONTROL.1D
1dcat X.nocensor.xmat.1D'[6]' > ideal_TASK.1D

# --------------------------------------------------
# extract non-baseline regressors from the X-matrix,
# then compute their sum
1d_tool.py -infile X.nocensor.xmat.1D -write_xstim X.stim.xmat.1D
3dTstat -sum -prefix sum_ideal.1D X.stim.xmat.1D

# ============================ blur estimation =============================
# compute blur estimates
touch blur_est.$subj.1D   # start with empty file

# create directory for ACF curve files
mkdir files_ACF

# -- estimate blur for each run in err_reml --
touch blur.err_reml.1D

# restrict to uncensored TRs, per run
foreach run ( $runs )
    set trs = `1d_tool.py -infile X.xmat.1D -show_trs_uncensored encoded \
                          -show_trs_run $run`
    if ( $trs == "" ) continue
    3dFWHMx -detrend -mask mask_epi_anat.$subj+tlrc                      \
            -ACF files_ACF/out.3dFWHMx.ACF.err_reml.r$run.1D             \
            errts.${subj}_REML+tlrc"[$trs]" >> blur.err_reml.1D
end

# compute average FWHM blur (from every other row) and append
set blurs = ( `3dTstat -mean -prefix - blur.err_reml.1D'{0..$(2)}'\'` )
echo average err_reml FWHM blurs: $blurs
echo "$blurs   # err_reml FWHM blur estimates" >> blur_est.$subj.1D

# compute average ACF blur (from every other row) and append
set blurs = ( `3dTstat -mean -prefix - blur.err_reml.1D'{1..$(2)}'\'` )
echo average err_reml ACF blurs: $blurs
echo "$blurs   # err_reml ACF blur estimates" >> blur_est.$subj.1D


# ---------------------------------------------------------
# QC: compute correlations with spherical ~averages
@radial_correlate -nfirst 0 -polort 4 -do_clean yes                      \
                  -rdir radcor.pb05.regress                              \
                  -mask mask_epi_anat.$subj+tlrc                         \
                  all_runs.$subj+tlrc.HEAD errts.${subj}_REML+tlrc.HEAD

# ========================= auto block: QC_review ==========================
# generate quality control review scripts and HTML report

# generate a review script for the unprocessed EPI data
gen_epi_review.py -script @epi_review.$subj \
    -dsets pb00.$subj.r*.tcat+orig.HEAD

# -------------------------------------------------
# generate scripts to review single subject results
# (try with defaults, but do not allow bad exit status)

# write AP uvars into a simple txt file
cat << EOF > out.ap_uvars.txt
  mot_limit          : 0.3
  out_limit          : 0.05
  copy_anat          : anatSS.sub-10785+orig.HEAD
  mask_dset          : mask_epi_anat.$subj+tlrc.HEAD
  template           : MNI152_2009_template_SSW.nii.gz
  ss_review_dset     : out.ss_review.$subj.txt
  max_4095_warn_dset : out.4095_warn.txt
  slice_pattern      : alt+z2
  vlines_tcat_dir    : vlines.pb00.tcat
EOF

# and convert the txt format to JSON
cat out.ap_uvars.txt | afni_python_wrapper.py -eval "data_file_to_json()" \
  > out.ap_uvars.json

# initialize gen_ss_review_scripts.py with out.ap_uvars.json
gen_ss_review_scripts.py -exit0        \
    -init_uvars_json out.ap_uvars.json \
    -write_uvars_json out.ss_review_uvars.json

# ========================== auto block: finalize ==========================

# remove temporary files
\rm -f rm.*

# --------------------------------------------------
# if the basic subject review script is here, run it
# (want this to be the last text output)
if ( -e @ss_review_basic ) then
    ./@ss_review_basic |& tee out.ss_review.$subj.txt

    # generate html ss review pages
    # (akin to static images from running @ss_review_driver)
    apqc_make_tcsh.py -review_style pythonic -subj_dir . \
        -uvar_json out.ss_review_uvars.json
    apqc_make_html.py -qc_dir QC_$subj

    echo "\nconsider running: \n"
    echo "   afni_open -b $subj.results/QC_$subj/index.html"
    echo ""
endif

# return to parent directory (just in case...)
cd ..

echo "execution finished: `date`"




# ==========================================================================
# script generated by the command:
#
# afni_proc.py -subj_id sub-10785 -script proc.sub-10785 -scr_overwrite                                        \
#     -blocks tshift align tlrc volreg mask blur scale regress -copy_anat                                      \
#     /data/NIMH_SSCC/rickr/UCLA.pamenc/AFNI/derivatives/AFNI_01_SSwarper/sub-10785/anatSS.sub-10785.nii       \
#     -anat_has_skull no -anat_follower anat_w_skull anat                                                      \
#     /data/NIMH_SSCC/rickr/UCLA.pamenc/AFNI/derivatives/AFNI_01_SSwarper/sub-10785/anatU.sub-10785.nii        \
#     -dsets                                                                                                   \
#     /data/NIMH_SSCC/rickr/UCLA.pamenc/pamenc.class.60.links/sub-10785/func/sub-10785_task-pamenc_bold.nii.gz \
#     -tcat_remove_first_trs 0 -tshift_opts_ts -tpattern alt+z2                                                \
#     -radial_correlate_blocks tcat volreg regress -align_unifize_epi local                                    \
#     -align_opts_aea -giant_move -cost lpc+ZZ -check_flip -tlrc_base                                          \
#     MNI152_2009_template_SSW.nii.gz -tlrc_NL_warp -tlrc_NL_warped_dsets                                      \
#     /data/NIMH_SSCC/rickr/UCLA.pamenc/AFNI/derivatives/AFNI_01_SSwarper/sub-10785/anatQQ.sub-10785.nii       \
#     /data/NIMH_SSCC/rickr/UCLA.pamenc/AFNI/derivatives/AFNI_01_SSwarper/sub-10785/anatQQ.sub-10785.aff12.1D  \
#     /data/NIMH_SSCC/rickr/UCLA.pamenc/AFNI/derivatives/AFNI_01_SSwarper/sub-10785/anatQQ.sub-10785_WARP.nii  \
#     -volreg_align_to MIN_OUTLIER -volreg_align_e2a -volreg_tlrc_warp                                         \
#     -volreg_compute_tsnr yes -mask_epi_anat yes -blur_size 6 -blur_in_mask                                   \
#     yes -regress_stim_times                                                                                  \
#     /data/NIMH_SSCC/rickr/UCLA.pamenc/AFNI/derivatives/AFNI_02_pamenc/sub-10785/timing/times.CONTROL.txt     \
#     /data/NIMH_SSCC/rickr/UCLA.pamenc/AFNI/derivatives/AFNI_02_pamenc/sub-10785/timing/times.TASK.txt        \
#     -regress_stim_labels CONTROL TASK -regress_stim_types AM1                                                \
#     -regress_basis_multi dmBLOCK -regress_motion_per_run                                                     \
#     -regress_censor_motion 0.3 -regress_censor_outliers 0.05                                                 \
#     -regress_compute_fitts -regress_fout no -regress_opts_3dD -jobs 8                                        \
#     -regress_3dD_stop -regress_reml_exec -regress_make_ideal_sum                                             \
#     sum_ideal.1D -regress_est_blur_errts -regress_run_clustsim no                                            \
#     -html_review_style pythonic