Fixed various bugs (found with upcoming integration tests).