Refactor code; add unit tests