function LockTime = lockTimeMeasure(Vctrl,Time,ErrorTol)
%#codegen
% Lock time measurement : This function computes the lock time of a PLL 
% by looking at the behavior of the control voltage to the VCO w.r.t time.
% The function looks for the time point (i.e. lock time) when control voltage
% gets stable and varies with certain tolerance.
% 
% Input:
%  Vctrl    - Input to the VCO i.e. a vector of control voltages during the
%              course of the PLL operation. Ideally it should be an N x 1
%              or 1 x N vector.
%  Time     - Vector of time points corresponding to the Vctrl.
%  ErrorTol - error tolerance for computing the lock time.
%
% Output:
% LockTime : lock time of the PLL measured in 's'.

% Copyright 2018 The MathWorks, Inc.
[NrVco,NcVco] = size(Vctrl);
[NrTime,NcTime] = size(Time);

if(NrVco ~= 1 && NcVco ~= 1)
    error(message('msblks:msblksMessages:VcoInMustBeVector'));
end

if(NrTime ~= 1 && NcTime ~= 1)
    error(message('msblks:msblksMessages:TimeMustBeVector'));
end

if(length(Vctrl) ~= length(Time))
    error(message('msblks:msblksMessages:TimeVcoInMustBeSameLength'));
end

if(nargin == 2 || ErrorTol <= 0 || isreal(ErrorTol) ~= 1)
    warning(message('msblks:msblksMessages:InvalidErrorTol'));
    ErrorTol=1e-6;
end

i=1;
search=1;

% making the Vctrl vector an N x 1 type
if (NcVco ~= 1)
    Vctrl=Vctrl';
end

% taking the last control voltage value to be the stable value of the given datapoints. 
    Vstable=Vctrl(end,1);

while(search)
        if(abs(Vctrl(i,1)-Vstable) > ErrorTol && i+1 < length(Vctrl))
            i=i+1;
        else
            for j=i+1:length(Vctrl)
                if(abs(Vctrl(j,1)-Vstable) > ErrorTol)
                    search=1;
                    i=j+1;
                    break;
                else
                    search=0;
                end
            end
        end
end
if(search == 0 && i+1 < length(Vctrl))
    LockTime=Time(i);
    [Y,~,U]=engunits(Time,'latex');
    [lock_t,~,lock_u]=engunits(LockTime,'latex');
    figure('Name','Control Voltage Plot','IntegerHandle','off','Tag','PlotControlVoltage');
    plot(Y,Vctrl);
    grid;
    xlabel(message('msblks:msblksMessages:VctrlPlotXLabel',U).getString);
    ylabel(message('msblks:msblksMessages:VctrlPlotYLabel').getString);
    title(message('msblks:msblksMessages:LockTimePlotTitle',num2str(lock_t),lock_u).getString);%;
else
    LockTime=0;
    disp(message('msblks:msblksMessages:VctrlNotStable').getString);
end

