Refactor and add more documentation