Major refactorization and unit testing