function [Additive,OutofLimits] = Cations2Additive(order,cations,MineralStruct,m,controlstruct)
%[Additive,OutofLimits] = Cations2Additive(order,cations,MineralCell,m,controlstruct)
%The purpuse of this code is to convert cation components to additive/exchange components.
%In addition this code determines if the the additive/exchange components are within the 
%limits of what could typically be expected for this mineral 
%INPUT 
%order = contains the order of data expected by the matrix A (cell array)
%cations = the input cations 
%MineralStruct = The ouput of CreateMineralCell.m which contains background info 
%for transformation (cell array)
%m = the column of MineralCell that contains the data for the mineral to be considered
%controlstruct = The output of CreateInputStuct.m that contains all optional information
%
%OUPUT
%Additive = The additive components in the order dictated by A (double vector)
%OutofLimits = Are the additive/exchange components outside a range typically expected for 
%this mineral 
%
%Written by K. Steffen (ksteffen@unm.edu) at the University of New Mexico,
%Department of Earch and Planetary Science
%Copyright 2003 Kurt Steffen
%
%Last Modified June 17, 2003


    A = MineralStruct(m).A; %laoding data 
    [rowA colA] = size(A);
    D = MineralStruct(m).D;
    Limits = MineralStruct(m).Limits;
        
    ordertemp = [order{2,:}]; %conversion from cations to additive/exchange
    input = cations(ordertemp); %placing in order for A matrix 
    if ~isempty(A) 
        Additive = (diag(D')*A)\(input.*D')';
    else
        Additive = -1;
    end
    
    if ~isempty(Limits) %checking limits 
        OutofLimits = 0;
        Limit = find(Additive' <= Limits(1,:) & Additive' > Limits(2,:));
        if length(Limit) < colA
            OutofLimits = 1;
        end
    else
        OutofLimits = 1;
    end