% Sweep SRCL (signal recycling cavity length) in DRFPMI and generate plots.
%
% [xPos, sigDC, fDC] = sweepSRCL(Nsweep)
% see sweepDC for information about the parameters
%
% This displays some DC signals, and some demod signals, during
% a SRCL sweep.  From this sweep, the phases of the POX_IP and POX_IM
% double-demod signals can be set to give the correct zero crossing.

function [xPos, sigDC, fDC] = sweepSRCL(Nsweep)

  % prepare some variables
  sweepSetup

  % 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)];

  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  % SRCL sweep
  posStart = zeros(opt.Noptic, 1);
  posStop = zeros(opt.Noptic, 1);
  posStart(nSR) = -1.5e-7;
  posStop(nSR) = 1e-7;
  
  [xPos, sigDC, fDC] = sweepDC(opt, posStart, posStop, Nsweep);

  % compute phase errors for double-demod signals
  Nmid = find(xPos(nSR, :) >= -1e-16, 1);
  phaseM = 180 * atan2(sigDC(nPOX(4), Nmid), sigDC(nPOX(5), Nmid)) / pi;
  phaseP = 180 * atan2(sigDC(nPOX(6), Nmid), sigDC(nPOX(7), Nmid)) / pi;
  str = sprintf('double demod phase errors: %g dg for %s, %g dg for %s', ...
                phaseM, prbNames{nPOX(4)}, phaseP, prbNames{nPOX(6)});
  disp(str)
  phaseM = opt.probe(nPOX(4)).phase - phaseM;
  phaseP = opt.probe(nPOX(6)).phase - phaseP;
  str = sprintf('  good phases: %g dg for %s, %g dg for %s', ...
                phaseM, prbNames{nPOX(4)}, phaseP, prbNames{nPOX(6)});
  disp(str)
  
  % make some plots
  fDCp = permute(fDC, [2, 3, 1]);  
  n = getFieldAt(opt, nSR, 'fr');		% SR front input field

  sDD = sigDC(nPOX(4:5), :) + sigDC(nPOX(6:7), :);
  
  subplot(2, 1, 1)
  semilogy(xPos(nSR, :), abs(fDCp(nSBa, :, n)), ...
           xPos(nSR, :), abs(fDCp(nSBb, :, n)), '--')
  title('SRCL sweep: RF component powers in the SRC')
  legend(num2str([vFrf(nSBa); vFrf(nSBb)] / 1e6))
  grid on
  lineAtX(0, 0.3 * [1 1 1]);
  
  subplot(2, 1, 2)
  plot(xPos(nSR, :), [sigDC(nPOX(4:7), :); sDD])
  legend(prbNames{nPOX(4:7)}, 'POX IM + IP', 'POX QM + QP')
  title('SRCL sweep: POX double-demod signals')
  grid on
  lineAtX(0, 0.3 * [1 1 1]);
