Refactor & add unit tests