CFY-644 refactor some
CFY-644 some more refactoring
CFY-644 (not the prettiest) bug fix