function struc=read_dat(fname)
% READ_DAT(fname) reads a space delimited numeric file with one header line.
%
% If "fname" is omitted the function will prompt for the input file.
%
% Read in a whitespace delimited ASCII numeric file with a one line     
% header of variable names. The file must have a variable name for each 
% column of numbers.  This script will create a structure of numeric    
% column vectors with each column using the corresponding name from the 
% header line.                                                          
%
% Many programs will create these files such as Excel (.txt or .prn)
% and PSI-Plot.
%
% Example input file:
%
%   rt.dat:
% t x v
%   0.00000000000E+00    3.96999999999E-02    0.00000000000E+00
%   5.00258517937E-04    3.99697150269E-02   -7.44753444412E+00
%   1.00272303185E-03    3.98886295490E-02   -5.93834113393E-01
%   2.00322475159E-03    3.99375098253E-02    1.31980134594E-05
%
% Example usage and output:
%
%   s=read_dat('rt.dat');
%   plot(s.t,s.x, s.t,s.v)
%
% or
%
%   s=read_dat

% David Edwards <david@btdt.org>    Sat Apr  9 15:28:43 PDT 2005
% Mon May  2 23:01:25 PDT 2005 (line 50: Print the selected file name)

if (nargin == 0)
    [fname,ppath] = uigetfile( ...
{'*.csv;*.txt;*.prn;*.dat', 'ASCII Files (*.csv, *.txt, *.prn, *.dat)'; ...
        '*.csv','Comma Separated Vectors (*.csv)'; ...
        '*.txt','Excel Text (tab delimited) (*.txt)'; ...
        '*.prn','Excel Formatted Text (space delimited) (*.prn)'; ...
        '*.dat','PSI Plot Text (*.dat)'; ...
        '*.*',  'All Files (*.*)'}, ...
        'Select an ASCII whitespace delimited numeric file');

    if (fname == 0)
        error('No file selected.');
    else
        fname=[ppath,fname];
        ['Selected file: ' fname]
    end
end

fid=fopen(fname, 'r');

% Read in the header line of variable names
var_names = fgetl(fid);

fclose(fid);

var_names = deblank(var_names);             % Remove trailing whitespace
var_names = regexprep(var_names,'^\s+',''); % Remove leading whitespace

% Load the string of variable names into a cell array
var_names=regexprep(var_names, '[,\s]+', ''','''); % t x-> t','x
var_names=['var_names={''', var_names, '''};'];
eval(var_names);

% Read the rest of the file into a matrix and convert to a cell array and
% then into a structure using var_names.
if (regexp(fname,'\.csv$'))
    mat = dlmread(fname,',', 1, 0);
else
    % Due to changes in dlmread betweeb MATLAB version 6 and 7...
    major_ver=version;
    major_ver=major_ver(1);

    if (eval(major_ver) < 7)
        mat = dlmread(fname,' ', 1, 0);
    else
        mat = dlmread(fname,'', 1, 0);
    end
end

[n,m]=size(mat);

% dlmread adds a column of zeros if there is extra white space after the
% last column of numbers. Therefore, only get Nvar columns.
Nvar = size(var_names,2);

if (m > Nvar)
    mat = mat(:,[1:Nvar]);
end

c=mat2cell(mat,n,ones(1,Nvar));
struc=cell2struct(c,var_names,2);