implementing the algo