Implementing the main algorithm