function varargout=ADAlignTrials(AlignEv,bn,minTrTime,varargin)
% function varargout=ADAlignTrials(AlignEv,bn,minTrTime,varargin)
%
% Aligns AD data matrices on a given event during the trial.
% NOTE: This assumes a sampling rate of 1kHz for the AD Data, and that
% all the times in bn and minTrTime are in ms. Also Note- The times in
% AlignEv and bn and I think minTrTime too are assumed to be integers in
% the input. If they are not input this way, each will be rounded
% anyway. Both endpoints of bn are inclusive, so for example if you ask
% to align from -5 to +5 ms from a given event, this will output 11
% samples as it also assumes that everything is at 1 kHz.
%
% Example of how this is called:
% [AlX,AlY]=ADAlignTrials(LastLeaveFix_,[-300 300],0,EyeX_,EyeY_);
%
% For every input AD data matrix in the varargin (nTr x nSampsPerTrial),
% this outputs the data in the corresponding in order in varargout in the
% same format but aligned on AlignEv (nTr x 1), a vector of event times
% in ms to align to. bn is a 1x2 matrix of the minimum and maximum times
% to output relative to AlignEv, such that the outputs in varargout will
% be of size (nTr x bn(2)-bn(1)+1). minTrTime is the time relative to
% TrialStart_ (or conceivably some other event) of the first time sample
% in the input AD matrix in varargin. It's important that minTrTime and
% AlignEv are referenced to the same event, typically TrialStart_.
%
% This doesn't use a big for loop (across trials) and so should be fairly
% quick.
%
% Note: to plot this as an individual trace for each trial, all on one
% graph, it's simply- plot([bn(1):bn(2)],OutArg);
%
% ***************** This will run into trouble if there are NAN's in your AlignEv... If
% you run into trouble with this, that's a likely culprit
%
% written 070711 by MJN
if nargin<4 error(['nargin is only: ' num2str(nargin) '. You need at least 4 arguments.']); end
AlignEv=round(AlignEv); bn=round(bn); minTrTime=round(minTrTime);
if size(AlignEv,1)>size(AlignEv,2) AlignEv=AlignEv'; end
maxTrTime=minTrTime+size(varargin{1},2)-1;
nTrs=length(AlignEv);
TimeLims=minmax(AlignEv)+bn;
FrontPad=min([minTrTime TimeLims(1)]);
EndPad=max([maxTrTime TimeLims(2)]);
tmpnsamps=EndPad-FrontPad+1;
if FrontPad<minTrTime disp('Warning- bn(1) went before AD sample for some trials. Padding beginning of these with NaN''s'); end
if EndPad>maxTrTime disp('Warning- bn(2) went beyond AD sample for some trials. Padding ends of these with NaN''s'); end
t=repmat([FrontPad:EndPad]',1,nTrs)-repmat(AlignEv,tmpnsamps,1);
for iAD=1:nargin-3
curAD=varargin{iAD}';
if FrontPad<minTrTime
curAD=[NaN*ones(minTrTime-FrontPad,nTrs); curAD];
end
if EndPad>maxTrTime
curAD=[curAD; NaN*ones(EndPad-maxTrTime,nTrs)];
end
varargout{iAD}=reshape(curAD( t>=bn(1) & t<=bn(2) ),bn(2)-bn(1)+1,nTrs)';
end