refactor and split into better functional chunks