refactor intermediate functions out, code cleanup