kindof finalized version of both algrorithms