Look at any program. they are all similar. at the top, you include the libraries. then you declare the variables. after that you write the functions. at the bottom, you have void(setup)
divide the code being added as noted above. include the libraries you need to add, insert the new variables you need, changing any that conflict with the existing code. paste in the new functions. add the necessary steps to void(setup)
it is a case of sorting apples from oranges, and sending the components of the incoming sketches to where they belong.