%% Get forward - feedback ROIs

function relativeOrder = get_forward_feedback_ROIs(computedROIs,ordered_rois)
% Given a set of ROIs names (computedROIs --> cell array) and the ROIs
% labels ordered according to the heirarchy (ordered_rois) this function
% computes the relative position of all the ROIs in the selected set w.r.t.
% all other ROIs in the set
%
% E.g. 
% relativeOrder.IP0.labels.feedback is a cell array with the labels of all the selected ROIs preceding IP0 in the hierarchy
% relativeOrder.IP0.idxs.feedback is an array with the idxs of all the selected ROIs preceding IP0 in the hierarchy

for XroiIdx = 1:numel(computedROIs)
    countFwd = 0;
    countFbk = 0;
    
    tmpIdxs = 1:numel(computedROIs);
    tmpIdxs(XroiIdx)=[];
    XroiLab = computedROIs{XroiIdx};
    XhierarchyIdx = find(strcmp(ordered_rois,XroiLab));
    
    for YroiIdx=tmpIdxs
        YroiLab = computedROIs{YroiIdx};
        YhierarchyIdx = find(strcmp(ordered_rois,YroiLab));
        
        if XhierarchyIdx < YhierarchyIdx
            countFwd = countFwd+1;
            relativeOrder.(matlab.lang.makeValidName(XroiLab)).labels.forward{countFwd} = YroiLab;
            relativeOrder.(matlab.lang.makeValidName(XroiLab)).idxs.forward(countFwd) = YroiIdx;
        elseif XhierarchyIdx > YhierarchyIdx
            countFbk = countFbk+1;
            relativeOrder.(matlab.lang.makeValidName(XroiLab)).labels.feedback{countFbk} = YroiLab;
            relativeOrder.(matlab.lang.makeValidName(XroiLab)).idxs.feedback(countFbk) = YroiIdx;
        end
    end
end

end