function data = get_calib(varargin)
% data = get_calib(varargin)
% 
% Get the most recent values of watertrack or bottom track calibration
%
% data is a structure with amp, phase (median, mean, std) and number of points
% data from calibration records are returned in reverse order from the file
% (returns empty if it cannot read the file)
%
% varargin is 
% 
% (name)        (options)                      (default)
% -------      -----------                     -----------
% 'dirname'    (path to adcp processing dir)    ./
% 'cruiseid'   (name for cruise)                ''               (empty)
% 'type'       'bottom' or 'water'              'water'
% 'file'       (name of output file to read)    'adcpcal.out'    (for watertrk)
%                                               'btcaluv.out'    (for btmtrk)
% 'last'       number of records to get         1                (last record)
% 'verbose'    (spew forth useful stuff)        0 
%
% default usage: to find latest values from ./cal/watertrk/adcpcal.out
%  data = get_calib;
%
%
% JH 2001/09/27

%set up defaults
config.dirname = '.';
config.type    = 'water';
config.file    = [];
config.last    = 1;
config.verbose = 0;
config.cruiseid = '';

% fill with new values from command line
config = fillstruct(config, varargin, 0);

vv = 0;
if (config.verbose)
   vv = 1;
end

% find out what kind of file it is (watertrk or bottomtrk)
if (strcmp(config.type, 'water'))
   if isempty(config.file)
      config.file = 'adcpcal.out';
   end
   calfile = fullfile(config.dirname, ['cal/watertrk/', config.file])
elseif (strcmp(config.type, 'bottom'))
   if isempty(config.file)
      config.file = 'btcaluv.out';
   end
   calfile = fullfile(config.dirname, ['cal/botmtrk/', config.file]);
else
   calfile = '';
end


if (isempty(calfile))
   data = [];
   return
end


fid = fopen(calfile);
if (fid == -1)
   data = [];
   sprintf('cannot open file %s: returning data=[]\n', calfile)
else

   %read the whole thing in
   F = fread(fid);
   fclose(fid);
   ss = char(F');

   %find the number of records available
   rec_start = [];
   rec_end = [];
   endlines = [0; find(F == 10)];  %find all newlines; 
                                   %add one to the beginning to help parsing 

   for ii = 2:length(endlines)
      line = ss( (endlines(ii-1) + 1) : (endlines(ii)-1)); %chars without \n
      word = strtok(line);
      if (strcmp(word, 'Calculation'))
         rec_start = [rec_start; ii-1]; %get one line prior to "Calculation"
      end
      if (strcmp(word, 'amplitude'))
         rec_end = [rec_end; ii+2];     %get 2 lines after "amplitude"
      end
   end

   config.last = min(config.last, length(rec_start));


   if (vv)
      sprintf('doing record numbers %d\n',...
              length(rec_start) : -1 : (length(rec_start) + 1 - config.last) )
   end
   
   
   cnt = 1;
   for recnum = length(rec_start) : -1 : (length(rec_start) + 1 - config.last) 
      data(cnt).dir = fullfile(pwd, calfile);
      data(cnt).cruiseid = config.cruiseid;
      data(cnt).recnum = recnum;
      %start at the end and work towards the top
      record = ss(endlines(rec_start(recnum)-1) : endlines(rec_end(recnum)));
      %not toss out all the lines with "="

     
      short_record = [];
      %now pull out relevant info only
      rec_endlines = [0  find((record+0) == 10)]';  %find all newlines; 
      for linenum = 2:length(rec_endlines)
         %chars without \n
         line = record((rec_endlines(linenum-1) + 1):(rec_endlines(linenum)-1)); 
         if (isempty(find(line == '=')))
            short_record = [short_record, 10,  line];
         end
      end


      if (vv) 
         record
         paused(1)
      end

      
      % now get the stuff for the data structure from the short record
      srec_endlines = [0  find((short_record+0) == 10)]';  %find all newlines; 
      for slinenum = 2:length(srec_endlines)
         line = short_record((srec_endlines(slinenum-1) + 1): ...
                             (srec_endlines(slinenum)-1));
         %---- time of calculation
         word = strtok(line);
         if (strcmp(word, 'Calculation'))
            data(cnt).timestamp = line;
         end
         %---- number of (edited) points
         if (strcmp(word, 'Number'))  %water track
            %Number of edited points:  32 out of  62"
            [j1, j2, j3, j4, data(cnt).numpts] = strread(line, '%s%s%s%s%d',1);
         end
         if (strcmp(word, 'edited:'))  %bottom track
            %"edited:   980 points, 2.0 min speed, 2.5 max dev
            [j1, data(cnt).numpts] = strread(line, '%s%d',1);
         end
         % ---- amplitude
         if (strcmp(word, 'amplitude'))
            %amplitude   0.9992   0.9991   0.0038
            [j1 data(cnt).amp_median, data(cnt).amp_mean, data(cnt).amp_std] = ...
                strread(line, '%s%f%f%f');
         end
         if (strcmp(word, 'phase'))
            %phase      -0.0152  -0.0144   0.1656
            [j1 data(cnt).phase_median, data(cnt).phase_mean, data(cnt).phase_std] = ...
                strread(line, '%s%f%f%f');
         end
      end
      cnt = cnt + 1;
   end

end                                   
                                   
                                   

