refactor and fix multiple issues