function  handles = gtMatchUpdateUsedReflections(handles,flag)

% Updates theta table in the main GUI when a phase is (de)selected.
% Use flag=1, if there has been a change in used phases or lattice parameters. 

% Reflection data in this macro is sorted in 3 different sets:
%  'all'   : all reflections for the active phases
%  'Sorted': 'all' sorted in ascending order
%  'Unique': 'sorted' uniqued and sorted in ascending order
%  'Used'  : those of unique which have been ticked
%

% If the active phases have changed
if flag
    
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% Sorted reflections
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    
    % Collect reflections from all used phases
    allthetas     = [];
    allphasetypes = [];
    allhkls       = [];
    allthetainds  = [];
    allints       = [];
   
    for ip = handles.UsedPhases
        allthetas     = [allthetas, handles.CompPhaseThetas{ip}];
        allphasetypes = [allphasetypes, repmat(ip,1,length(handles.CompPhaseThetas{ip}))];
        allhkls       = [allhkls, handles.CompPhaseHKLs{ip}];
        allthetainds  = [allthetainds, handles.CompThetaIndices{ip}];
        allints       = [allints, handles.CompIntensities{ip}];
    end
    
    % Arrange thetas in ascending order, record phase type:
    [handles.SortedThetas,theta_ind] = sort(allthetas);
    handles.SortedPhaseTypes   = allphasetypes(theta_ind);
    handles.SortedThetaIndices = allthetainds(theta_ind);
    handles.SortedHKLs         = allhkls(:,theta_ind);
    handles.SortedIntensities  = allints(theta_ind);
   
    
    % Create table content of active phases
    thetatable = cell(length(handles.SortedThetas),6);
    
    for ii = 1:length(handles.SortedThetas)
        
        thetatable{ii,1} = handles.SortedThetas(ii);
        
        thetatable{ii,2} = ['   ', handles.PhaseNames{handles.SortedPhaseTypes(ii)}];
 
        thetatable{ii,4} = handles.SortedIntensities(ii);
        
        thetatable{ii,6} = handles.CompThetasTicked{...
            handles.SortedPhaseTypes(ii)}(handles.SortedThetaIndices(ii));
        
        hkltext = num2str(handles.SortedHKLs(:,ii)');
        hkltext(hkltext==' ') = [];
        hkltext = ['   {', hkltext, '}'];
        thetatable{ii,3} = hkltext;
        
    end
    
    
    % Warning in table if a theta value belongs to more than one reflection
    % or phase
    for it = 1:length(handles.SortedThetas)
        wt = find(abs(handles.SortedThetas(it)-handles.SortedThetas)<=handles.ThetaUniqueTol);
        if length(wt) > 1
            thetatable{it,5} = '  !! ';
        else
            thetatable{it,5} = ' ';
        end
    end
    
    set(handles.Theta_Table,'Data',thetatable)
    
    gtMatchUpdateThetaMarkers(handles,'select');

    
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %% Lattice parameters table
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    
    if isempty(handles.UsedPhases)
        tablesize = size(handles.LatticeParTable(:,:,1));
        set(handles.LattPars_Table,'Data',cell(tablesize));
    else
        ph = handles.UsedPhases(get(handles.Phases_Listbox_Active,'Value'));
        set(handles.LattPars_Table,'Data',handles.LatticeParTable(:,:,ph));
    end

end
 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Used reflections
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Collect reflections from all used phases
allthetas     = [];
allphasetypes = [];
allhkls       = [];
allthetainds  = [];

for ip = handles.UsedPhases
    allthetas     = [allthetas, handles.CompPhaseThetas{ip}(handles.CompThetasTicked{ip})];
    allphasetypes = [allphasetypes, repmat(ip,1,sum(handles.CompThetasTicked{ip}))];
    allhkls       = [allhkls, handles.CompPhaseHKLs{ip}(:,handles.CompThetasTicked{ip})];
    allthetainds  = [allthetainds, handles.CompThetaIndices{ip}(handles.CompThetasTicked{ip})];
end


% Find unique thetas in ascending order (NaNs ignored), record phase type:
[handles.UsedThetas,theta_ind] = gtMathsUniqueTol(allthetas,handles.ThetaUniqueTol,0);
handles.UsedPhaseTypes   = allphasetypes(theta_ind);
handles.UsedThetaIndices = allthetainds(theta_ind);
handles.UsedHKLs         = allhkls(:,theta_ind);
handles.UsedHKLUnique    = false(1,length(theta_ind));

% If a theta value belongs to more than one reflection or phase,
% it cannot be identified in matching, so set these to NaN.
for it = 1:length(handles.UsedThetas)

    % Indices with the same thetas
    wt = abs(handles.UsedThetas(it)-allthetas) <= handles.ThetaUniqueTol;

    if sum(wt) > 1    
        handles.UsedHKLUnique(it) = false;
    else
        handles.UsedHKLUnique(it) = true;
    end

    % If they belong to more than one phase
    if length(unique(allphasetypes(wt))) > 1    
        handles.UsedPhaseTypes(it) = NaN;
        handles.UsedHKLs(:,it)     = NaN;
    end
end










