Implemented main algorithm