% datos
%H = [0 1   2   3    4   5   6    7    8;
%     0 0.2 0.3 0.15 0.1 0.1 0.05 0.05 0.05];
 

H = [  0,  1,   2,   3,   4,   5,   6,   7;
     0.0,0.3, 0.1, 0.3, 0.1, 0.1,0.05,0.05;]
 
%H = [ 0,   1,   2,   3,   4;
%      0, .25, .25, .25, .25];


R = 4;
periodo = 1;
buffer = 6; 
frames = 20000;
pruebas = 100;

fprintf('R = %g, B = %g, T = %g, frames = %g\n\n', R, buffer, periodo, frames);

% Primero calcula el buffer por histogramas
fprintf('1... Calculando por histograma');
[BH, CLR1, i] = HML_PBufferSP(H(2,:), R, buffer);
RFBH = [ linspace(0,length(BH)-1, length(BH)) ; BH]; 
fprintf(' OK! CLR = %g\n', CLR1);

% Segunda simula el buffer
fprintf('2... Calculando por simulación %g pruebas\n\n', pruebas);
for i = 1:pruebas
    % Genera trafico
    T = HML_HGenTraffic(H, frames, false);
    %B = HML_Load( T, R, periodo, buffer);
    [B, CLR(i)] = HML_Buffer( T, R, periodo, buffer);
    BS = HML_HistB( B, RFBH(1,:));
    DIFF(i) = norm(RFBH(2,:)-BS(2,:));
    fprintf(' [%g] CLR = %g Diff = %g\n', i, CLR(i), DIFF(i));
end

[MUHAT, SIGMAHAT, MUCI, SIGMACI] = normfit(DIFF);
fprintf('\n OK! DIFF = %g  95%% [%g,%g]\n', MUHAT, MUCI(1), MUCI(2));
[MUHAT, SIGMAHAT, MUCI, SIGMACI] = normfit(CLR);
fprintf('      CLR = %g  95%% [%g,%g]\n', MUHAT, MUCI(1), MUCI(2));


clf

bar(H(1,:), H(2,:));
xlabel('traffic load in period (cells)');


% Dibujamos
todos = 0;
if todos 
subplot(3,2,1)
bar(H(1,:), H(2,:));
title('Load Histogram');
xlabel('traffic load in period');
subplot(3,2,2)
plot(T)
title('Simulation traffic'); 
xlabel('traffic in period');
subplot(3,2,3)
bar(RFBH(1,:),RFBH(2,:));
title('buffer Histogram');
xlabel('cells in buffer');
subplot(3,2,4)
bar(RFBH(1,:),BS(2,:));
title('Simulation Histogram');
xlabel('cells in buffer');
subplot(3,2,5)
bar(RFBH(1,:),RFBH(2,:)-BS(2,:));
title('Absolute Difference ');
xlabel('cells in buffer');
subplot(3,2,6)
B2 = [RFBH(2,:); BS(2,:)];
bar(RFBH(1,:),B2');
legend('Histogram','Simulation');
title('All');
xlabel('cells in buffer');
end

