Refactor and organize code