%% ===========================================================================
% Copyright (C):
%     2000-2003 by Forschungszentrum Telekommunikation Wien, Austria;
%                                                     All rights reserved. 
%
% Description   : Calculates the maximum possible bitrate of a SDSL-modem
%                 in a given scenario. 
%
% Project       : FTW's xDSLsimu
%
% Author(s)     : Tomas Nordstrom (Tomas.Nordstrom@FTW.at)
%               : Gernot Schmid (gernot.schmid@arcs.ac.at)
%
%
%% ===========================================================================

%% ===========================================================================
% Change History
%      2000-11-02 (GS) Created
%      2000-11-07 (GS) Made the iteration procedure converging faster 
%      2003-11-03 (ToNo) Lists now use cell arrays for both Octave and Matlab
%% ===========================================================================

clear all;
global ex;
global res;

% Test if we have problem reading numbers in international OS versions
if 3 == 3.14,
    error(['Matlab thinks 3 is equal to 3.14, ' ...
           'please use an US (or posix C) version of the system. ' ...
           'Or add LC_NUMERIC=us into $MATLAB/bin/.matlab5rc.sh' ]);
end

ex.param    = setupParam;  % basic default simulation Parameter

ex.tfplist  = itu_tfplanHAM([]);                % Need a HAM band definition
ex.tfplist  = fsan_modelsMISC(ex.tfplist);     % Get plans for alien noise
ex.tfplist  = etsi_noisesSDSL(ex.tfplist);
ex.tfplist  = etsi_tfplansVDSL(ex.tfplist);     % Get plan VDSL-FDD
ex.tfplist  = etsi_tfplansSDSL(ex.tfplist);

ex.lclist   = setupLClist;                      % Line code definition (Theo.)
ex.lclist   = etsi_lcdefsADSL(ex.lclist);           % Line code definitions (ADSL)
ex.lclist   = etsi_lcdefsSDSL(ex.lclist);       % Line code definitions (SDSL)

ex.clist    = etsi_cablesSDSL([]);                  % Get ETSI (and ANSI) cables;


% Determines how the generic name ADSL is mapped to a specific linecode
xDSL.name='ADSL';     
xDSL.used='ADSL';
ex.param.xDSLlist=insertList(ex.param.xDSLlist,xDSL);

gui.ttlist  = fsan_loopsVDSL([]);                   % Def. of some FSAN Topologies
gui.ttlist  = UserLoopsSDSL(gui.ttlist);      % Def. of some Example Loops
ex.param.NoiseModel='Calculate';   	        % Use predefined noise models or 'Calculate'

% Symbolic name for the Modem considered.
% Note that the same must be used in the traffic struct
if 1
    ex.param.modemlist=str2mat('SDSL-sym');  % Consider symmetric-PSD SDSL 
else
    ex.param.modemlist=str2mat('SDSL-asym'); % Consider asymmetric-PSD SDSL
end


scenario='SDSL-Scenario 1';                  % Scenario to be investigated

% Margin to be met (includes 1.6 dB for implementation loss) 
target_margin=0;  

bitrate_range=128:64:2304;       % Bitrate range and iteration step definition

%===================== End of Set up Parameter section ======================


ex.tt       = getList(gui.ttlist,scenario);     % Get the scenario
% Show traffic and topology structure
figure; 
plotTTstructure(ex.tt);
drawnow; % Show it now


bkup_list=ex.param.modemlist;                   % Save original modemlist

% Check if there are only SDSL Services in modemlist:
[no_dm,strlen]=size(ex.param.modemlist);

if no_dm > 1
    message=sprintf('Only one SDSL Modem can be considered for max Bitrate calculation');
    error(message);
end

if ~strncmp(ex.param.modemlist,'SDSL',4)
    message=sprintf('Modemlist contains non-SDSL Services !!');
    error(message);
end


% Extract considered modems from traffic struct
dm=getDM(ex.tt.traffic,ex.param.modemlist); 

% Some parameters needed for the search
tmp=diff(bitrate_range);
ratestep=tmp(1);
st(1)=bitrate_range(length(bitrate_range))+ratestep;
gt(1)=bitrate_range(1);
minmargin = target_margin+1; % Start value (any value > target margin)
cnt=0;
quitloop=0;
% h = waitbar(0,'Max Bitrate Computation in Progress, Please wait...');

% Search for max bit-rate
while quitloop==0  
    
    cnt=cnt+1;  
    newrange=gt(cnt):ratestep:st(cnt);
    newrate=newrange(round(length(newrange)/2)); % Bitrate start value 
    
    oldmargin=minmargin;
    ratestr=[bkup_list '-' int2str(newrate)];
    ex.param.modemlist=ratestr;
    
    % Modify traffic struct to make the i-th modem flexible in bitrate:
    ex.tt.traffic{dm}{3} = ratestr;
    
    % Create needed linecodes and tfplans for the used SDSL services
    ETSI_SDSL_traffic2lctf;
    
    % Evaluate this experiment at a specific bitrate for the considered service
    result = evalExperiment; 
    
    % Evaluate the margin
    [bitrate_LT, bitrate_NT, margin_LT, margin_NT] = calcXDSLresult(ex,result);
    minmargin=min(margin_LT,margin_NT);
    
    if minmargin(1)==target_margin             
        quitloop=1;
    end
    
    if minmargin(1)< target_margin
        double=find(st==newrate);
        if isempty(double)
            st(cnt+1)=newrate;
            gt(cnt+1)=gt(cnt);
        else
            quitloop=1;
        end
    end
    
    if minmargin(1)> target_margin
        double=find(gt==newrate);
        if isempty(double)
            gt(cnt+1)=newrate;
            st(cnt+1)=st(cnt);
        else
            quitloop=1;
        end
    end
%    waitbar(10*cnt/100,h)

end % while
% close(h)

if (newrate==bitrate_range(1))& (minmargin(1)<target_margin)
    resmargin_LT=0;
    resmargin_NT=0;
    maxrate=0;
else
    resmargin_LT=margin_LT(1);
    resmargin_NT=margin_NT(1);
    maxrate=newrate;
end

% Show the result in the command window
tmp=ex.tt.traffic{dm};
servicename=bkup_list;
node=tmp{2}-1;
fprintf('\n\nMaximum available Bitrate for %14s (from CO to NT%d)\n', ...
        servicename,node);
fprintf('Max.Bitrate: %g kBitps\n',maxrate);
fprintf('Resulting margin: \tLT:%2.2fdB \tNT:%2.2fdB',...
        resmargin_LT,resmargin_NT);
fprintf('   (target margin:%2.2fdB)\n\n',target_margin);