I think it's reading from the back of the file looking for the last z move to get the height.
One way around it is to put your start and end gcode into the start.g and stop.g files. Start.g gets called before the print gcode file starts and stop.g gets called by having M0 in your end gcode section in the slicer. You can also call custom macros from the start and end gcode section of the slicer with M98.