Refactor to small functions