code refactor from rob, additional changes to logic