#!/usr/bin/python
# -*- coding: utf-8 -*-
from sys import argv, exit, stderr
from os.path import isdir
from os      import  mkdir, rename

WIDTH=640
HEIGHT=480
BROKENPATH='broken_images'

if len(argv) <= 1 :
  print "Usage: %s <JPEG file>" % argv[0]
  exit(-1)

import Image

imagefile = argv[1]

try:
    im = Image.open(imagefile)
except IOError, err:
    print >>stderr, "Unable to open %s (%s)" % (imagefile, err) 
    exit(-1)

if not im.format.startswith('JPEG'):
    print >>stderr, "File %s is not in JPEG format" % (imagefile) 
    exit(-1)
if im.size[0] != WIDTH:
    print >>stderr, "File %s has unexpected width (%i) instead of %i." % (imagefile, im.size[0], WIDTH) 
    exit(-1)
if im.size[1] != HEIGHT:
    print >>stderr, "File %s has unexpected height (%i) instead of %i." % (imagefile, im.size[1], HEIGHT) 
    exit(-1)
if not im.mode.startswith('RGB'):
    print >>stderr, "File %s is not in RGB mode" % (imagefile) 
    exit(-1)

try:
    lastpixel = im.getpixel((WIDTH-1,HEIGHT-1))
except IOError, err:
    if not isdir(BROKENPATH):
        try:
            mkdir(BROKENPATH)
        except:
            print >>stderr, "Unable to create directory %s." % BROKENPATH
            exit(-1)
    rename(imagefile, BROKENPATH+'/'+imagefile)
    print "Image %s seems to be truncated (%s) and so it was moved to directory %s." % \
           ( imagefile, err, BROKENPATH)
    exit(1)

# print lastpixel

