Extract main function.
Add some doctests.