Refactor and add documentation