% For in vivo spine data analyzed using MapManager V_20171028 
% Author: Richard Roth (rhroth@stanford.edu)
% Date: October 2019
% Based on MapManager-Matlab-1.0.1-alpha by Robert Cudmore, 20171016

function retVal = segmentCall(myMapList, MapName, SegmentNumber, SessionConditions, StatName, channel, PersCond, MinSpines)

clear ps

ps = mmMap.defaultPlotStruct();
ps.stat = StatName;
ps.channel = channel;
ps.mapsegment = SegmentNumber;

ps.plotbad = false;
ps.plotintbad = false;
ps.ploterrorwarning = false;
ps.plotuserflag = false;

condList = SessionConditions;
numCond = length(condList);

i=find(strcmp({myMapList(:).mapName},MapName));
[m,~] = size(myMapList(i).objectRunMap);
ps.val = NaN(m,numCond);

 for k = 1:numCond
            currCond = condList{k};
            
            % condMean is single column of means across sessions
            % matching currCond (wildcard)
            currCondMean = myMapList(i).GetMapValuesCond(ps, currCond);
        
            ps.val(:,k) = currCondMean(:);
            ps.cond(:,k) = {currCond};
 end

% Remove values of spines that are present in less sessions than defined in PersCond
spinepersses =repmat(sum(~isnan(ps.val),2),1,numCond);
ps.val(spinepersses < PersCond) = NaN;

% Remove values from segments with less than MinSpines spines 
if max(sum(~isnan(ps.val),1))<MinSpines
    
retVal.values = NaN(1,numCond);
retVal.mean = NaN(1,numCond);
retVal.geomean = NaN(1,numCond);
retVal.count = NaN(1,numCond);
retVal.std = NaN(1,numCond);
retVal.se = NaN(1,numCond);   

else
retVal.values = ps.val;
retVal.mean = nanmean(ps.val,1);
retVal.geomean = nangeomean(ps.val,1);
retVal.count = sum(~isnan(ps.val),1);
retVal.std = std(ps.val,0,1,'omitnan');
retVal.se = retVal.std ./ sqrt(retVal.count);
end

