function ok = gtIndexCheckAllPairCons(act, cand, tol, samenv, ACM)
% GTINDEXCHECKALLPAIRCONS All positive pair consistency check.
%
% ok = gtIndexCheckAllPairCons(act, cand, tol, samenv, ACM)
%
% ---------------------------------------------------------
%
% Checks whether all reflections in 'cand' are pair consistent with 'act'.
%
% INPUT
%   act.    - the actual reflection data to be tested against
%   cand.   - candidate reflections to be tested 
%   tol.    - tolerances
%   samenv  - sample envelope
%   ACM     - angular consistency matrix
%
% OUTPUT
%   ok      - binary value; true if all candidates are pair consistent
%


ok = false;


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Check meta-data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Bbox y size close enough?
cons = (act.bbys/tol.bbys < cand.bbys) & (cand.bbys < act.bbys*tol.bbys);
if ~all(cons)
	return
end

% Bbox x size close enough?
cons = (act.bbxs/tol.bbxs < cand.bbxs) & (cand.bbxs < act.bbxs*tol.bbxs);
if ~all(cons)
	return
end

% Integrated intensities close enough?
cons = (act.int/tol.int < cand.int) & (cand.int < act.int*tol.int);
if ~all(cons)
	return
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Check distance and location
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Spatial distance small enough?
cons = gtMathsLinesDists([act.ca act.dir],[cand.ca cand.dir]) < tol.dist;
if ~all(cons)
	return
end

% Is the intersection point in the sample volume?
%
% NOTE: the intersection of 2 diff. paths might actually be far from 
% the grain center if they are near being parallel. This could be taken 
% into account here, however, there should be no parallel diff. paths 
% in a grain set.

pofinters = gtMathsLinePairsIntersections([act.ca act.dir],[cand.ca cand.dir]);
cons      = gtIndexIsPointInSample(pofinters,samenv);

if ~all(cons)
	return
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Check angle
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Angles between plane normals consistent?

cons = false(size(cand.pl,1),1);

% Angular tolerance in radians
tol_ang_rad = tol.ang*pi/180;

% Angular consistency matrix; hklind{} may have more than one element !
ACM_reduced = ACM(act.hklind{1},:);

% Angle between actual and candidates
ang = gtMathsVectorsAnglesRad(act.pl, cand.pl, 0);  

% !!! This could be a parfor loop! But may be too short.
for ii = 1:size(cand.pl,1)
  ACV = ACM_reduced(:,cand.hklind{ii});
  ACV = vertcat(ACV{:});
  cons(ii) = min(abs(ACV - ang(ii))) < tol_ang_rad;  
end

if ~all(cons)
	return
end


% All pairs are consistent
ok = true;


end % of function