Fixed some logic errors according to test case results. More debugging to go