Add check to prevent write-after-end error