function fit = FindOpt(p,d,dd)
p
%init the code vector
ddcode = zeros(1,length(dd));
%quantize the first derivative
ddcode(find(dd<p(1)))=0;
    ddcode(find(dd>=p(1) & dd<p(2)))=1;
    ddcode(find(dd>=p(2) & dd<p(3)))=2;
    ddcode(find(dd>=p(3) & dd<p(4)))=3;
    ddcode(find(dd>=p(4) & dd<p(5)))=4;
    ddcode(find(dd>=p(5) & dd<p(6)))=5;
    ddcode(find(dd>=p(6) & dd<p(7)))=6;
    ddcode(find(dd>=p(7) & dd<p(8)))=7;
    ddcode(find(dd>=p(8) & dd<p(9)))=8;
    ddcode(find(dd>=p(9) & dd<p(10)))=9;
    ddcode(find(dd>=p(10) & dd<p(11)))=10;
    ddcode(find(dd>=p(11) & dd<p(12)))=11;
    ddcode(find(dd>=p(12) & dd<p(13)))=12;
    ddcode(find(dd>=p(13) & dd<p(14)))=13;
    ddcode(find(dd>=p(14) & dd<p(15)))=14;
    ddcode(find(dd>=p(15)))=15;

dl = zeros(1,length(ddcode));
for i=2:length(ddcode)
    dl(i) = dl(i-1)+ p(ddcode(i)+16) - .125*dl(i-1); % .* w';
end

fit = mean((d(2:end)-dl').^2);