Coding for **By trial group (folder average)**

You have two possible approaches:

1 - Within your process: Add a classification of the input files in multiple groups (by folder) to be processed separately. You can call directly the sorting function from process_average.

% Group files
avgtype = 3;
[iGroups, GroupComments] = process_average('SortFiles', sInputs, avgtype);
% Average each group
for i = 1:length(iGroups)
    % Your code, adapted from lines 175-190 of process_average.m
end

This solution would be easy to add to your current process function. If you select this option, then I recommend you keep all the possible options available for avgtype in process_average. If you implement only what you need (ie. avgtype=3), it would be more difficult to share your process with other users, as they might not expect it to run ONLY in one configuration (per folder and per subject).

2 - The other option is to keep your process as it is (processing all the input files together at once), and write a script that calls in a loop. Your script would loop over subjects and folders in your database, search all the data files in each subject/folder, and call the process on it.
This would require a bit more reading about Brainstorm scripting and database requests: