function matches=matchTrials(Inds,matchTypeInds,constVals)
%MATCHTRIALS    gets two vectors of trial indexes (Inds,matchTypeInds) and finds the closest match
% in matchTypeInds for each value in Inds. Output: matches is a vector in
% the size of 'Inds' with a matching trial's index from 'matchTypeInds' for each index in 'Inds'.

matches(1:length(Inds),1) = nan;

% make sure Inds and matchTypeInds are not empty
if ~isempty (Inds) && ~isempty (matchTypeInds)
    
    for ii = 1:length(Inds)% for each trial in Inds
        
        % find a matching (nearest) trial from matchTypeInds
        
        absVect = abs(matchTypeInds-Inds(ii));  % Abs. dist. values
        absMinVal = min(absVect);               % Minimal abs. dist
        minDistVect = (absVect == absMinVal);   % Which locations correspond to min.?
        match = find(minDistVect, 1, 'last');   % Return index of last match. in case of two possible matches,
        % (one would be before the current trial and one after, both with
        % same distance from the current trial), then the code will select the trial following the current trial.  
        
        % matching trial index
        matchTrialNum = matchTypeInds(match);
        matchDistance = absVect(match);
        
        if (matchDistance <= constVals.maxSearchDist)% ensure match is not greater than 5 trials from current trial
            matches(ii) = matchTrialNum;
        else
            matches(ii) = nan;
        end
            
    end
    
    
end
