refactor and minor fixes