memory leak fixes plus small algo tweak