Refactor code and enhance migrate script