function  [trials,lags] = prior_repetition(data)

% PRIOR_REPETITION  --  Time (and lag) of the most recent repeated stimulus.
%
% trials = prior_repetition(data)
% [trials,lags] = prior_repetition(data)
%
% DATA is a stimulus matrix; each column is treated separately.
% TRIALS is the trial (=row) number of the most recent identical stimulus.
% If this is the first occurence of a particular stimulus value, TRIALS = 0.
% LAGS = (ROW_NO - TRIALS)  -- time since most recent repetition.
%
% Example:
%   data = [-1 0 -1 1 0 1 1 -1 -1 0]' ; 
%   [trials,lags] = prior_repetition(data) ; [1:10;data';trials';lags']
% ans =  1   2   3   4   5   6   7   8   9  10
%       -1   0  -1   1   0   1   1  -1  -1   0     % data'
%        0   0   1   0   2   4   6   3   8   5     % trials'
%        1   2   2   4   3   2   1   5   1   5     % lags'
% 
% See also SPLIT, AGGREG.

% Original coding by Alex Petrov, Ohio State University
% $Revision: 1.0 $  $Date: 2001/02/06 12:10 $
%
% Part of the utils toolbox version 1.1 for MATLAB version 5 and up.
% http://alexpetrov.com/softw/utils/
% Copyright (c) Alexander Petrov 1999-2006, http://alexpetrov.com
% Please read the LICENSE and NO WARRANTY statement in ../utils_license.m

[N_trials,N_sbj] = size(data) ;
time_line = [1:N_trials]' ;

trials = zeros(N_trials,N_sbj) ;
for k = 1:N_sbj
  x = [data(:,k) time_line] ;      % [stim trial_no]
  x = sortrows(x,1) ;              % group identical stimuli together
  sort_stim = x(:,1) ;
  sort_tr = x(:,2) ;
  prev_tr = [0 ; sort_tr(1:N_trials-1)] ;  % time of previous sorted stimulus
  transitions = [1 ; sign(sort_stim(2:N_trials)-sort_stim(1:N_trials-1))] ;
  first_occurrences = find(transitions==1) ;
  prev_tr(first_occurrences) = 0 ;     % 0 by convention
  trials(sort_tr,k) = prev_tr ;
end

if (nargout > 1)   % if LAGS requested
  lags = repmat(time_line,1,N_sbj) - trials ;
end

%--- Return TRIALS and, possibly, LAGS
%%%%% End of PRIOR_REPETITION.M
