% rdi2mat - a routine to convert RDI "asciiout" files to MATLAB
% Jim Manning August 1997 on OC311

ph=menu('phase?','load data','plot','detided plots');

if ph==1;
  % open inputfile
  fn=input('Asciiout file name? ','s');
%  fn='/data5/jmanning/adcp/al9801/g98a004t.101';
  f=fopen(fn);
  disp(' ')
  disp('Processing in progress...wait a few minutes.');
  disp(' ')

  % skip 3 lines with comment & configuration info
  for i=1:3;fgetl(f);end;

  % read each ensemble ... one at a time until you get red error
  dd=1;
  i=0;
  j=0;
  while dd~=-1&dd~=[];

    % read date, time, and temperature
    dd=fscanf(f,'%f',13)';
    if dd~=-1&dd~=[];
      i=i+1;
      if i==1;
        %      define size of "d"
        d=ones(100,15);
        dv=ones(6000,14);
      end;
      d(i,1:8)=[dd(8) dd(1:6) dd(13)];
  
      %   read bottom depth and add to "d"
      dd=fscanf(f,'%f',12);
      d(i,9)=mean(dd(9:12));

      %   skip cummulative distance line
      fgetl(f);
      fgetl(f);

      %   read lat/lon and ship speed
      dd=fscanf(f,'%f',5);
      d(i,10:13)=dd(1:4)';  

      %   skip discharge
      fgetl(f);
      fgetl(f);

      %   read # of bins
      dd=fgetl(f);
      d(i,14)=str2num(dd(1:2));

      %   derive yearday
      d(i,15)=julian(d(i,3),d(i,4),d(i,2),d(i,5)*100+round(d(i,6)+d(i,7)/60));

      %   read data bin by bin
      for k=1:d(i,14);
        j=j+1;
        dv(j,:)=[d(i,1) fscanf(f,'%f',13)'];
      end;
    end;
  end;

  % reduce the size of the matrix to that used
  d=d(1:i,:);
  idd=find(dv(:,1)<=d(i,1));
  dv=dv(idd,:);

  % save data in a mat file
  sd=menu('Save data in a mat file as "d" and "dv"?','y','n');
  if sd==1;  eval(['save ',fn(1:length(fn)-4),' d dv']);    end;
end;

%%%%%%%%%%%   Phase two plotting %%%%%%%%%%%%%%%%%%%%

% define percent good acceptable
accept=70;
disp(['NOTE: Percent Good acceptable set at: ',num2str(accept)]);

if ph==2;
  [nr,nc]=size(d);
  for i=1:nr;
    id=find(dv(:,1)==d(i,1)&dv(:,13)>accept);
    % vertical averaged vectors
    ub(i)=mean(dv(id,5));
    vb(i)=mean(dv(id,6));
  end;

  % plot time series
  plot(d(:,15),ub,'r',d(:,15),vb,'g');

  % plot vbar vectors if nav is avaiable
  
  if min(d(:,10))<30000;
    figure(2)
    plot(d(:,11),d(:,10),'.');
    hold on;
    vecplot2(d(:,11),d(:,10),ub,vb);
  end;

end;

%%%%%%%%%%%%%%%%%   DETIDED PLOTS  %%%%%%%%%%%%%%%%%%%%%

if ph==3;
  % calculate tide estimate (Note: we added one for leap year)
  [ut,vt]=detide(d(:,11),d(:,10),(d(:,2)-94)*365*24+24+d(:,15)*24);
  % remove the tide
  uf=ub-ut*100;
  vf=vb-vt*100;

  % plot time series
  plot(d(:,15),ub,'r',d(:,15),vb,'g',d(:,15),uf,'r--',d(:,15),vf,'g--');

  % plot vbar vectors
  figure(2)
  plot(d(:,11),d(:,10),'.');
  hold on;
  vecplot2(d(:,11),d(:,10),uf,vf);

end;
