Various improvements and added unit tests.