Fixed logic errors and added extra logging