Add more unittests and comments. Minor refactorings.