Algorithm works better now