Added the main algorithm