function [neworder,cations,weights] = PrepWeightsandCationsOrder(sumcations,sumweights,sumorder,theindex)
%[neworder,cations,weights] = PrepWeightsandCationsOrder(sumcations,sumweights,sumorder,theindex)
%The purpose of this function is to establish a mapping of the order between the in input data 
%and the order required my the background information
%
%INPUT
%sumcations = a cell array that contains the cation values for all of the mineral models
%sumweights = a cell array that contains the weight values for all of the mineral models
%sumorder = a cell array that contains the order of the input data
%theindex = a scaler that contains the index into the above three inputs for the
%case that is currently being considered
%
%OUTPUT
%neworder = the mapping between the input data and that required by the background
%cations = the cation data for this case
%weights = the weight data for this case
%
%Written by K. Steffen (ksteffen@unm.edu) at the University of New Mexico,
%Department of Earch and Planetary Science
%Copyright 2003 Kurt Steffen

if length(sumorder) > 1
	cations = sumcations{theindex};
	weights = sumweights{theindex};
	order = sumorder{theindex};
else
	cations = [sumcations{:}];
	weights = [sumweights{:}];
	order = sumorder{1};
end

[crap thelength] = size(weights);
neworder = cell(1,thelength);

for k = 1:thelength
	temp = find([order{2,:}] == k);
	if ~isempty(temp)
		neworder(k) = order(1,temp);    
	end
end
    
for k = thelength:-1:1
	if isempty(neworder{k})
		neworder(k) = [];
		cations(k) = [];
		weights(k) = [];
	end
end