I am confident this version should produce correct result
Fixed the bug for empty interval