updated main algorithm