Fix some subtle bugs and tests for coverage