I just realized that ImageMagick had a -auto-orient switch. No need for all that code.