function eval_blep_hs()

nsin = 1024;
nharm_max = 256;
L = 4800;
fs = 48000;
fstart = 44;
fend = 44;
df = (fend-fstart)/L


% 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,
    bb(mm, :) = sin((mm-1)*xx*pi);
end;
aa = sin(xx*pi);

for mm=1:nharm
    for nn=1:length(xx)
        if (aa(nn) == 0)
            blitm(mm,nn) = (mm-1);
        else
            blitm(mm,nn) = bb(mm, nn)/aa(nn).*Hw(nn);
        end
    end
end;
for mm=1:nharm
    blepm(mm, :) = cumsum(blitm(mm, :))/nsin;
end;

%blep2 = blepm(nharm_max/2+1, :)'
%aa2 = aa(:)'
%bb2 = bb(nharm_max/2+1, :)'

x = 0.0;
x2 = -0.5;
z = 0;
f = fstart;
f2 = 0.6*f;
dx2 = f2/fs;
tri = 0;
NLG = 2;
h = lagrange(1, 0.35)
sync = 0;
restart = 0;
startup = 1;
minblep_active = 0;
minblep_count = 0;
minblep_length = 200;
minblep = 1-(0:minblep_length-1)/minblep_length;
for n = 1:L,

    sync = 0;
    if startup,
        x = 0.0;
        startup = 0;
		p = fs/f;
		dx  = 1.0/p;
		m = min(fix((p/2.0)) + 1, nharm_max);
		z = 0;
    end;
    if (x >= 0.5),
		x = x - 1;
		p = fs/f;
		dx  = 1.0/p;
		m = min(fix((p/2.0)) + 1, nharm_max);
		z = ~z;
	end;
	if (x2 >= 0.5),
		x2 = x2 - 1;
        sync = 1;
        startup = 1;
        minblep_count = minblep_length;
	end;
    nn = (x+0.5)*(nsin-1) + 1;
    ni = fix(nn);
    nf = nn - ni;
    
    h = lagrange(NLG, nf);
    blep = h(NLG+1)*blepm(m, max(1, ni));
    j = 1;
    for i = NLG:-1:1
        blep = blep + h(i)*blepm(m, max(1, ni-j));
        j = j + 1;
    end;
    if (minblep_count > 0)
        saw = saw_last - minblep(minblep_count)/(1-2*saw_last+minblep_length*dx);
        minblep_count = minblep_count - 1;
        minblep_active = 1;
    else
        minblep_active = 0;
        saw = x - blep;
        saw_last = saw;
    end
	if (z == 0)
        sqr = blep;
    else
        sqr = 1-blep;
    end
    tri = tri + 2*(sqr-0.5)*dx;
	vtri(n) = tri;

	vsaw(n) = 2*(saw+0.5);
	vsqr(n) = 0.5*(sqr-0.5);
	vblep(n) = blep;
    vx(n) = x;
    vsync(n) = sync;
    vminblep_active(n) = minblep_active;
	x2 = x2 + dx2;
	x = x + dx;
	f = f + df;

end;
		

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

figure;
subplot(3, 1, 1)
plot(1:L, vx, 1:L, vsync, 'r'); grid;
subplot(3, 1, 2)
plot(1:L, vblep); grid;
subplot(3, 1, 3)
plot(1:L, vsaw, 1:L, vminblep_active); 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
