Complete refactoring code - have not tested yet