Moved some doctests to unittests. Some code polishing.