These lines are copied several times.  Could you extract that into a function or method so this does not get repeated so often?  Repetition also means that if an error is spotted in these lines, it needs to be fixed in lots of places.