Refactor and reorganize code to separate concerns