1st part of the algo should work properly, the second still has problems