fixed some logic errors that surprisingly did not show up until some funky data appeared.