Bug fixes, refactoring, more doctests
Refactoring