function [Xv, Yv, Zm] = readgrd(FileName)
% READGRD   - Read Ascii grid data from SURFER
%
% Use As:   [Xv, Yv, Zm] = readgrd('FileName')
%        or [Xv, Yv, Zm] = readgrd 
%
% Inputs: FileName = String containing the name of the ASCII Grid
%                    Data file from Golden Software's Surfer
%
% Output: Xv = Vector specifying X coordinates
%         Yv = Vector specifying Y coordinates
%         Zm = Matrix with nodes specfied by Xv and Yv containing Z data
%

% B. Schlining
% 05 Aug 1997
% 08 Jan 1998;B.S.; Cleaned up and added if infile == 0

%===========
% Open File
%===========
if ~nargin
   [infile inpath] = uigetfile('*.grd','Select Ascii grid file',0,0);
   if infile == 0
      Xv = [];
      Yv = [];
      Zm = [];
      return                            % Return if CANCEL is selected
   end
   FileName = [inpath infile];
end

%===========
% Read File
%===========
fid    = fopen(FileName,'r');				 % Open File
TrashS = fgetl(fid);							 % The first line is header info
BufS   = fgetl(fid);							 % Second line is [#Xlines #Ylines]
Size   = sscanf(BufS,'%f',2);		
BufS   = fgetl(fid);							 % Third line is [min(X) max(X)]
X      = sscanf(BufS,'%f',2);		
Xint   = (X(2) - X(1))/(Size(1) - 1);	 % Calculate the X interval
Xv     = [X(1):Xint:X(2)]';		       % Create a vector of X values
BufS   = fgetl(fid);		              	 % Forth line is [min(Y) max(Y)]
Y      = sscanf(BufS,'%f',2);
Yint   = (Y(2) - Y(1))/(Size(2) - 1);	 % Create the Y interval
Yv     = [Y(1):Yint:Y(2)]';	        	 % Create a vector of Y values
BufS   = fgetl(fid);		              	 % Fifth line is [min(Z) max(Z)]
Z      = sscanf(BufS,'%f',2);           % Z is not used
Zv     = fscanf(fid,'%f');              % Read the rest of the file
Zm     = reshape(Zv,[Size(1) Size(2)])';% Orient the matrix correctly

fclose(fid);                            % Close the fid
