Refactor and fix some issues