Adding more tests and extracting more code

Adding more tests and extracting more logic into `lib` for greater readability.