refactor the code extracted from original libpomelo