function userFunctionBar(src,evnt,varargin) %#ok<INUSL>

%Handle to ScanImage
hSI = evnt.Source.hSI;  %#ok<NASGU> 

persistent hBar;
global meanRoisSaved_global;
norm =1;

switch evnt.EventName
    case {'focusStart' 'acqModeStart'}
         disp('Focusing');
        figure(989)
        clf(989)
        numRois = numel(hSI.hRoiManager.roiGroupMroi.rois);
        meanRois = zeros(numRois+1,1);
        hBar = bar(meanRois);
        yLimit = hSI.hChannels.channelLUT{1};
        ylim(yLimit);
        for i = numRois+1:-1:1
            text(i,double(yLimit(2))*0.9,'','HorizontalAlignment','center', 'FontSize', 16, 'Color',[.9 .9 .9])
        end
        set(gca,'Color', 'k')
        
    case 'frameAcquired'
         %disp('Frame');
         numRois = numel(hSI.hRoiManager.roiGroupMroi.rois);
         meanRois = zeros(numRois+1,1);
         numRSDB = length(hSI.hDisplay.rollingStripeDataBuffer);
         numRD = length(hSI.hDisplay.rollingStripeDataBuffer{1}{1}.roiData);
         for iRSDB = 1:numRSDB
             for iRD = 1:numRD
                 iRoi = (iRSDB-1)*numRD + iRD;
                 meanRois(iRoi) = mean(hSI.hDisplay.rollingStripeDataBuffer{iRSDB}{1}.roiData{iRD}.imageData{1}{1}(:))/hSI.hDisplay.displayRollingAverageFactor;
             end
         end
         meanRois(end) = mean(meanRois(1:numRois));
         if norm
             meanRois = meanRois./meanRoisSaved_global;
             yLimit = [.75, 1.25];
                  ch = get(gca,'Children');
            for i = 1:numRois+1
                set(ch(i),'Position',[i double(yLimit(2))*0.9])
                set(ch(i),'String',sprintf('%.3f',meanRois(i)))
            end
         else
            yLimit = hSI.hChannels.channelLUT{1};
            meanRoisSaved_global = meanRois;
                     ch = get(gca,'Children');
            for i = 1:numRois+1
            %    set(ch(i),'Position',[i double(yLimit(2))*0.9])
%                set(ch(i),'String',sprintf('%.0f',meanRois(i)))
            end
         end
         set(hBar,'ydata',meanRois);
         ylim(yLimit);
         %set(get(hBar,'Parent'),'ylim',(hSI.hChannels.channelLUT{1}));
         %sprintf('%.2f', meanRois(end))
    otherwise
        warning('Unexpected event ''%s'' processed by %s',eventName,mfilename);
end
