second refactor and minor corrections