#!/usr/bin/env python

import sys
import os.path
import PythonMagick

if __name__ == '__main__' :
	if len(sys.argv) < 2 :
		print 'need files.'
		sys.exit(1)
	
	for fn in sys.argv[1:] :
		print 'process %s' % fn
		if not os.path.exists(fn) :
			print 'could not access %s' % fn
			sys.exit(1)
		image = PythonMagick.Image(fn)
		orient = int(image.attribute('EXIF:Orientation'))
		orients = {
			1 : 0,
			8 : 90,
			3 : 180,
			6 : 270
		}
		if orient not in orients :
			# see http://sylvana.net/jpegcrop/exif_orientation.html
			print 'EXIF Orientation %d unknown for %s' % (orient, fn)
			sys.exit(1)
		orient = orients[orient]
		print 'orientation is %d' % orient
		if orient == 0 :
			continue
		orient = -float(orient)

		image.rotate(orient)
		#image.attribute('EXIF:Orientation', '1')

		image.write(fn)
