refactor and fix some issues