% 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

% Used for NearesNeighbor.m and getmyMapListValuesCondDist_Neighbour.m

function [retVal,retValDist] = segmentCall(myMapList, MapName, SegmentNumber, SessionConditions, StatName, SecStatName, SecStatChannel, PersCond, MinSpines)


clear ps

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

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


psDist = ps;
psDist.stat = SecStatName;


condList = SessionConditions;
numCond = length(condList);

i=find(strcmp({myMapList(:).mapName},MapName));
[m,~] = size(myMapList(i).objectRunMap);
ps.val = NaN(m,numCond);
psDist.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);
            currdistCondMean = myMapList(i).GetMapValuesCond(psDist, currCond);
        
            ps.val(:,k) = currCondMean(:);
            ps.cond(:,k) = {currCond};
            psDist.val(:,k) = currdistCondMean(:);
            psDist.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;
psDist.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);  

retValDist.values = NaN(1,numCond);
retValDist.mean = NaN(1,numCond);
retValDist.geomean = NaN(1,numCond);
retValDist.count = NaN(1,numCond);
retValDist.std = NaN(1,numCond);
retValDist.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);

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

