Re-factored and added unit tests.