Refactor and minor fixes