Some refactoring. Added some tests