major re-factoring to make code cleaner with more test coverage