#!/usr/bin/env python
import os, sys
import Image
import getopt

#default values
size=(120,120)
prefix="t_"
qual=80


def usage():
    print  """    
p-thumb [-s <max_thumb_size> | -H <max_thumb_height>] [-p <out_filename_prefix>]
        [-q <quality>] file1 [file2 [...]]
        
Geneartes thumbnails for all the file specified on command line. Accepts a wide
range of input formats. Always generates JPEG files.

   -s   maximus size, that is the value for the gratest between
        height and width, dafault=%d
    
   -H   maximum height, so all the thumbnails will have the same height
        
   -p   prefix to be used for thumbanils image file names, cannot be an empty
        string, default=%s
        
   -q   quality of generated thumbnails, min=0, max=100, default=%d"
    
For more information visit http://ppgal.sourceforge.net/
"""%(size[0],prefix,qual)


try:
    (opt,arg)=getopt.gnu_getopt(sys.argv[1:],"hs:H:p:q:")
except :    
    usage()
    sys.exit()

for j in opt:
    if j[0]=="-s": #Define the thumbnails max size
       size=(int(j[1]),int(j[1]))
       print "", j[1]
    if j[0]=="-H": #Define the thumbnails max height
       size=(int(j[1])*100,int(j[1]) )
    if j[0]=="-p": #Define the prefix for names
        prefix=j[1]
    if j[0]=="-q": #Define the quality of output JPEG
        qual=int(j[1])
    if j[0]=="-h":
        usage()
        sys.exit()
   
if len(arg)==0:
    usage()
    sys.exit()


for infile in arg:
    if not infile.startswith(prefix):
        outfile = prefix+infile
        if infile != outfile:
            try:
                im = Image.open(infile)
                im.thumbnail(size,Image.BICUBIC)
                print size
                im.save(outfile, "JPEG",quality=qual)
            except IOError:
                print "cannot create thumbnail for", infile

