[BUG FIX] algorithm taking care of all cases
[BUG FIX] algorithm taking care of all cases