implemented most of the algo