function b= modeanalysis(a,MineralList,controlstruct)
%b= modeanalysis(a,MineralList,controlstruct)
%This program does a modal analysis on the raw data (a).  First column
%of output is the name of each phase identified.  The second column
%is the number of times that phase appears in this set of analysis.
%The third column is the mode in percent of each phase. The 
%fourth column is the indices of the occurance of each phase (a vector
%of integers).
%modeanalysis sends this information to the screen and also saves this information
%to output directory as "Mode.csv".  The .csv also has a list of the indices for
%each mineral appended to row, so if the number column for garnet is 10 there will be
%10 extra integers on the row that corraspond to the indices in the original data
%that corraspond to garnet.
%
%INPUT
%a = the output of thefinder.m, the raw data;
%MineralList = a structure array that contains the data order and positions for
%the raw data (a)
%controlstruct = the structure that contains the basic information to run APHID,
%created in APHIDengine.m
%
%OUTPUT
%b = the output as a cell array (described above) 
%
%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 17, 2003

	if isempty(MineralList)  %Making sure some analysis have been identified
		error('Can not run Modal Analysis as no minerals were identified');
	end
	nameposition = MineralList(1).MineralNameLocation;
	b = [{'Mineral'} {'Number'} {'Percent'} {'Indices'}];
	numberofanalysis = length(a);
	lengthb = 2;
	for k = 1:numberofanalysis %looping through all the analysis 
		test = strcmp(b(:,1),a{k}{nameposition});
		test = find(test == 1);
		if isempty(test) % if this mineral has not been seen before then add to list
			b(lengthb,1) = a{k}(nameposition);
			b(lengthb,2) = {0};
			b(lengthb,3) = {0};
			b(lengthb,4) = {k};
			test = lengthb;
			lengthb = lengthb + 1;
		else %or else add the occurance to the list for the proper mineral 
			temp = b{test,4};
			temp = [temp k];
			b(test,4) = {temp};
		end
		b(test,2) = {b{test,2} + 1};        
	end
	%determining the percentages 
	totals = [b{2:end,2}];
	sumtotals = sum(totals);
	totals = (totals/sumtotals)*100;
	for k = 1:length(totals)
		b(k+1,3) = {totals(k)};
	end 
    	outcell = b;
	for k = 1:lengthb-2
		number = b{k+1,2};
		for m = 1:number
			outcell(k+1,3+m) = {b{k+1,4}(m)};
		end
	end 
	
	%printing results to screen
	disp('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%');
	disp('Modal Analysis');
	disp([b(:,1:3)]);
	file = [controlstruct.savefile filesep 'Mode.csv'];
	displaystring = sprintf('Modal Analysis information saved at %s\n\n',file);
	disp(displaystring);
	writecsv(file,outcell); %writing results to a CSV file
	disp('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%');