function [samples,weights]=WeightedResampling(samplesinit,weightsinit,resample,draw,range,pfun)


  % WeightedResampling   Weighted Resampling method
  %
  % [samples,weights]=WeightedResampling(samplesinit,weightsinit,resample,draw,range)
  %
  % sampleinit: initial sample values 
  % weightsinit: initial weights       
  % resample: r(U) in the initial values
  % draw: 1, draw result information, 0, just sample
  % range: range values to draw
  % pfun: p(I) funtion (only to draw)
  
  
  % APRENDIZAJE AUTOMÁTICO (G. Pajares y J. M. de la Cruz, Eds.)
  % Editorial: RA-MA
  % Capítulo 7 y 8: Monte Carlo I y II
  % Autores: Eva Besada-Portas, Sergey M. Plis

  
% ------------------------------------------------------------ SAMPLING

N=length(samplesinit);
index = randsample(1:N,N,true,resample); %Resampling method with replacement.
samples=samplesinit(index);              %new samples
weights=weightsinit(index)./resample(index); %new weights
weights=weights/sum(weights);                %normalized weights
  
if ~draw
    return;
end

% ----------------------------------------------------------- PLOTTING


% original and new weights, and r(I=
subplot(411)
[sorted,ind]=sort(samplesinit);
plot(sorted,weightsinit(ind)/sum(weightsinit),'-g','LineWidth',2);
hold on;
plot(sorted,resample(ind)/sum(resample),'-r','LineWidth',2);
[sorted,ind]=sort(samples);
plot(sorted,weights(ind),'-','Color',[.5 .5 .5],'LineWidth',2);
title('a) Pesos','FontSize',12);
h=legend('Inicial','r(C)','Final');
set(h,'FontSize',12);
xlim([min(range),max(range)]);  

 %Histogram counts of the initial samples
 subplot(412)
 HistogramCount(samplesinit);
 title('b) Numero de muestras originales','FontSize',12);
 
 xlim([0,100]);

 %Histogram counts after resampling
 subplot(413)
 HistogramCount(samples);
 title('c) Numero de muestras despues del remuestreo','FontSize',12);
  xlim([min(range),max(range)]);  

 
 %Draw weigthed histogram
subplot(414)
HistogramWeighted(samples,weights);
hold on;
r= pfun.fun(0,range,pfun.param{:}); 
plot(range,r,'g','LineWidth',3);
h=legend('Hist.','p(C)');
set(h,'FontSize',12);
title('d) Histograma','FontSize',12);
ylims = ylim();
ylim([-0.05 ylims(2)]);
xlim([min(range),max(range)]);  
xlabel('Concentracion (%)','FontSize',12);
  

