function X = readfsi(filename)
% READFSI   - Read FSI data files
%
% NOTES: The FSI test file had occasional 'weird' characters at the 
% start of some lines. If an error message pops up saying 'Unable to parse string ...'
% its probably becuase of this. To fix the data file go to the line specified in the 
% error message and delete the first character. 

% Brian Schlining
% 24 Jul 2000

%===========
% Open File
%===========
if ~nargin
   [infile inpath] = uigetfile('*.*','Select FSI data file',0,0);
   if infile == 0
      y = [];
      return                            % Return if CANCEL is selected
   end
   filename = [inpath infile];
end

fid  = fopen(filename,'rt');
if fid < 0
   error(['Unable to open file ' filename])
end

n = 100000;
timeBuf = cell(n,1);
X.time = ones(n,1)*NaN;
X.lat = ones(n,1)*NaN;
X.lon = ones(n,1)*NaN;
X.depth = ones(n,1)*NaN;
X.data = ones(n, 1)*NaN;

fprintf(1, 'Reading %s...', filename);
n = 0;
m = 0;
while ~feof(fid)
   s = fgetl(fid);
   m = m + 1;
   if ~isempty(s)
      n = n + 1;
      try 
         timeBuf{n} = stringtokenizer(s, 4, ',');
         X.lat(n) = sscanf(stringtokenizer(s, 8, ','), '%f');
         X.lon(n) = sscanf(stringtokenizer(s, 10, ','), '%f');
         X.depth(n) = sscanf(stringtokenizer(s, 2, ','), '%f');
         X.data(n) = sscanf(stringtokenizer(s, 1, ','), '%f');
         
         if ~rem(n, 1000)
            fprintf(1,'.');
         end
         
      catch
         fprintf(1, '\n')
         warning(['Unable to parse string ''' s ''' on line ' num2str(m)])
         timeBuf{n} = '';
         X.lat(n) = NaN;
         X.lon(n) = NaN;
         X.depth(n) = NaN;
         X.data(n) = NaN;
      end
      
      
   end
end

fprintf(1, '\n');


good = find(~isnan(X.lat) & ~isnan(X.lon));
if ~isempty(good)
   X = chopstruct(X, good);
   X.time = datenum(char(timeBuf(good)));
   X.lat = X.lat./60./60; % convert sedonds lat to deg
   X.lon = X.lon ./60./60;
else
   X = [];
end

X.tag = 'FSI';
X.filename = filename;
