Do you realize you don't have $target_encoding defined in the second one (like you do in the first)?
Sorry, I cut and pasted badly, but it was just above the section I pasted. I later rearranged that so it's more in the order of the working one, but it still doesn't work.