Merged changes from @blackwhale. Added and fixed unit tests.
Merged changes from @blackwhale. Added and fixed unit tests.