working on ivan's algorithm