complete main algorithm