Needs rework of alogrithm