function i = binsearch( vec, val )
%i = binsearch( vec, val )
%   Find that i such that vec(i-1) < val <= vec(i), where vec(0) and
%   vec(length(vec)) are notionally considered to be -Inf and +Inf.
%   val may be a vector, in which case i will be a column vector of the
%   same length.

    i = zeros(length(val),1);
    for vi=1:length(val)
        lo = uint32(1);
        hi = uint32(length(vec));
        while hi > lo
            mid = bitshift( lo+hi, -1 );
            if val(vi) <= vec(mid)
                hi = mid;
            else
                lo = mid+1;
            end
        end
        i(vi) = lo;
    end
end
