function rasterwrite(filename,X,Y,Z)

% write/export data to ESRI ArcGIS ASCII file
% 
% Syntax
%     
%     rasterwrite(filename,X,Y,Z)
%     rasterwrite(X,Y,Z)
%
% Description
%
%     rasterwrite writes a matrix to an ESRI ArcGIS ASCII file. X and Y 
%     are coordinate matrices as generated by meshgrid and must have  
%     same size as the data matrix Z (e.g. a digital elevation model). 
%     filename must be a string indicating the relative or absolute 
%     file path. rasterwrite opens a dialog box for saving files, if no
%     filename is supplied.
%
% See also: RASTERREAD
% 
% Author: Wolfgang Schwanghart (w.schwanghart[at]unibas.ch)
% Date: 15. March, 2009

narginchk(3, 4)

if nargin == 4;
    validateattributes(filename, {'char'}, {},'rasterwrite', 'filename')
else
    Z = Y;
    Y = X;
    X = filename;
    [FileName,PathName] = uiputfile({'*.txt';'*.asc'});
    if FileName == 0
        disp('     no output written to disk')
        return
    end
    filename = [PathName FileName];
end

siz = size(Z);
cellsize = Y(1)-Y(2);
nodata   = -9999;

if isvector(X)
    minx = min(X);
else
    minx = min(X(1,:));
end

if isvector(Y)
    miny = min(Y);
else
    miny = min(Y(:,1));
end


% write header
fid = fopen(filename,'w');
fprintf(fid,'ncols         %g\n',siz(2));
fprintf(fid,'nrows         %g\n',siz(1));
fprintf(fid,'xllcorner     %f\n',minx-abs(cellsize/2));
fprintf(fid,'yllcorner     %f\n',miny-abs(cellsize/2));
fprintf(fid,'cellsize      %g\n',abs(cellsize));
fprintf(fid,'NODATA_value  %g\n',nodata);
fclose(fid);

Z(isnan(Z)) = nodata;

if cellsize<0;
    Z        = flipud(Z);
end

dlmwrite(filename,Z,'-append', 'delimiter',' ');

