% Sweep DARM (differential arm length) and generate plots.
%
% [xPos, sigDC, fDC] = sweepDARM(Nsweep)
% see sweepDC for information about the parameters
%
% This displays some DC signals, and some demod signals, during
% a DARM sweep.  The AS_I2 and Q2 signals are used for DARM, but
% the phase at DC is only part of the story (see respDARM).

function [xPos, sigDC, fDC] = sweepDARM(varargin)

  % prepare some variables
  sweepSetup

  if nargin < 1
    Nsweep = 200;
  else
    Nsweep = varargin{1};
  end
  
  
  % adding this to sweepSetup causes matlab to crash, so do it here
  nDC = [nREFL(1) nAS(1) nPOX(1) nPOY(1) nTRX(1) nTRY(1)];

  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  % DARM sweep
  pos = zeros(opt.Noptic, 1);
  pos(nEX) = 3e-11;
  pos(nEY) = -3e-11;
  
  [xPos, sigDC, fDC] = sweepDC(opt, -pos, pos, Nsweep);

  
  % Get sensing matrix elements and determine phase error in AS
  %   First point just below resonance
  noob = max(find(xPos(nEX,:) < 0));
  % slope around resonance
  slopeAS = sigDC(nAS(2:end),noob+1)-sigDC(nAS(2:end),noob);
  % divide slope by the ETM motion to get derivative
  smAS = slopeAS / (xPos(nEX,noob+1) - xPos(nEX,noob));
  
  purr = 180/pi * atan2(smAS(1), smAS(2));
  gphase = opt.probe(nAS(2)).phase - purr;
  
  % If phase error is greater than 0.5 degrees
  if abs(purr) > 0.5
    disp('  ')
    disp(['Change AS phase to: ' num2str(gphase)])
    disp('  ')
  end


  
  top = subplot('Position',[0.1,0.52,0.82,0.4]);
  semilogy(xPos(nEX, :), sigDC(nDC, :))
  legend(prbNames(nDC))
  title('DARM sweep: DC signals')
  axis tight
  set(top,'XTickLabel',[]);
  grid on

  bottom = subplot('Position',[0.1,0.1,0.82,0.4]);
  plot(xPos(nEX, :), sigDC(nAS([1:3]), :))
  legend(prbNames(nAS([1:3])))
  axis tight
  grid on
