%% sub-function for extracting average betas for a range of ROIs on cluster
function get_uni(beta_dir, sub_roi_dir, rois, maps, tempath)

% iterate over ROIs and over maps per label
meanvals = NaN( 1, length( rois));
for n_roi = 1 : length( rois)
    for nmap = 1 : length( maps)
        fbeta   =  	fullfile( beta_dir, sprintf( 'beta_%04g.nii', maps(nmap)));
        fmask   =   fullfile( sub_roi_dir, sprintf( '%s.nii', rois{n_roi}));
        TS      =   cosmo_fmri_dataset( fbeta, 'mask', fmask);
        
        if nmap == 1
            DS  =   TS;
        else
            DS  =   cosmo_stack( {DS, TS}, 1);
        end
    end
    
    % remove NaNs, save average, and remove DS structs
    DS              =   cosmo_remove_useless_data( DS);
    meanvals(n_roi)  =   nanmean( DS.samples(:));
    clearvars DS TS
 
end % end of ROI loop

% save (temporary) results for current iteration
save( tempath, 'meanvals');

end % end of subfunction

