function data = fileread4(file,delimiter)
%function data = fileread4(file,delimiter)
%reads formated data from file and outputs into a cell array
%the data can include numbers and charactar strings
%No data will be read after a % (percent sign) in a line (matlab style comments)
%INPUT
%file = the file to be read
%delimiter = the charectar the delimits the data (the default is '')
%
%OUTPUT 
%data = a cell array that contains doubles and strings
%
%
%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 13, 2003

    if nargin == 1
        delimiter = ' ';
    end
    fid = fopen(file,'r'); %opening file and checking 
    if fid == -1
        tempstring = ['File ' file ' can not be found'];
        error(tempstring);
    end
    data = cell(1);
    count = 1;
    string = [];
    m = 1;
    line = fgetl(fid); %is the file empty
    anypercent = findstr(line,'%');
    
    if ~isempty(anypercent)
    line = line(1:anypercent(1)-1);    
    end
    if line == -1
       data = [];
       return
    end
    while line ~= -1
		if strcmp(line(1),'%') == 0
			for k = 1:length(line)
				if k == length(line) %at the end of the line 
					string = [string line(k)];
					if isnan(str2double(string))
						data(m,count) = {string};
					else %if it is a number convert to string 
						data(m,count) = {str2double(string)};
					end
					string = [];
					count = 1;
				elseif line(k) == delimiter %ran into a delimiting charector 
					if isnan(str2double(string))
						data(m,count) = {string};
					else %if it is a number convert to string 
						data(m,count) = {str2double(string)};
					end
					count = count + 1;
					string = [];
				else
					string = [string line(k)]; %otherwise add charector to string 
				end
			end
			m = m +1;
        end 
        line = fgetl(fid); % get the next line 
    end
    fclose(fid); %closing file 