%--------------------------------------------------------------------------
% function [block] =
% FT_add_lock_commands_to_block(block,nodename,mirrorname,basename,fmod,phi0,phase0,gain,accuracy)
%
% A function for Matlab which adds lock commands to a block structure. 
% Theses commands define a cavity lock in the simulation Finesse for a 
% given interferometer setup.  The error signal for the lock is produced by
% a photodiode (PD) placed at a given node in the interferometer, 
% demodulated at the sideband frequency. For optimum lock parameters see
% FT_finesse_lock_parameters.m.
%
% block:        Block structure
% nodename:     Name of node at which to place the PD
% mirrorname:   Mirror to tune to lock the cavity
% basename:     Name to be used for the PD, error signal and lock, i.e.
%               PDname = PDbasename
%               errorname = errbasename
%               lockname = basenamelock
% fmod:         Modulation frequency of the sidebands added to the laser 
%               light [Hz].
% phi0:         Approximate operating point.  The lock function requires a 
%               starting point close to the real operating point [degrees].
% phase0:       Photodiode demodulation phase (for optimum phase see
%               FT_finesse_lock_parameters.m) [degrees].
% gain:         Lock gain [deg/W]
% accuracy:     Threshold for error signal
%
% block:        Returned block structure containing lock commands.
%
% Part of the Simtools package, http://www.gwoptics.org/simtools
% Charlotte Bond    11.10.2012
%--------------------------------------------------------------------------
%

function [block] = FT_add_lock_commands_to_block(block,nodename,mirrorname,basename,fmod,phi0,phase0,gain,accuracy)

    % Add comments
    block = FT_add_line_to_block(block,'########## Cavity Lock ##########');

    % Adding photodiode, demodulating at the sideband frequencies and the
    % given demodulation phase
    PDname = sprintf('pd%s',basename);
    block = FT_add_line_to_block(block,sprintf('pd1 %s %g %g %s',PDname,fmod,phase0,nodename));
    block = FT_add_line_to_block(block,sprintf('noplot %s',PDname));

    % Set error signal
    errorname = sprintf('err%s',basename);
    block = FT_add_line_to_block(block,sprintf('set %s %s re',errorname,PDname));
    
    % Lock command
    lockname = sprintf('%slock',basename);
    block = FT_add_line_to_block(block,sprintf('lock %s $%s %g %g',lockname,errorname,gain,accuracy));
    
    % Feedback signal, including original tuning near the operating point,
    % phi0
    fbname = sprintf('fb%s',basename);
    block = FT_add_line_to_block(block,sprintf('func %s = $%s + %g',fbname,lockname,phi0));
    block = FT_add_line_to_block(block,sprintf('noplot %s',fbname));
    
    % Feedback to the mirror
    block = FT_add_line_to_block(block,sprintf('put* %s phi $%s',mirrorname,fbname));

    % End comment
    block = FT_add_line_to_block(block,'#################################');

end

