% Sweep PRCL (signal recycling cavity length) in DRFPMI and generate plots.
%
% [xPos, sigDC, fDC] = sweepPRCL(Nsweep)
% see sweepDC for information about the parameters
%
% This displays some DC signals, and some demod signals, during
% a PRCL sweep.  From this sweep, one might try to find a good
% signal for PRCL.

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

  % Check number of input arguments
  if nargin < 1
    Nsweep = 100;
  elseif nargin > 1
    error('Too Many Arguments!')
  end

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

  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  % PRC sweep
  pos = zeros(opt.Noptic, 1);
  pos(nPR) = 4e-8;
  
  [xPos, sigDC, fDC] = sweepDC(opt, -pos, pos, Nsweep);

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

  subplot(2, 1, 1)
  semilogy(xPos(nPR, :), abs(fDCp(nSBa, :, n)), ...
           xPos(nPR, :), abs(fDCp(nSBb, :, n)), '--')
  title('PRCL sweep: RF component powers in the PRC')
  legend(num2str([vFrf(nSBa); vFrf(nSBb)] / 1e6))
  grid on

  subplot(2, 1, 2)
  plot(xPos(nPR, :), sigDC(nREFL(2:end), :))
  legend(prbNames(nREFL(2:end)))
  title('PRCL sweep: REFL demod signals')
  grid on
