Refactor

Refactor for most of the code.
Added unit tests.