Write test and various bug fixes.