Major refactoring. Added unit tests