This whole chunk of code might be more readable if all the tmxWriter calls were together, so that it is easy to see what is being written in what order - the details of how each of the items are generated is at a lower level of abstraction so should not be mixed in, and ideally should be in separate methods (though that would be overkill for some of it).