function out=legTrackerAlignBy(dataAll,target, windowSize)
%legTrackerAlignBy takes the output object of legTrackerClassifyRawData.m
%and a list of behavioral transitions, detects all instances of the
%behavioral transitions in the behavioral annotation sequence, and outputs
%windowSize*2 of the raw data and higher order features flanking the instances
%of those behavioral transition. This allows you to examine what, for
%example, a the x- component of a particular leg is doing during a behavioral
%transition of interest.
%Usage:
%out=legTrackerAlignBy(dataAll,target, windowSize)
%data = output object from legTrackerClassifyRawData.m
%target = n x 2 array of n transitions, each specified by a pair of label
%         numbers. E.g. [1 2; 1 3] indicates the 1 -> 2 and 1 -> 3 transitions.
%windowSize = the amount of flanking data before and after the transition
%         to be collected (in frames).


%initialize variables
vars=dataAll.data;
preds=dataAll.pred;
numPreds=size(preds,1);

%pad variable vectors and prediction sequence with windowSize zeros 
vars=[zeros(windowSize+1,size(vars,2));vars;zeros(windowSize+1,size(vars,2))];
preds=[zeros(windowSize+1,1);preds;zeros(windowSize+1,1)];

%determine max potential number of transitions in the data
tick=0;
for i=2:numPreds
    if preds(i)==target(2)
        tick=tick+1;
    end
end

%initialize collection variables based on max # of transitions
varStack=zeros(tick,2*windowSize+1,size(vars,2));
predStack=zeros(tick,2*windowSize+1);

tick=1;

%for all frames
for i=4:numPreds
    
    %if transition is observed over two frames pre- and post-
    if preds(i)==target(2) && preds(i-1)==target(2)  && preds(i-2)==target(1)  && preds(i-3)==target(1)
        %add the prediction sequence +/-windowSize frames to the collection variable
        predStack(tick,:)=preds(i-windowSize:i+windowSize)';
        %add the data variables sequence +/-windowSize frames to the collection variable
        varStack(tick,:,:)=vars(i-windowSize:i+windowSize,:);
        tick=tick+1;
    end
    
end

%remove excess zeros from collection variables
predStack(tick+1:end,:)=[];
varStack(tick+1:end,:,:)=[];

%output collection variables
out.predStack=predStack;
out.varStack=varStack;

%register all variables by subtracting their means within each transition-centered slice
for i=1:size(vars,2)
    out.varStack(:,:,i)=varStack(:,:,i)-repmat(nanmean(varStack(:,:,i),2),1,2*windowSize+1);
end

temp=[];

%optional visualization code:
%determine the frequency of each behavioral label frame by frame across the
%aligned windows
for i=0:11
    temp=[temp;sum(predStack==i)];
end
% display 
figure;
bar(temp','stacked');