fixed and tested algorithm