function [samples,weights]=ImportanceSampling(N,pfun,qfun,draw,range)
  
  % ImportanceSampling  Create samples with the Importance Sampling method
  %
  % [samples,weights]=ImportanceSampling(N,pfun,qfun,draw,range)
  % N=# of samples
  % pfun: Target original function (see define function)
  % qfun: Proposal function (see define function)
  % draw: 1, draw result information, 0 just sample
  % range: range values to draw
  % samples: sample values
  % weights: weights of the samples
  
  
  % 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

  samples = qfun.fun(1, N, qfun.param{:});       %U
  q = qfun.fun(0, samples, qfun.param{:});       %q(U)
  weights = pfun.fun(0,samples,pfun.param{:})./q;    %weights 
  weights=weights/sum(weights);                          %Normalize weights
  
  
  if ~draw
      return;
  end
% ----------------------------------------------------------- PLOTTING
  

  %Draw qfun and pfun
  subplot(411)
  hold on;
  p= pfun.fun(0,range,pfun.param{:}); 
  plot(range,p,'g','LineWidth',3);
  q= qfun.fun(0,range,qfun.param{:});
  plot(range,q,'r','LineWidth',2);
  h=legend('p(C)','q(C)');
  set(h,'FontSize',12);
  title('a) Funciones de densidad','FontSize',12);


  %Draw number of samples 
  subplot(412)
  HistogramCount(samples);
  title('b) Numero de muestras','FontSize',12);
  xlim([min(range),max(range)]);
 
  %Draw weights, unnormalized
  subplot(413)
  w=p./q;
  w(q==0)=0; %As q(range) can be evaluated in regions where samples are not created, we correct the value, making it 0
  plot(range,w,'-','Color',[0.5 .5 .5],'LineWidth',2);
  ylims = ylim();
  ylim([-0.05 ylims(2)]);
  xlim([min(range),max(range)]);
  title('c) p(C)/q(C)','FontSize',12);
 
  %Draw weighted histogram
  subplot(414)
  HistogramWeighted(samples,weights);
  hold on;
  plot(range,p,'g','LineWidth',3);
  h=legend('Hist.','p(C)');
  set(h,'FontSize',12);
  title('d) Histograma','FontSize',12);
  xlabel('Concentracion (%)','FontSize',12);
  ylims = ylim();
  ylim([-0.05 ylims(2)]);
  xlim([min(range),max(range)]);
  hold off
  
 
                                              
                                              
 