%function [] = deltaT(idt)
%--------------------------------------------------------------------------
%
% PURPOSE: Plot Imagenex 837 multibeam data
% AUTHOR:  Rob McEwen
% DATE:    2013/1/28
%
%--------------------------------------------------------------------------
%

%  global startTime dataDC rangeToWall position deltaTFig deltaTFig2


  if( exist('idt') ~= 1 || ~isfield(idt,'data') )
    fprintf('Delta T data not present\n')
  end

  if exist('titleStr') ~= 1
    titleStr = ['; Data Set: ', DirName];
  end
  
  str = [' ',titleStr,' Plotted on ',myDate];
  PaperPosn = [.5 .5 3.75 2.5];
  FigurePosn = [5 30 815 760];
  i = 0;
  if( exist('position') ~= 1 ) position = [3 59 1213 1070]; end

  
  if( exist('fontsize') == 0), fontsize = 20; end
  if( fontsize ==12 ), 
    linewidth = .5;
  else
    linewidth = 1;
  end
  fontweight = 'normal';

  idt.figPtr={};
  idt.subPlotPtr = {};
  idt.plotPtr = {};
  idt.legendPtr = {};
  lstr = {};
  if( ~isfield(idt,'nbeams') )  idt.nbeams = 120; end
  if( ~isfield(idt,'npbeams') ) idt.npbeams = 119;end
  if( ~isfield(idt,'windowLen') ) idt.windowLen = 1;end
  if( ~isfield(idt,'onePlot') ) idt.onePlot = 0;end

  if( exist('idt')==1 && isfield(idt,'data') )
      if exist( 'deltaTFig2' ) ~= 1
          deltaTFig2 = figure;
          figure(deltaTFig2);
          idt.figPtr{end+1}=deltaTFig2;
          %   winpos( position(1,:) );
      else
          figure(deltaTFig2);
      end

      
      set( deltaTFig2, 'Name', 'OA Multibeam Plot', 'DeleteFcn', 'clear deltaTFig2' );
      set(gcf,'position',position)
      set(gca,'fontsize',fontsize,'fontweigh',fontweight)
      set(gcf,'defaultaxesfontsize',fontsize,'defaulttextfontsize',fontsize)

      %
      % Index into idt.data
      idt.BeamRange=idt.BeamRange1+[0:idt.nbeams-1]';

      idt.ngoodbeams = zeros(length(idt.data),5);

      idt.ngoodbeams(:,1) = sum(logical(idt.data(:,idt.BeamRange1:idt.BeamRange30)'))';
      idt.ngoodbeams(:,2) = sum(logical(idt.data(:,idt.BeamRange31:idt.BeamRange60)'))';
      idt.ngoodbeams(:,3) = sum(logical(idt.data(:,idt.BeamRange61:idt.BeamRange90)'))';
      idt.ngoodbeams(:,4) = sum(logical(idt.data(:,idt.BeamRange91:idt.BeamRange120)'))';
      for( i=1:4 )
          idt.ngoodbeams(:,5) = idt.ngoodbeams(:,5)+idt.ngoodbeams(:,i);
      end

      beamIndx   = floor(idt.nbeams/(idt.npbeams+1)*[1:idt.npbeams]);
      %beamAngles = (beamIndx-60)*idt.nbeams/(idt.nbeams-1);
      %beamAngles = (beamIndx*idt.nbeams/(idt.nbeams-1) - 60)*pi/180;  %Degrees
      beamAngles = ([0:idt.nbeams-1]*idt.nbeams/(idt.nbeams-1) - 60)*pi/180;  %Degrees
      beamAngles = ([0:idt.nbeams-1] - 60)*pi/180;  %Degrees
      if( 0 )
          idtx   = interp1(dataNav(:,1), posx, idt.data(:,1));
          idty   = interp1(dataNav(:,1), posy, idt.data(:,1));
          idtPsi = interp1(dataNav(:,1), dataNav(:,mPsi), idt.data(:,1));
          %
          for( i=1:length(idtx) )
              idtx(i,1:length(beamIndx)) = idtx(i) + sin(idtPsi(i) + ...
                                                         beamAngles(beamIndx)).*...
                  idt.data(i,idt.BeamRange(beamIndx));
              idty(i,1:length(beamIndx)) = idty(i) - cos(idtPsi(i) + ...
                                                         beamAngles(beamIndx)).*...
                  idt.data(i,idt.BeamRange(beamIndx));
          end
      end
      hold on
      grid on
      idt.plotPtr{end+1} = plot(idt.data(:,1), idt.ngoodbeams(:,1:5),'-');
      lstr(length(lstr)+1,1) = { 'Good Beams in 0 -30  Sector' };
      lstr(length(lstr)+1,1) = { 'Good Beams in 30-60  Sector' };
      lstr(length(lstr)+1,1) = { 'Good Beams in 60-90  Sector' };
      lstr(length(lstr)+1,1) = { 'Good Beams in 90-120 Sector' };
      lstr(length(lstr)+1,1) = { 'Good Beams in all    Sectors' };
      
      idt.plotPtr{end+1} = plot(idt.data(:,1), idt.data(:,idt.BeamRange(beamIndx) ), ...
                                '.','Markersize',8);
      for( i=1:length(beamIndx))
          beamStr = sprintf('DeltaT Beam %d at %.1f Deg.',beamIndx(i), ...
                            beamAngles(beamIndx(i))*180/pi);
          %lstr(length(lstr)+1,1) = { 'Decimated side-Looking Imagenex Ranges; '};
          lstr(length(lstr)+1,1) = { beamStr };
      end
      if( ~exist('startTime') ) 
          startTime = idt.startTime; 
      end
      xstr = sprintf('Seconds; t_0 = %.1f', startTime);
      xlabel(xstr);
      ylabel('Meters');
      if( idt.onePlot )
          title(['Forward and Aft OA Multibeam Ranges Combined; ',titleStr]);
      else
          title(['Aft OA Multibeam Range; ',titleStr]);
      end      
      
      if(idt.npbeams <= 5) 
          idt.legendPtr=legend(lstr,'location','best');
      else
          idt.legendPtr=legend(lstr{1:10},'location','best');
      end
      
  end

if( exist('idt_fwd')==1 && isfield(idt_fwd,'data') )
    idt_fwd.figPtr={};
    idt_fwd.subPlotPtr = {};
    idt_fwd.plotPtr = {};
    idt_fwd.legendPtr = {};
    lstr = {};

    % The | handles the case where there is only fwd data
    if( idt.onePlot == 0 | ~isfield(idt,'data') )  
        if exist( 'deltaTFwdFig2' ) ~= 1
            deltaTFwdFig2 = figure;
            figure(deltaTFwdFig2);
            idt_fwd.figPtr{end+1}=deltaTFwdFig2;
            %   winpos( position(1,:) );
        else
            figure(deltaTFwdFig2);
        end
        set( deltaTFwdFig2, 'Name', 'Fwd OA Multibeam', 'DeleteFcn', 'clear deltaTFwdFig2' );
        set(gcf,'position',position)
        set(gca,'fontsize',fontsize,'fontweigh',fontweight)
        set(gcf,'defaultaxesfontsize',fontsize,'defaulttextfontsize',fontsize)
    end  

    if( ~isfield(idt_fwd,'nbeams') )  
        idt_fwd.nbeams = idt_fwd.data(1,idt_fwd.NumberOfBeams); end
    if( ~isfield(idt_fwd,'npbeams') ) idt_fwd.npbeams = idt_fwd.nbeams-1;end
    if( idt_fwd.npbeams >= idt_fwd.nbeams ) 
          idt_fwd.npbeams = idt_fwd.nbeams;end
    if( ~isfield(idt_fwd,'windowLen') ) idt_fwd.windowLen = 1;end

    idt_fwd.ngoodbeams = zeros(length(idt_fwd.data),5);

    idt_fwd.ngoodbeams(:,1) = sum(logical(idt_fwd.data(:,idt_fwd.BeamRange1:idt_fwd.BeamRange30)'))';
    idt_fwd.ngoodbeams(:,2) = sum(logical(idt_fwd.data(:,idt_fwd.BeamRange31:idt_fwd.BeamRange60)'))';
    idt_fwd.ngoodbeams(:,3) = sum(logical(idt_fwd.data(:,idt_fwd.BeamRange61:idt_fwd.BeamRange90)'))';
    idt_fwd.ngoodbeams(:,4) = sum(logical(idt_fwd.data(:,idt_fwd.BeamRange91:idt_fwd.BeamRange120)'))';
    for( i=1:4 )
        idt_fwd.ngoodbeams(:,5) = idt_fwd.ngoodbeams(:,5)+idt_fwd.ngoodbeams(:,i);
    end

    %
    % Index into idt_fwd.data
    idt_fwd.BeamRange=idt_fwd.BeamRange1+[0:idt_fwd.nbeams-1]';
    beamIndx   = floor(idt_fwd.nbeams/(idt_fwd.npbeams+1)*[1:idt_fwd.npbeams])+1;
    %beamAngles = (beamIndx-60)*idt_fwd.nbeams/(idt_fwd.nbeams-1);
    %beamAngles = (beamIndx*idt_fwd.nbeams/(idt_fwd.nbeams-1) - 60)*pi/180;  %Degrees
    beamAngles = ([0:idt_fwd.nbeams-1]*idt_fwd.nbeams/(idt_fwd.nbeams-1) - 60)*pi/180;  %Degrees
    beamAngles = ([0:idt_fwd.nbeams-1] - 60)*pi/180;  %Degrees
    if( 0 )
        idtx   = interp1(dataNav(:,1), posx, idt_fwd.data(:,1));
        idty   = interp1(dataNav(:,1), posy, idt_fwd.data(:,1));
        idtPsi = interp1(dataNav(:,1), dataNav(:,mPsi), idt_fwd.data(:,1));
        %
        for( i=1:length(idtx) )
            idtx(i,1:length(beamIndx)) = idtx(i) + sin(idtPsi(i) + beamAngles(beamIndx)).*...
                idt_fwd.data(i,idt_fwd.BeamRange(beamIndx));
            idty(i,1:length(beamIndx)) = idty(i) - cos(idtPsi(i) + beamAngles(beamIndx)).*...
                idt_fwd.data(i,idt_fwd.BeamRange(beamIndx));
        end
    end
    hold on
    grid on
    idt_fwd.plotPtr = plot(idt_fwd.data(:,1), ...
                           idt_fwd.data(:,idt_fwd.BeamRange(beamIndx) ), '.',...
                           'Markersize',8);

    if(~idt.onePlot)
        for( i=1:length(beamIndx))
            beamStr = sprintf('DeltaT Beam %d at %.1f Deg.',beamIndx(i), ...
                              beamAngles(beamIndx(i))*180/pi);
            %lstr(length(lstr)+1,1) = { 'Decimated side-Looking Imagenex Ranges; '};
            lstr(length(lstr)+1,1) = { beamStr };
        end
        if( ~exist('startTime') ) 
            startTime = idt_fwd.startTime; 
        end
        plot(idt_fwd.data(:,1), idt_fwd.ngoodbeams(:,1:5));
        xstr = sprintf('Seconds; t_0 = %.1f', startTime);
        xlabel(xstr);
        ylabel('Meters');
        title(['Forward OA Multibeam Range; ',titleStr]);

        if(idt_fwd.npbeams <= 5) 
            idt_fwd.legendPtr=legend(lstr,'location','best');
        end
    end  
end

 %
 % Switch between wall and bottom following:
 % 
 if( exist('idt')==1 && ~isfield(idt,'vertMt'))
    idt.vertMt = 1;
 end 

  if( exist( 'SideBeamIndex' ) == 1 && idt.vertMt == 0) 
      fprintf('Data from DynamicControlLog\n');
      if(isfield(idt,'dataSource'))
          fprintf('Warning: DynamicControlLog exists and idt contains %s.\n',...
                  idt.dataSource);
      else
          idt.dataSource = 'DynamicControlLog';
      end
  elseif(isfield(idt,'dataSource') && idt.vertMt == 0)
      fprintf('Data from %s\n',idt.dataSource);
  else
      return; 
  end

  if(~isfield(idt,'computeValues')) idt.computeValues=0;end
  
  if( ~strcmp(idt.dataSource,'DynamicControlLog') | idt.computeValues )
      fprintf('Finding SideBeamIndex in Matlab.\n');
      fprintf('Finding the minimum distance for each sounding.\n');
      idt.minAllowableRange = 1;
      idt.halfWindowLen = floor( (idt.windowLen-1)/2 );
      
      % [idt.minRange, idt.minRangeIndx]=min(idt.data(:,idt.BeamRange1: ...
      %                                               121)');
      % [idt.tIndx idt.minRangeIndx]=...
      %     find(idt.data(:,idt.BeamRange1:idt.BeamRange1+120)>idt.minAllowableRange & ...
      %          idt.data(:,idt.BeamRange1:idt.BeamRange1+120)<idt.maxAllowableRange);
      % idt.minRange=idt.minRange';
      % idt.minRangeIndx=idt.minRangeIndx'+idt.BeamRange1-1;

      idt.minRange = 500*ones(length(idt.data),1);
      idt.minAngle = NaN(length(idt.data),1);
      idt.minIndx  = NaN(length(idt.data),1);
      idt.median   = NaN(length(idt.data),1);
      tic
      for( i=1:length(idt.data) )
          for( j=idt.BeamRange1:idt.BeamRange1+119 )
              if( idt.data(i,j) > idt.minAllowableRange & idt.data(i,j) < idt.minRange(i) ) 
                  idt.minRange(i) = idt.data(i,j);
                  idt.minIndx(i) = j;
              end
          end
          minArrayIndx=idt.minIndx(i)-idt.BeamRange1+1;
          if( isnan(minArrayIndx) )
              idt.median(i) = NaN;
              continue;
          end
          idt.minAngle(i) = beamAngles(minArrayIndx);
          %
          % Now find the median
          if( idt.windowLen > 1 )
              %
              % Median filter.  Select halfWindowLen neighboring beams to either side
              % of the minimum range beam.  Handle the case where _beamIndx is within
              % halfWindowLen of either end of the array.

              if( minArrayIndx < idt.halfWindowLen ) 
                  startIndx = 0;
              elseif( minArrayIndx > idt.nbeams - idt.halfWindowLen - 1 ) 
                  startIndx = idt.nbeams - idt.windowLen;
              else 
                  startIndx = minArrayIndx - idt.halfWindowLen;
              end
              %
              % Find the median in the window
              idt.median(i) = median(...
                  idt.data(i,startIndx+idt.BeamRange1:startIndx+idt.BeamRange1+idt.windowLen-1));
          else
              idt.median(i) = idt.data(i,idt.minIndx(i));
          end
      end
      toc
  end

  lstr={};
  if exist( 'deltaTFig' ) ~= 1
    deltaTFig= figure;
    figure(deltaTFig);
%   winpos( position(1,:) );
    idt.figPtr{end+1}=deltaTFig;
  else
    figure(deltaTFig);
  end
  set( deltaTFig, 'Name', 'Minimum Beam Plot', 'DeleteFcn', 'clear deltaTFig' );
  set(gcf,'position',position)
  set(gca,'fontsize',fontsize,'fontweigh',fontweight)
  set(gcf,'defaultaxesfontsize',fontsize,'defaulttextfontsize',fontsize)

  idt.subPlotPtr{end+1} = subplot(2,1,1);
  set(gca,'fontsize',fontsize,'fontweigh',fontweight)
  if( strcmp(idt.dataSource,'DynamicControlLog') & ~idt.computeValues ) 
      idt.plotPtr{end+1} = plot(dataDC(:,1), dataDC(:,rangeToWall),'x');
  else
      idt.minTimeIndx = find(~isnan(idt.minIndx));
      %idt.plotPtr{end+1} = plot(idt.data(idt.minTimeIndx,1), ...
      %                          idt.data(idt.minTimeIndx, ...
      %                                   idt.minIndx(idt.minTimeIndx)),'o');
      idt.plotPtr{end+1} = plot(idt.data(idt.minTimeIndx,1), ...
                                idt.minRange(idt.minTimeIndx),'x');
      lstr(length(lstr)+1,1) = {'Unfiltered'};
      hold on
      idt.plotPtr{end+1} = plot(idt.data(idt.minTimeIndx,1), ...
                                idt.median(idt.minTimeIndx),'ro');
      lstr(length(lstr)+1,1) = {'Median Filtered'};
      
      %if(idt.npbeams <= 5) 
      idt.legendPtr(end+1,1)=legend(lstr,'location','best');
      %end
      
  end
  grid on
  xlabel('Seconds');
  ylabel('Meters');
  title(['Minimum Beam Range; ', titleStr]);


  idt.subPlotPtr{end+1} = subplot(2,1,2);
  set(gca,'fontsize',fontsize,'fontweigh',fontweight)
  if( strcmp(idt.dataSource,'DynamicControlLog') & ~idt.computeValues )
      idt.plotPtr{end+1} = plot(dataDC(:,1), dataDC(:,SideBeamIndex));
  else
      idt.plotPtr{end+1} = plot(idt.data(idt.minTimeIndx,1), ...
                                idt.minAngle(idt.minTimeIndx)*180/pi,'x');
  end
  grid on
  xlabel('Seconds');
  ylabel('Degrees');
  title('Minimum Beam Angle');

  linkaxes(get(gcf,'children'),'x')
