How to avoid code duplication in a function?

So any suggestions?

I don't see why you cannot use a function to group those tasks together.

To communicate with the function, you can use parameters, or global variables, or a "payload": a collection of dissimilar things in a struct. So before executing that function, you load the payload with the right parameters / pointers, and then execute the function (passing the payload to it).