implemented main algorithm