#! /usr/bin/env python

#    joinpic - merge two pictures together
#    Copyright (C) 2000  Matthew Mueller <donut@azstarnet.com>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import getopt,sys,os,Image

version='1.1'

class config:
	verbose=0
	pngcrush=0
	pngcrushargs=""

def printusage():
	print 'Usage: joinpic [-v] [-V|-H] [-o 0|1|c] [-q 0-100] [-C options] file1 file2 output'
	print '  -V       vertical'
	print '  -H       horizontal'
	print "  -o x     optimize output (0, 1, or c[rush], default 0)"
	print "  -q x     set compression quality (0-100, JPEG only. default 75)"
	print '  -C x     extra pngcrush options'
	print '  -v       verbose'
	print '  -h       help'
	sys.exit()
def printhelp():
	print 'joinpic v%s - Copyright (C) 2000 Matthew Mueller - GPL license'%version
	printusage()

try:
	optlist, args = getopt.getopt(sys.argv[1:], 'o:q:C:vVHh?')
except getopt.error, a:
	print "joinpic: %s"%a
	printusage()

align=None
#saveoptions={'optimize':1}
saveoptions={}
for o,a in optlist:
	if o=='-V':
		align='v'
	elif o=='-H':
		align='h'
 	elif o=='-v':
		config.verbose=1
	elif o == "-o":
		config.pngcrush=0
		if saveoptions.has_key("optimize"):
			del saveoptions["optimize"]
		if a=='c' or a=='crush':
			config.pngcrush=1
        	elif int(a):
	        	saveoptions["optimize"] = int(a)
	elif o == "-q":
		saveoptions["quality"] = int(a)
	elif o == "-C":
		config.pngcrushargs=a
	elif o=='-h' or o=='-?':
		printhelp()

if len(args) == 0:
	printhelp()
if len(args) != 3:
	print 'invalid number of filenames'
	sys.exit(1)

if align==None:
	print 'no alignment specified'%args[2]
	sys.exit(1)

if os.path.exists(args[2]):
	print '%s already exists'%args[2]
	sys.exit(1)

im1=Image.open(args[0])
im2=Image.open(args[1])

if im1.mode!=im2.mode:
	print 'Images are not of the same type (%s=%s, %s=%s)'%(args[0],im1.mode,args[1],im2.mode)
	sys.exit(1)

if align=='h':
	if im1.size[0]!=im2.size[0]:
		print 'Images are different widths'
		sys.exit(1)
	outim=Image.new(im1.mode,(im1.size[0]+im2.size[0],im1.size[1]))
	outim.paste(im1,(0,0))
	outim.paste(im2,(im1.size[0],0))

if align=='v':
	if im1.size[1]!=im2.size[1]:
		print 'Images are different heights'
		sys.exit(1)
	outim=Image.new(im1.mode,(im1.size[0],im1.size[1]+im2.size[1]))
	outim.paste(im1,(0,0))
	outim.paste(im2,(0,im1.size[1]))

if config.pngcrush:
	import tempfile
	outfn=tempfile.mktemp()
	try:
		print 'saving temp file %s (%s)'%(outfn,saveoptions)
		apply(outim.save, (outfn,'png'), saveoptions)
		s='pngcrush %s %s %s'%(config.pngcrushargs,outfn,args[2])
		print s
		os.system(s)
	finally: #delete the tempfile even if there is an exception
		if os.path.exists(outfn): #but don't overwrite the exception with a file not found if the tempfile isn't there
			print 'deleting temp file %s'%outfn
			os.unlink(outfn)
else:
	print 'saving %s (%s)'%(args[2],saveoptions)
	apply(outim.save, (args[2],), saveoptions)
if config.verbose:
	im1size=os.path.getsize(args[0])
	im2size=os.path.getsize(args[1])
	im3size=os.path.getsize(args[2])
	print '%s=%ib %s=%ib %s=%ib(%f%%)'%(args[0],im1size,args[1],im2size,args[2],im3size,float(im3size)/(im1size+im2size)*100)
