%% ===========================================================================
% Copyright (C) 2000 by Forschungszentrum Telekommunikation Wien, Austria;
%                                                     All rights reserved. 
% Description   : Calculates the resulting margin of a SDSL transmission 
% 						on an ETSI testloop
%
% Project       : B1, FTW
% Author(s)     : Tomas Nordstrom (Tomas.Nordstrom@FTW.at)
%               : Gernot Schmid (gernot.schmid@arcs.ac.at) 
%
% Reference:
%    ETSI STC TM6 Permanent document TM6(98)10, 980p10a3
%    ETSI Helsinki 2000, WD22R3 & WD19R3, 002t22a0
%
% CVS:       $Id: ExSDSLtestloop.m,v 1.1 2000/11/10 10:18:24 tono Exp $
%% ===========================================================================

%% ===========================================================================
% Change History
%      2000-10-25   (GS) Created as Testloop-Ex.m 
%% ===========================================================================

global ex;
global res;

format compact;

%======================= Parameter Set up Section ============================
plotit=1;      % If set graphical output of scenarion and results is enabled
plot_detail=0; % If set, additionally detailed loop information will be shown  

ex.param    = setupParam;                       % Basic default simu. parameter

ex.tfplist  = itu_tfplanHAM([]);                % Need a HAM band definition
ex.tfplist  = fsan_noise(ex.tfplist);
ex.tfplist  = etsi_tfplansSDSL(ex.tfplist);

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

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

% Use predefined noise models or 'Calculate'
ex.param.FSANNoiseModel='Model SDSL Noise A';   

ex.param.modemlist=str2mat('SDSL-asym-2048');   % Linecode to be investigated

% Testloop to be investigated (defined in 'etsi_loopsSDSL.m')
scenario='SDSL-Loop6';  

testlooplength=1000; % meter; if not defined or set to zero default values are used 

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

% Get bitrate from linecode name
dash_index=find(ex.param.modemlist=='-');
bitrate=1e3*str2num(ex.param.modemlist(dash_index(2)+1:length(ex.param.modemlist)));

% If not defined use default testloop length
if (exist('testlooplength')~=1)|(testlooplength==0) 
    loopindex=str2num(scenario(end));
    testlooplength=etsi_loopsSDSLdeflen(ex.param.FSANNoiseModel,bitrate,...
                                          ex.param.modemlist, loopindex);
end

% Definition of ETSI-SDSL testloops   
gui.ttlist  = etsi_loopsSDSL([],testlooplength);  

% Change generic name 'SDSL' in Testloop Traffic-struct into the specified one
ex.tt              = getList(gui.ttlist,scenario); % Get the scenario
ex.tt.traffic(1,3) = cellstr(ex.param.modemlist);

% Create needed linecodes and tfplans for all SDSL services in the scenario
ETSI_SDSL_traffic2lctf;

if plotit   
    % Show traffic and topology structure
    figure; 
    plotTTstructure(ex.tt);
    drawnow; % Show it no
end;

fprintf('\n\n==============================================\n');
fprintf('Margin Calculation for SDSL Testloop:\n');
fprintf('\nTestloop: %s,   length: %d m,   Noise Model: %s \n\n',...
        scenario,testlooplength,ex.param.FSANNoiseModel);    

% Evaluate this experiment at a specific bitrate
result = evalExperiment; 

% Evaluate the margin
[bitrate_LT, bitrate_NT, margin_LT, margin_NT] = calcFSANresult(ex,result);
minmargin=min(margin_LT,margin_NT);

% Present resulting margins on the screen
dm=getDM(ex.tt.traffic,ex.param.modemlist); 
for current =1:length(result)
    tmp=ex.tt.traffic(dm(current),:);
    servicename=tmp{3};
    node=tmp{2}-1;
    fprintf('\nBitrate: \t\tLT:%g kBitps \tNT:%g kBitps\n',...
            bitrate_LT(current)*1e3,bitrate_NT(current)*1e3);
    fprintf('Resulting margin: \tLT:%2.2fdB \tNT:%2.2fdB\n\n',...
            margin_LT(current),margin_NT(current));
end

% Plot some loop details if wanted
if plot_detail,  
    % Get the cable information and plot it
    segs=size(ex.tt.topology);
    f= ex.param.frequency.f;
    Att=getAtt(ex,1,segs(1),ex.tt.topology,f,ex.param.Zterm);
    figure;
    plot(f,Att,'m');
    titlestr=sprintf('SDSL loop attenuation');
    title(titlestr);
    legendstrs=sprintf('%s',scenario);
    legend(legendstrs);
    xlabel('Frequency');
    ylabel('dB');
    grid on;
    
    % Plot signals and noises at LT and NT
    for current =1:length(result)
        f=ex.param.frequency.f;
        NT_Rx=result(current).NT.Rx_signal;
        LT_Rx=result(current).LT.Rx_signal;
        NT_Tx=result(current).NT.Tx_signal;
        LT_Tx=result(current).LT.Tx_signal;
        NT_TotNoise=result(current).NT.Tot_noise.down;
        LT_TotNoise=result(current).LT.Tot_noise.up;
        SNR_NT = (NT_Rx)./(NT_TotNoise);
        SNR_LT = (LT_Rx)./(LT_TotNoise);
        
        modem=result(current).Modem.Name;
        LTnode=result(current).Modem.LT_Node;
        NTnode=result(current).Modem.NT_Node;

        figure;
        plot(f,10*log10(abs(NT_Tx)),...
             f,10*log10(abs(LT_Rx)),...
             f,10*log10(abs(LT_TotNoise)));
        legend('Tx PSD (NT)','Rx PSD (LT)','Total noise');
        axis([0,2e6,-140,-30]) 
        grid on;
        title(['Signals and noises for LT  for ' modem ' ' int2str(LTnode) ' - ' int2str(NTnode)]);
        figure;
        plot(f,10*log10(abs(SNR_LT)),f,10*log10(abs(SNR_NT))) 
        axis([0,2e6,-60,60]) 
        grid on;
        title(['SNR for LT and NT for ' modem ' ' int2str(LTnode) ' - ' int2str(NTnode)]);
        legend('LT','NT');
    end % for
end % if plot_detail


% Show  the simulation results graphically
if plotit,
    faxis.min=1e3;
    faxis.max=1.5e6;
    axvec=[faxis.min faxis.max ex.param.backgroundNoise-20 0];

    ftype='Linear'; % prepare for plotting
    
    % Plot the result from experiment
    for current=1:length(result),
        figure;
        tmp_str=sprintf('SDSL Simulation Result, Modem %d (%s-%s)',...
                        current, ...
                        ex.tt.topology{result(current).Modem.LT_Node,3}, ...
                        ex.tt.topology{result(current).Modem.NT_Node,3});
        set(gcf,'NumberTitle','off','Name',tmp_str);

        % Plot the LT side
        subplot(211)
        plotResult(ex,result,current,'LT',ftype,faxis);

        % Plot the NT side
        subplot(212)
        plotResult(ex,result,current,'NT',ftype,faxis);
    end
end