% Sweep CARM  (common arm length) in DRFPMI and generate plots.
%
% [xPos, sigDC, fDC] = sweepCARM(Nsweep)
% see sweepDC for information about the parameters
%
% This displays some DC signals, and some demod signals, during
% a CARM sweep.  The phase of the REFL_I1 signal is set to maximize
% its response to this sweep.

function [xPos, sigDC, fDC] = sweepCARM(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)];

  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  % CARM 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 REFL1
  %   First point just below resonance
  noob = max(find(xPos(nEX,:) < 0));
  % REFL1 slope around resonance
  slopeREFL = sigDC(nREFL(2:end),noob+1)-sigDC(nREFL(2:end),noob);
  % divide slope by the ETM motion to get derivative
  smREFL = slopeREFL / (xPos(nEX,noob+1) - xPos(nEX,noob));
  
  % Phase error
  purr = 180/pi * atan2(smREFL(2), smREFL(1));

  % Get the digital phase now and add the error to it
  gphase = opt.probe(nREFL(2)).phase + purr;
  
  if abs(purr) > 0.3
    disp('  ')
    disp(['Change REFL1 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),...
         'Location','SouthWest',...
         'Orientation','horizontal')
  title('CARM sweep: DC signals (top) & Demods (bottom)')
  grid on
  set(top,'XTickLabel',[]);

  bottom = subplot('Position',[0.1,0.1,0.82,0.4]);
  plot(xPos(nEX, :), sigDC(nREFL(2:end), :))
  legend(prbNames(nREFL(2:end)),...
         'Location','SouthEast',...
         'Orientation','horizontal')
  grid on
