% en435_read_ctd_data.m

clear;
flops(0);

ctdList=1:1:166;

% ---- CTD data files Path, title.
path_name_en435='~/en435/CTD/process/'; % !!!! use your path here
path_name=path_name_en435;
cruise_title='R/V Endeavor EN435';
cr_id='en435';
% ---- CTD datafile:
% Number of Headers lines.
headerLastLineNum=105+8;
% Number of variables.
n_par = 18;
% *.cdn CTD datafile columns#.
colPres=2;
colTemp=3;
colTemp_s=4;
colCnd=5;
colCnd_s=6;
colTrans=7;  % (v0) Trans
colAltim=8;  % (v2) Altim
colPar=9;    % (v3) Par
colOxy=10;   % (v4) Oxy
colOxy_s=11; % (v5) Oxy
colFluor=12; % (v7) Fluor
colSpar=13;  % (v9) Spar
colSal=14;
colSal_s=15;
colSig=16;
colSig_s=17;
% Flag - 'bad data'.
bad_flag=-9.990e-29;

% Quantity  column (e.g.):
col_num=colTemp;
jN='Temperature';

str_disp='';
   for stNum=10%ctdList
       % Write input file names to string.
      if stNum < 10
         j = ['ctd00' num2str(stNum) '.cdn'];
      elseif  stNum >=10 & stNum<100
         j = ['ctd0' num2str(stNum) '.cdn'];
      else 
         j = ['ctd' num2str(stNum) '.cdn'];
      end
      % Open file for reading.
      pfid = fopen([path_name j]);
      % Read first lines (headers).
      headerLastLineNum_st=headerLastLineNum;
      for lineNum=1:1:headerLastLineNum_st
         headerLine=fgets(pfid);
      end
      % Read formated data from file.
      da=fscanf(pfid,'%f',[1 inf])';
      % Reshape data matrix.
      data = (reshape(da,n_par,size(da,1)/n_par))';
      % Close file.
      fclose(pfid);
      % Remove 'bad' data.
      r_bad=find(data(:,colPres)==bad_flag | data(:,col_num)==bad_flag);
      if ~isempty(r_bad)
          str_disp=strvcat(str_disp,['Station No ' num2str(stNum) ', ' jN ': ' num2str(length(r_bad)) ' line(s) with "bad" data (flag=-9.990e-29)'],...
             'Pressure  Quantity',num2str([data(r_bad,colPres) data(r_bad,col_num)]));
           data(r_bad,:)=[];
      end
  end % For for stNum=10%ctdList
  if ~isempty(str_disp), disp(str_disp); end
