changed bisect to more sophisticated version