code refactor and minor fixes