function z = loaddoc(filename,ncol)
%Data = LOADDOC(Filename,Ncol) Load data from ASCII file with documentation.
%  This program loads data from an ASCII file into a workspace variable
%  (Data) where the data are preceded by an alpha-character header section
%  consisting of comment records that begin with '%'. This allows the user
%  to document the structure, origin, units, etc. of the data and still be
%  able to load the included data as a Matlab matrix variable. 
%
%  Usage:  Data=LOADDOC(Filename,Ncol)
%
%  Input arguments:
%      Filename = 'name_of_the_file'
%      Ncol     = number of columns in data matrix (optional)
%
%  Output argument:
%      Data = data vector or array
%
%  Warnings:
%  1) The program must be informed of the data matrix structure. i.e., the
%     number of columns in the data array (Ncol). This may be passed
%     as an input parameter as shown above. If it is not passed (optional),
%     then following the display of documentation, the user will be asked
%     to input the number of columns. Obviously, it is wise to include this
%     structural information in the comment records.
%
%  2) The data file has to be somewhere within the path of MATLAB.
%
%  3) Filename handling & input/output works for Macintosh. The program
%     may require modification to work on other platforms.
%
%  4) Large files may give memory limit errors, since string conversion 
%     multiplies the number of array elements used.
%
%  Written by D.Enfield, NOAA Atlantic Oceanographic and Meteorological
%  Laboratory, Miami, Florida. Internet: enfield@aoml.erl.gov
%
%  See also: LOAD, LOADASC

% Open and read file to an ASCII string
fid=fopen(filename,'r');
eval('strg=setstr(fread(fid,inf,''uchar''));')
fclose(fid);
strg=[strg(:)',setstr(13)];               % Convert to a row vector
idx=find(strg==setstr(10));               % Find line feeds, if any
strg(idx)=setstr(13*ones(length(idx),1)); % Eliminate LFs (leave CRs)

% Display and eliminate comment records
idx=find(strg=='%');                      % Find comment records
doc='';                                   % Initialize DOC string
for i=length(idx):-1:1 
 pcr=idx(i)+min(find(strg(idx(i)+1:length(strg))==setstr(13)));
 doc=[strg(idx(i)+1:pcr) doc];         % Add comment to DOC
 strg(idx(i):pcr)=[];                  % Chop comment from string
end 
doc=[setstr(13) doc];
disp(doc)                                 % Display comments (DOC)

% If Ncol not passed, query user for input
if nargin < 2
 ncol=input('Number of data columns = ');
end
data=sscanf(strg,'%f');                   % Convert from string to data

% Reconfigure data vector to specified matrix structure
if rem(length(data),ncol)~0; disp('Data matrix not square'); return;end
nrow=length(data)/ncol;                   % Find the number of rows
z=zeros(nrow,ncol);                       % Preallocate output array
for j=1:nrow
 j1=(j-1)*ncol+1;j2=j*ncol;
 z(j,:)=data(j1:j2,:)';
end
 

