Implementing David's algorithm