Big refactor and enhancement