function D = readseabass(fileIn)
% READSEABASS - Read seaBASS formatted files (usually with extension '.ftp')
%
% Use as: s = readseabass(filename)
%
% Inputs: filename = name of the file to read
% Output: s = structure containing the header info and data from filename
%             s.data(:,1) contaings the date (as matlab date numbers), while
%             s.data(:,2:end) contains the data values

% Brian Schlining
% 12 May 1999
% 19 Aug 1999; First working version

%===========
% Open File
%===========
if ~nargin
   [infile inpath] = uigetfile('*.ftp','Select Ascii grid file',0,0);
   if infile == 0
      D = [];
      return                            % Return if CANCEL is selected
   end
   fileIn = [inpath infile];
end

%===========
% Read File
%===========

% Several different index pointers to keep track of
nDate = 0;
nTime = 0;
n     = 0;											% Line counter
firstPass = 1;
D.filename = fileIn;								% Store the filename
fid = fopen(fileIn,'rt');						% Open it for reading
if fid < 0
   warning(['Invalid file name: ' fileIn])
   D = [];
   return
end


while ~feof(fid)									% Loop through the file
   p = ftell(fid);								% Get the start of each line
   S = fgetl(fid);								% Get the line
   
   if strcmp(S(1),'/')							% Read the header
      n = n + 1;
      k = findstr('=',S);						% See if its a metadata header line
      if ~isempty(k)
         ID = S(2:k-1);							% The name of the metadata attribute
         Data = S(k+1:end);					% The value of the metadata attribute
         switch ID								% Catch special attributes
         case 'original_file_name'
            D = setfield(D,ID, Data);
         case 'delimiter'
         case 'missing'
            Bad = sscanf(Data,'%f');
         case 'north_latitude'
            nl = sscanf(Data,'%f');
         case 'south_latitude'
            sl = sscanf(Data,'%f');
         case 'east_longitude'
            el = sscanf(Data,'%f');
         case 'west_longitude'
            wl = sscanf(Data,'%f');
         case 'start_date'
            D = setfield(D,ID, datestr(hdate2num(Data),1));
         case 'end_date'
            D = setfield(D,ID, datestr(hdate2num(Data),1));
         case 'fields'							% parse the fields apart
            i = 0;
            c = 1;
            
            numTokens = length(findstr(Data, ',')) + 1;
            
            for j = 1:numTokens
               T = stringtokenizer(Data, j, ',')
               
               i = i + 1;
               c = c + 1;
               if i == 1
                  fields{1} = 'Date';		% The first column will always be the datanumber
                  fi = 2;						% Index for other fields
                  fv = 1;						% Indices used by the 'units' switch
               end
               
               
               switch T							% Catch Time fields which are parsed and converted to datenumbers
               case 'Time'			
                  fS = '%2f:%2f:%2f ';
                  nTime = 2;
                  timeIndStart = i;
                  timeIndEnd   = i + nTime;
                  i = i + nTime;
                  
               case 'Date2'
                  fS = '%2f/%2f/%4f ';
                  nDate = 2;
                  dateIndStart = i;
                  dateIndEnd   = i + 2;
                  i = i + nDate;
                  
               otherwise
                  fS = '%f ';
                  fields{fi} = T;
                  fi = fi + 1;
                  fv = [fv c];
               end
               
               if i == 1						% Create a formating string for use with sscanf
                  formatS = fS;
               else
                  formatS = [formatS fS];
               end
               
            end

            if ~exist('dateIndStart')
               
               for kk = 2:length(fields)
                  buf{kk-1} = fields{kk};
               end
               fields = buf;
            end
            
            
            D = setfield(D,ID, fields);
            cols = i - 1 - nTime - nDate;
            
         case 'units'
            i = 1;
            units{1} = 'serial Days';
            while ~isempty(Data)
               i = i + 1;              
               [T, Data] = strtok(Data,',');
               
               units{i} = T;
            end
            D = setfield(D,ID, {units{fv}});
            %D = setfield(D,ID, units);
         otherwise
            D = setfield(D,ID, Data);
         end
      end      
      
   elseif strcmp(S(1),'!')				% Ignore comments
      
   else										% Read Data
      if firstPass						
         j = 0;
         d = fread(fid,'int8');				  % Scan in the entire file as ascii
         rows = length(find(d == 10))+1; 	  % Count the return characters
         dat = ones(rows,cols)*NaN;			  % Initialize memory
         firstPass = 0;			
         if exist('dateIndStart') %<-------added 12/15
            ind = 1:cols + nTime + nDate + 1;  % Creative indexing to ignore the date and time fields
            ind(dateIndStart:dateIndEnd) = [];
            ind(timeIndStart:timeIndEnd) = [];
         else%<-------added 12/15
            
            ind = 1:cols;%<-------added 12/15
         end %<-------added 12/15
         fseek(fid,p-n,-1);				     % rewind the file to the start of the data
      else
         j = j + 1;
         d = sscanf(S, formatS);				  % parse each line of data
         
         if length(d) == (cols + nTime + nDate + 1)
            if exist('dateIndStart') %<-------added 12/15
               sdn = datenum(d(dateIndEnd), d(dateIndStart),d(dateIndEnd-1), d(timeIndStart), d(timeIndStart+1), d(timeIndEnd));
            end %<-------added 12/15
            dat(j,:) = [sdn; d(ind)]';
            %fprintf(1,'%4i %2i %2i %14s %3i\n',d(dateIndEnd), d(dateIndEnd-1), d(dateIndStart),datestr(sdn),length([sdn; d(ind)]'));
            
         end
         
         
         
      end
      
      
   end
   
   
end
fclose(fid);

D.lat = mean([nl sl]);				% Calculate the mean lat
D.lon = mean([el wl]);				% Calculate the mean lon
dat = sortrows(dat,1);				% Sort it all by date
i = find(dat == Bad);				% Set missing calues to NaN
dat(i) = NaN;
i = find(~isnan(dat(:,1)));		% Chop off any row with a date of NaN
D.data = dat(i,:);

