function eval_minblep()

nsin = 4096;
nharm_max = 1800;
L = 48000/2;
fs = 48000;
fstart = 440;
fend = 440;
f2start = 200;
f2end = 600;
df = (fend-fstart)/L
df2 = (f2end-f2start)/L
saw = 0;

% Calc blep table
nharm = min(fix((fs/fstart/2.0)) + 1, nharm_max)
Hw = kaiser(nsin, 8);
xx = (0:nsin-1)/nsin - 0.5;

for mm=1:nharm
    blitm(mm,:) = sin(xx*(mm-1)*pi)./sin(xx*pi).*Hw';
    blitm(mm,(find(isnan(blitm(mm,:))))) = (mm-1);
end;

for mm=1:nharm
    blepm(mm, :) = cumsum(blitm(mm, :))/nsin;
end;

w = [1; 2*ones(nsin/2-1,1); ones(1 - rem(nsin,2),1); zeros(nsin/2-1,1)]';
for mm=1:nharm
    x_rc = real(ifft(log(abs(fft(blitm(mm, :))))));
    y = real(ifft(exp(fft(w.*x_rc))));
    minblepm(mm, :) = cumsum(y)/nsin;
end;

x = 0;
x2 = 0;
z = 0;
f = fstart;
f2 = f2start;
tri = 0;
NLG = 2;
h = lagrange(1, 0.35)
startup = 1;
blep = 1;
for n = 1:L,

    if x >= 1 || startup,
        x = 0;
        p = fs/f;
        dx  = 1.0/p;
        m = min(fix((p/2.0)) + 1, nharm_max);
        blep_offset = 0;
        blep_gain = 1;
        z = ~z;
    end;
    if x2 >= 1 || startup,
        x2 =0;
        dx2  = f2/fs;
%        blep_offset = -(1-x);
%        blep_gain = x;
%        x = 0;
%        z = ~z;
    end;
    startup = 0;
    
    nn = (x+0.0)*(nsin-1) + 1;
    ni = fix(nn);
    nf = nn - ni;
    h = lagrange(NLG, nf);
    blep = h(NLG+1)*minblepm(m, max(1, ni));
    j = 1;
    for i = NLG:-1:1
        blep = blep + h(i)*minblepm(m, max(1, ni-j));
        j = j + 1;
    end;

    saw = x - blep_gain*blep + blep_offset;
	if (z == 0)
        sqr = blep;
    else
        sqr = 1-blep;
    end
    tri = tri + 2*(sqr-0.5)*dx;
	vsqr(n) = 0.5*(sqr-0.5);
	vtri(n) = tri;
	vsaw(n,1) = x;
	vsaw(n,2) = saw+0.5;
	vblep(n,1) = x;
	vblep(n,2) = blep;
	x = x + dx;
	f = f + df;
    x2 = x2 + dx2;
	f2 = f2 + df2;
end;
		

close all
plot(1:nsin, blepm(fix(nharm/2), :), 1:nsin, minblepm(fix(nharm/2), :)); grid;

wavwrite(0.5*vtri, fs, 'tri.wav');
wavwrite(0.5*vsqr, fs, 'sqr.wav');
wavwrite(0.5*vsaw, fs, 'saw.wav');
wavwrite(0.5*vblep, fs, 'blep.wav');

function h = lagrange(N, delay)
    %LAGRANGE h=lagrange(N,delay) returns order N FIR
    % filter h which implements given delay
    % (in samples). For best results,
    % delay should be near N/2 +/- 1.
    n = 0:N;
    h = ones(1,N+1);
    for k = 0:N
        index = find(n ~= k);
        h(index) = h(index) * (delay-k)./ (n(index)-k);
    end
