some changes to algorithm