Refactor and fix minor errors