function [binNb, width]  = refineScore(mag,binNb)

toneFactor = 2^(1/12);

firstBin = floor((binNb+1)/toneFactor)-2;
lastBin = ceil((binNb+1)*toneFactor)+2;
firstBin = max(firstBin,1);
width =0;
if (firstBin<lastBin-1)
    %pitch refinment
    [maxB,indMax ]= max(mag(firstBin:lastBin));
    maxIdx = firstBin+indMax-1;
    if (maxB <0.9)
    binNb =0;
    elseif (maxIdx ~= lastBin && maxIdx ~= firstBin)
        a = log(mag(maxIdx-1));
        b = log(mag(maxIdx));
        c = log(mag(maxIdx+1));
        binNb = (maxIdx + (a - c)/(2*(a-2*b+c)))-1;
        minIdx = floor(binNb);
        maxIdx = ceil(binNb);
        while(minIdx>0&&mag(minIdx)>0.1*maxB)
            minIdx = minIdx-1;
        end
        while(mag(maxIdx)>0.1*maxB)
            maxIdx = maxIdx+1;
        end
        width = 2*min( maxIdx -binNb+1,binNb- minIdx+1);
        width = max(width,3);
    else
%         plot(mag(1:maxIdx+10))
%         close all;
    end
end

