function writecsv(file,incell,writetype)
%writecsv(file,incell,writetype)
%
%This program takes a cell array(incell) and writes a comma seperated variable file
%at the location of file.  incell must not contain it's own cells (it must be flat) 
%INPUT
%file = the file location to save to
%incell = the cell array that contains the data to be written
%writetype = how the file should be opened, follows standard C/Matlab
%formats (a = append, w =write). If writetype is not given nargin < 3
%then the format is w
%
%OUTPUT
%A CSV text file 
%
%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

if nargin == 2
	writetype = 'w';
end

[rowincell colincell] = size(incell);
fid = fopen(file,writetype);

if fid == -1
	error(sprintf(...
	'Could not open and/or create file %s for writing.\n Folder exist? File open/locked in other program ?',file)); 
end
 
for k = 1:rowincell
    string = [];
    for m = 1:colincell
        temp = incell{k,m};
        if ischar(temp)
            string = [string temp];
        else
            string = [string num2str(temp)];
        end
        if m < colincell
            string = [string ',']; 
        end
    end
    fprintf(fid,'%s',string);
    fprintf(fid,'\n');
end
fclose(fid);