function [thenewlabels,newdata,extradata,extralabel] = loadtext(controlstruct,elements)
%[thenewlabels,newdata,extradata,extralabel,elements] = loadtext(controlstruct,elements)
%The purpose of loadtext is to read the input analysis file and produced formatted output for 
%the APHID program.
%INPUT
%controlstruct =  a structure that contains the basic information required to run APHID
%loadtext specifically needs the name of the inputfile
%elements = a cell array of strings that provides the names of the elements that APHID expects to 
%receive from the data file. loadtext returns an error if all of these elements are not present 
%in the input file
%
%OUTPUT
%thenewlabels = the column labels of the output data.  These will be the same as the elements input
%a cell array of strings
%newdata = a double array which is the compositional data that will be used by APHID.  The rows
%are the individual analysis and the columns are the elements
%extradata = a cell array that contains the data from any columns in the input file that were
%not specifically requested by APHID.  This data is retained and output by APHID for possible
%use in post-processing
%extralabel = a cell array of strings that contains the labels of the extra data
%
%Written by K. Steffen (ksteffen@unm.edu) at the University of New Mexico,
%Department of Earch and Planetary Science and copyrighted under the GNU
%public license, see APHID.m and www.gnu.org for details
%
%Last Modified June 13, 2003


	[thelabels data] = GetData(controlstruct.infile,',',1);  %loads the input data and seperates label row   
    
	[rowsdata colsdata] = size(data);
	lengthelement = length(elements);
	extradata = cell(0);
	extralabel = cell(0);

	numberout = length(elements);
	thenewlabels = elements;
	try  %finding the columns in the data that corraspond to the columns in elements
		thenewlabels = GetColumnsGeneral(thelabels,thenewlabels);
	catch %if all of these elements are not included in the data file then produce a detailed error message
		temp = GetColumnsGeneral3(thelabels,thenewlabels);
		whichbad = find([temp{2,:}] == -1);
		bad = temp(1,whichbad);
		errorstring = [];
		for k = 1:length(bad)
			errorstring = [errorstring ' ' [bad{k}]]; 
		end
		errorstring = ['The Components ' errorstring ' from backgroundfile ' controlstruct.backgroundfile ' are not found in datafile ' controlstruct.infile];
		error(errorstring);
	end
    
	for k = 1:numberout  %ordering the data into the order of elements
 		newdata(:,k) = data(:,thenewlabels{2,k}); 
	end
    
	%producing the extra data	
 	counter = 1;
 	for k = 1:colsdata
 		test = 0;
		for m = 1:lengthelement
			if thenewlabels{2,m} == k
				test = 1;
			end
		end
            
		if test == 0
			extralabel(counter) = thelabels(k);      
			extradata(:,counter) = data(:,k);
			counter = counter + 1;
		end
	end
	thenewlabels = thenewlabels(1,:);
	newdata = cell2double(newdata);