refactors to make more testable and adds fully implemented test