Currently there are some duplicate logics in this function. We need to refactor and combine some match branches to make the code concise.