commented main algorithm