code cleanup: split function into three