#!/usr/bin/python
# gtkrawgallery.py: entry point of GTKRawGallery
# author: (c) 2007-2008 Daniele Isca <bit123@users.sourceforge.net>
# license: GNU GPL v.2 (see COPYING)
# This software comes with no warranty of any kind, use at your own risk!
# version: 0.9.3

import time

start_t = time.time()

import gtk
import gtk.glade
import pygtk
import os.path
import sys
import commands

try:
        import numpy
except ImportError:
        print "GTKRawGallery requires numpy 1.0.4 or newer.\n"
        sys.exit(1)
try:
	import Image
	import ImageStat
except ImportError:
	print "GTKRawGallery requires Imaging Python 1.1.6 or newer.\n"
	sys.exit(1)
if gtk.gtk_version < (2, 10, 0):
	raise ImportError, "GTKRawGallery requires GTK+ 2.10.0 or newer.\n"
	sys.exit(1)
if gtk.pygtk_version < (2, 10, 0):
	raise ImportError, "GTKRawGallery requires PyGTK 2.10.0 or newer.\n"
	sys.exit(1)
        
if os.path.isfile('/usr/bin/convert') or os.path.isfile('/usr/local/bin/convert'): found = True
else:
        try:
                if 'imagemagick' in commands.getoutput('dpkg -l | grep imagemagick'): found = True
        except:
                try:
                        if 'imagemagick' in commands.getoutput('rpm -l | grep imagemagick'): found = True
                except:
                        found = False
if not found:
        raise ImportError, "GTKRawGallery requires ImageMagick 6.3.4 or newer.\n"
        sys.exit(1)
	
splash_tree = gtk.glade.XML('splash.glade')
image = splash_tree.get_widget('image1')
image.set_from_file('icons/splash.png')
splash = splash_tree.get_widget('window1')
while gtk.events_pending():
        gtk.main_iteration(False)

import glob
import math
import os
import cPickle
import string
import gc
import shutil
import thread
import threading
import pango
import cairo
import gobject

import exif
from pythonmagickwand.image import Image as MagickImage
from pythonmagickwand import api
from pythonmagickwand.color import Color
from ctypes import POINTER, c_ulong

if os.getcwd() not in sys.path:
        sys.path.append(os.getcwd())

PI = POINTER(c_ulong)
PI = c_ulong()
QUANTUM = api.GetMagickQuantumDepth(PI) 
Q_RANGE = int(api.GetMagickQuantumRange(PI))

gobject.threads_init()

class Gallery:
        
	def __init__(self):
		self.wtree = gtk.glade.XML('gtkrg.glade')
		handlers_dict = {"on_window1_delete_event" : self.destroy,
			"on_toolbutton2_clicked" : self.first_photo,
			"on_toolbutton3_clicked" : self.last_photo,
			"on_toolbutton4_clicked" : self.previous_photo,
			"on_toolbutton5_clicked" : self.next_photo,
			"on_toolbutton12_clicked" : self.fullscreen_mode,
                        "on_toolbutton44_clicked" : self.add_to_batch_queue,
                        "on_treeview2_row_expanded" : self.expand_rows,
			"on_treeview2_row_collapsed" : self.collapse_rows,
                        "on_add_to_album1_activate" : self.add_selection,
                        "on_delete1_activate" : self.delete_selection,
                        "on_open_image_activate" : self.display_photo,
                        "on_open_with_gimp_activate" : self.open_with_gimp,
                        "on_open_with_other_activate" : self.open_with_other,
                        "on_menuitem9_activate" : self.open_with_gimp,
                        "on_menuitem10_activate" : self.open_with_other,
			"on_menuitem13_activate" : self.hide_pane,
                        "on_convert_activate" : self.show_convert,
                        "on_about1_activate" : self.info,
			"on_exit2_activate" : self.destroy,
                        "on_rename1_activate" : self.rename_album,
                        "on_delete3_activate" : self.Delete,
                        "on_menuitem5_activate" : self.get_options,
			"on_window1_window_state_event" : self.window_state_event,
                        "on_window2_window_state_event" : self.window_state_event,
                        "on_button5_clicked" : self.stop_thumbnails,
                        "on_save_as_activate" : self.save_as_dialog,
                        "on_win6_okbutton_clicked" : self.multiple_conversion,
                        "on_win6_cancelbutton_clicked" : self.hide_win6,
			"on_toolbutton24_toggled" : self.full_exif,
			"on_toolbutton25_clicked" : self.hide_exif,
			"on_toolbutton37_clicked" : self.save_as_dialog,
			"on_menuitem6_activate" : self.open_with_gimp,
			"on_imagemenuitem5_activate" : self.make_bottom_panel,
                        "on_imagemenuitem8_activate" : self.add_selection,
                        "on_imagemenuitem9_activate" : self.delete_selection,
                        "on_imagemenuitem10_activate" : self.save_as_dialog,
			"on_imagemenuitem19_activate" : self.set_album_preview,
			"on_imagemenuitem20_activate" : self.set_album_preview,
			"on_menuitem22_activate" : self.show_tag_manager,
			"on_menuitem24_activate" : self.show_tag_manager,
			"on_button4_clicked" : self.default_colors,
			"on_button22_clicked" : self.clear_cache,
			"on_notebook2_switch_page" : self.on_notebook2_switched,
			"on_combobox5_changed" : self.wb_changed, 
			"on_combobox6_changed" : self.on_combobox6_changed,
			"on_combobox13_changed" : self.on_combobox13_changed,
			"on_button17_clicked" : self.set_default_dcraw_options,
			"on_hscale3_change_value" : self.on_hscale3_change_value,
			"on_hscale4_change_value" : self.on_hscale4_change_value,
			"on_hscale5_change_value" : self.on_hscale5_change_value,
			"on_hscale6_change_value" : self.on_hscale6_change_value,
			"on_hscale7_change_value" : self.on_hscale7_change_value,
			"on_hscale8_change_value" : self.on_hscale8_change_value,
			"on_hscale9_change_value" : self.on_hscale9_change_value,
			"on_hscale10_change_value" : self.on_hscale10_change_value,
			"on_hscale11_change_value" : self.on_hscale11_change_value,
			"on_hscale12_change_value" : self.on_hscale12_change_value,
			"on_hscale13_change_value" : self.on_hscale13_change_value,
			"on_hscale14_change_value" : self.on_hscale14_change_value,
			"on_hscale15_change_value" : self.on_hscale15_change_value,
                        "on_hscale16_change_value" : self.on_hscale16_change_value,
                        "on_hscale17_change_value" : self.on_hscale17_change_value,
			"on_hscale18_change_value" : self.on_hscale18_change_value,
                        "on_hscale19_change_value" : self.on_hscale19_change_value,
			"on_hscale20_change_value" : self.on_hscale20_change_value,
			"on_hscale21_change_value" : self.on_hscale21_change_value,
			"on_hscale22_change_value" : self.on_hscale22_change_value,
                        "on_hscale24_change_value" : self.on_hscale24_change_value,
                        "on_hscale26_change_value" : self.on_hscale26_change_value,
                        "on_hscale27_change_value" : self.on_hscale27_change_value,
                        "on_hscale29_change_value" : self.on_hscale29_change_value,
                        "on_hscale30_change_value" : self.on_hscale30_change_value,
                        "on_hscale31_change_value" : self.on_hscale31_change_value,
                        "on_hscale32_change_value" : self.on_hscale32_change_value,
                        "on_hscale33_change_value" : self.on_hscale33_change_value,
			"on_hscale3_scroll_event" : self.on_hscale_scrolled,
			"on_hscale4_scroll_event" : self.on_hscale_scrolled,
			"on_hscale5_scroll_event" : self.on_hscale_scrolled,
			"on_hscale6_scroll_event" : self.on_hscale_scrolled,
			"on_hscale7_scroll_event" : self.on_hscale_scrolled,
			"on_hscale8_scroll_event" : self.on_hscale_scrolled,
			"on_hscale9_scroll_event" : self.on_hscale_scrolled,
			"on_hscale10_scroll_event" : self.on_hscale_scrolled,
			"on_hscale11_scroll_event" : self.on_hscale_scrolled,
			"on_hscale12_scroll_event" : self.on_hscale_scrolled,
			"on_hscale13_scroll_event" : self.on_hscale_scrolled,
			"on_hscale14_scroll_event" : self.on_hscale_scrolled,
			"on_hscale15_scroll_event" : self.on_hscale_scrolled,
			"on_hscale16_scroll_event" : self.on_hscale_scrolled,
			"on_hscale17_scroll_event" : self.on_hscale_scrolled,
                        "on_hscale18_scroll_event" : self.on_hscale_scrolled,
			"on_hscale19_scroll_event" : self.on_hscale_scrolled,
			"on_hscale20_scroll_event" : self.on_hscale_scrolled,
			"on_hscale21_scroll_event" : self.on_hscale_scrolled,
			"on_hscale22_scroll_event" : self.on_hscale_scrolled,
			"on_hscale24_scroll_event" : self.on_hscale_scrolled,
			"on_hscale26_scroll_event" : self.on_hscale_scrolled,
			"on_hscale27_scroll_event" : self.on_hscale_scrolled,
			"on_hscale29_scroll_event" : self.on_hscale_scrolled,
			"on_hscale30_scroll_event" : self.on_hscale_scrolled,
                        "on_hscale31_scroll_event" : self.on_hscale_scrolled,
                        "on_hscale32_scroll_event" : self.on_hscale_scrolled,
                        "on_hscale33_scroll_event" : self.on_hscale_scrolled,
			"on_combobox2_scroll_event" : self.on_hscale_scrolled,
			"on_combobox3_scroll_event" : self.on_hscale_scrolled,
			"on_combobox4_scroll_event" : self.on_hscale_scrolled,
			"on_combobox5_scroll_event" : self.on_hscale_scrolled,
			"on_combobox6_scroll_event" : self.on_hscale_scrolled,
			"on_combobox8_scroll_event" : self.on_hscale_scrolled,
			"on_combobox11_scroll_event" : self.on_hscale_scrolled,
			"on_combobox12_scroll_event" : self.on_hscale_scrolled,
			"on_combobox13_scroll_event" : self.on_hscale_scrolled,
			"on_hscale4_button_release_event" : self.on_level_changed,
			"on_hscale5_button_release_event" : self.on_level_changed,
			"on_hscale6_button_release_event" : self.on_level_changed,
			"on_hscale7_button_release_event" : self.on_brightness_and_saturation_changed,
			"on_hscale8_button_release_event" : self.on_brightness_and_saturation_changed,
                        "on_hscale18_button_release_event" : self.on_brightness_and_saturation_changed,
			"on_hscale9_button_release_event" : self.color_balance,
			"on_hscale10_button_release_event" : self.color_balance,
			"on_hscale11_button_release_event" : self.color_balance,
			"on_hscale12_button_release_event" : self.on_contrast_changed,
			"on_hscale13_button_release_event" : self.on_midtones_contrast_changed,
			"on_hscale14_button_release_event" : self.on_midtones_contrast_changed,
                        "on_hscale31_button_release_event" : self.on_channel_mixer_changed,
                        "on_hscale32_button_release_event" : self.on_channel_mixer_changed,
                        "on_hscale33_button_release_event" : self.on_channel_mixer_changed,
                        "on_spinbutton1_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton4_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton5_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton6_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton7_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton8_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton9_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton10_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton11_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton12_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton13_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton14_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton15_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton16_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton17_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton18_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton19_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton20_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton21_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton22_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton23_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton24_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton25_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton26_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton27_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton28_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton29_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton30_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton31_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton32_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton33_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton34_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton35_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton36_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton37_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton38_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton40_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton41_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton43_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton44_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton46_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton47_scroll_event" : self.on_spinbutton_scrolled,
                        "on_spinbutton48_scroll_event" : self.on_spinbutton_scrolled,
			"on_spinbutton1_value_changed" : self.on_spinbutton1_value_changed,
                        "on_spinbutton10_value_changed" : self.on_spinbutton10_value_changed,
			"on_spinbutton11_value_changed" : self.on_spinbutton11_value_changed,
                        "on_spinbutton12_value_changed" : self.on_spinbutton12_value_changed,
                        "on_spinbutton13_value_changed" : self.on_spinbutton13_value_changed,
                        "on_spinbutton14_value_changed" : self.on_spinbutton14_value_changed,
                        "on_spinbutton15_value_changed" : self.on_spinbutton15_value_changed,
                        "on_spinbutton16_value_changed" : self.on_spinbutton16_value_changed,
                        "on_spinbutton17_value_changed" : self.on_spinbutton17_value_changed,
                        "on_spinbutton18_value_changed" : self.on_spinbutton18_value_changed,
                        "on_spinbutton20_value_changed" : self.on_spinbutton20_value_changed,
                        "on_spinbutton21_value_changed" : self.on_spinbutton21_value_changed,
                        "on_spinbutton22_value_changed" : self.on_spinbutton22_value_changed,
                        "on_spinbutton25_value_changed" : self.on_spinbutton25_value_changed,
                        "on_spinbutton29_value_changed" : self.on_spinbutton29_value_changed,
			"on_spinbutton31_value_changed" : self.on_spinbutton31_value_changed,
			"on_spinbutton33_value_changed" : self.on_spinbutton33_value_changed,
			"on_spinbutton32_value_changed" : self.on_spinbutton32_value_changed,
			"on_spinbutton34_value_changed" : self.on_spinbutton34_value_changed,
			"on_spinbutton36_value_changed" : self.on_spinbutton36_value_changed,
                        "on_spinbutton37_value_changed" : self.on_spinbutton37_value_changed,
                        "on_spinbutton40_value_changed" : self.on_spinbutton40_value_changed,
                        "on_spinbutton41_value_changed" : self.on_spinbutton41_value_changed,
                        "on_spinbutton43_value_changed" : self.on_spinbutton43_value_changed,
                        "on_spinbutton44_value_changed" : self.on_spinbutton44_value_changed,
                        "on_spinbutton48_value_changed" : self.on_spinbutton48_value_changed,
                        "on_spinbutton47_value_changed" : self.on_spinbutton47_value_changed,
                        "on_spinbutton46_value_changed" : self.on_spinbutton46_value_changed,
			"on_spinbutton10_button_release_event" : self.on_color_spinbutton_released,
			"on_spinbutton12_button_release_event" : self.on_color_spinbutton_released,
			"on_spinbutton13_button_release_event" : self.on_color_spinbutton_released,
			"on_spinbutton14_button_release_event" : self.on_color_spinbutton_released,
			"on_spinbutton15_button_release_event" : self.on_color_spinbutton_released,
			"on_spinbutton16_button_release_event" : self.on_color_spinbutton_released,
			"on_spinbutton17_button_release_event" : self.on_color_spinbutton_released,
			"on_spinbutton18_button_release_event" : self.on_color_spinbutton_released,
			"on_spinbutton20_button_release_event" : self.on_color_spinbutton_released,
			"on_spinbutton21_button_release_event" : self.on_color_spinbutton_released,
			"on_spinbutton22_button_release_event" : self.on_color_spinbutton_released,
			"on_spinbutton27_button_release_event" : self.on_color_spinbutton_released,
			"on_spinbutton28_button_release_event" : self.on_color_spinbutton_released,
                        "on_spinbutton37_button_release_event" : self.on_color_spinbutton_released,
			"on_spinbutton46_button_release_event" : self.on_color_spinbutton_released,
			"on_spinbutton47_button_release_event" : self.on_color_spinbutton_released,
			"on_spinbutton48_button_release_event" : self.on_color_spinbutton_released,
			"on_toolbutton23_clicked" : self.undo_workflow,
			"on_toolbutton39_clicked" : self.redo_workflow,
			"on_button36_clicked" : self.on_button36_clicked,
			"on_button42_clicked" : self.on_button42_clicked,
			"on_button45_clicked" : self.on_button45_clicked,
                        "on_button40_clicked" : self.remove_from_batch_queue,
			"on_button54_clicked" : self.undo_handler,
                        "on_button55_clicked" : self.delete_tag,
			"on_button57_clicked" : self.undo_handler,
			"on_button58_clicked" : self.apply_sharpen,
			"on_button61_clicked" : self.undo_handler,
			"on_button63_clicked" : self.apply_noise,
			"on_button64_clicked" : self.new_tag,
			"on_button65_clicked" : self.undo_handler,
			"on_button66_clicked" : self.scale,
			"on_button67_clicked" : self.on_window8_delete_event,
			"on_button68_clicked" : self.undo_handler,
                        "on_button69_clicked" : self.apply_img_border,
			"on_button70_clicked" : self.apply_blur,
                        "on_button72_clicked" : self.undo_workflow,
			"on_button74_clicked" : self.undo_handler,
			"on_button75_clicked" : self.apply_reduce_noise,
                        "on_button76_clicked" : self.delete_tag,
			"on_button77_clicked" : self.new_tag,
                        "on_toolbutton36_clicked" : self.save_workflow,
			"on_button80_clicked" : self.undo_handler,
			"on_button81_clicked" : self.apply_median_filter,
			"on_button83_clicked" : self.undo_handler,
			"on_button84_clicked" : self.apply_sepia_tone,
			"on_button86_clicked" : self.on_abort_button_clicked,
			"on_button89_clicked" : self.undo_handler,
			"on_button90_clicked" : self.grayscale,
			"on_button92_clicked" : self.undo_handler,
                        "on_button93_clicked" : self.undo_workflow,
                        "on_button94_clicked" : self.undo_handler,
                        "on_button95_clicked" : self.apply_unsharp_mask,
                        "on_button97_clicked" : self.apply_crop,
			"on_button103_clicked" : self.apply_normalize,
			"on_menuitem7_activate" : self.open_with_other,
			"on_menuitem14_activate" : self.copy_and_move,
			"on_menuitem15_activate" : self.copy_and_move,
			"on_menuitem16_activate" : self.delete_files,
                        "on_menuitem17_activate" : self.rename_image,
			"on_menuitem18_activate" : self.copy_and_move,
			"on_menuitem19_activate" : self.copy_and_move,
			"on_menuitem20_activate" : self.delete_files,
                        "on_menuitem21_activate" : self.rename_image,
			"on_checkbutton17_toggled" : self.undo_workflow,
                        "on_checkbutton18_toggled" : self.on_checkbutton18_toggled,
                        "on_checkbutton19_toggled" : self.on_checkbutton19_toggled,
                        "on_checkbutton20_toggled" : self.on_checkbutton20_toggled,
			"on_checkbutton21_toggled" : self.on_checkbutton21_toggled,
                        "on_checkbutton24_toggled" : self.on_checkbutton24_toggled,
                        "on_treeview1_button_press_event" : self.show_menu6,
                        "on_scrolledwindow2_scroll_event" : self.scroll_eventbox1,
                        "on_window3_button_press_event" : self.on_delete_window3,
                        "on_window3_scroll_event" : self.scroll_fullphoto,
                        "on_window4_button_press_event" : self.on_delete_event,
                        "on_window4_scroll_event" : self.on_delete_event,
                        "on_scrolledwindow3_scroll_event" : self.scroll_scrolledwindow3,
                        "on_window3_key_press_event" : self.on_key_press_event,
                        "on_window4_key_press_event" : self.on_key_press_event,
			"on_window7_delete_event" : self.on_delete_event,
			"on_window8_delete_event" : self.on_window8_delete_event,
			"on_window7_window_state_event" : self.on_window7_state_event,
                        "on_imagemenuitem6_activate" : self.open_on_window2,
                        "on_combobox14_changed" : self.on_combotag_changed,
                        "on_combobox15_changed" : self.on_combotag_changed,
			"on_checkbutton28_toggled" : self.on_checkbutton28_toggled,
			"on_checkbutton29_toggled" : self.on_checkbutton29_toggled,
			"on_checkbutton30_toggled" : self.on_checkbutton30_toggled,
			"on_checkbutton31_toggled" : self.on_checkbutton31_toggled}
		
		self.wtree.signal_autoconnect(handlers_dict)
		self.load_widgets(self)
		self.setup_signal_handlers(self)
		self._id = None
		self.drawing_area = 0
		self.combobox12_id = 0
		self.pid = 0
		self.n_columns = 0
		self.magick_size = 0
		self.wand_list = []
		self.size_history = [0] * 100
		self.wand_index = 0
		self.crop_count = 0
		self.border_count = 0
		self.wand = None
		self.window7_was_iconified = False
		self.window2_closed = False
		self.overexposed = False
		self.crop_ratio = 1.5
		self.x_offset = self.y_offset = 0  
		self.surface = None
		self.pixbuf1 = None
		self.drawing_area_id = None		
                self.stop_batch_process = None
		self.batch_iter = None
		self.sample = None
		self.close_panel = None
		self.scrolledwindow6 = None
		self.raw_preview = None
		self.watch = gtk.gdk.Cursor(gtk.gdk.WATCH)
		self.stop_thread = threading.Event()
		self.stop_progressbar2 = threading.Event()
		self.stop_progressbar5 = threading.Event()
		self.lock = thread.allocate_lock()
		self.lock2 = thread.allocate_lock()
		self.count = 0
		self.n = 0
		self.stop_thumb = 0
		self.indice = 0
		self.win2_indice = 0
		self.total_size = 0
		self.delay = 0.00
		self.x = 0
		self.y = 0
		self.x1 = 0
		self.y1 = 0
		self.infile = 0
		self.w = 0
		self.h = 0
		self.RGB_levels = {'RGB' : [0,1.0,100], 'Red' : [0,1.0,100], 'Green' : [0,1.0,100], 'Blue' : [0,1.0,100]}
		self.mixer_levels = {'Red' : [100,0,0] , 'Green' : [0,100,0], 'Blue' : [0,0,100]}
		self.c_balance = [0,0,0]
	 	self.mid_contrast = []
	 	self.sigmoidal_contrast_args = ()
	 	self.IM_border_args = ()
	 	self.blur_args = ()
	 	self.sharpen_args = ()
	 	self.unsharp_args = ()
	 	self.add_noise_args = ()
	 	self.reduce_noise_args = ()
	 	self.median_args = ()
	 	self.sepia_tone_args = ()
	 	self.scale_args = ()
		self.crop_args = ()
		self.repage_args = ()
		self.matrix = ()
		self.expander_list = [self.expander2, self.expander3, self.expander4, self.expander5,
                self.expander6, self.expander7, self.expander8, self.expander9, self.expander10,
                self.expander11, self.expander12, self.expander13, self.expander14, self.expander15,
                self.expander16, self.expander17, self.expander18, self.expander20, self.expander21]
		self.contrast = self.ratio = self.fine_degree = 0
		self.cache_size = 50
		self.border_color = 0xffffffff
		self.gradi = [gtk.gdk.PIXBUF_ROTATE_NONE, gtk.gdk.PIXBUF_ROTATE_COUNTERCLOCKWISE,
                gtk.gdk.PIXBUF_ROTATE_UPSIDEDOWN, gtk.gdk.PIXBUF_ROTATE_CLOCKWISE]
		self.width = 150
		self.height = 100
		self.rotate = False
		self.overwrite_thumb = False
		self.image_was_changed = False
                self.workflow_started = False
                self.overwrite_all = False
		self.history = []
		self.workflow_copy = []
		self.level_hist = []
		self.bright_sat = [0,0,0]
		self.pila = []
		self.list = []
		self.selected = []
		self.image = []
		self.e = []
		self.event = []
		self.pblist = range(3)
		self.pblist[1] = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, 0, 8, 1, 1)
		self.fullpblist = range(3)
		self.b_pixlist = range(3)
		self.image_size = self.image_size2 = '0x0'
		self.fname = 'filetemp'
		self.pixindex = 1
		self.pbindex = 1
		self.fullpbindex = 1
		self.loop = 1
		self.r = 1
		self.g = 1
		self.b = 1
		self.previous_index = 1
		self.oldadj = 2
		self.pause = 2
		self.frames = 25
		self.album = ''
		self.added_album = ''
		self.cartella = ''
		self.font = 'TSCu_Comic 12'
		self.rawpath = {}
		self.rotated = {}
		self.batch_queue = {}
		self.ark = os.environ['HOME'] + '/.GTKRawGallery/' 
		self.cache = self.ark + '.Thumbnails/'
		self.batch_thumbs = self.ark + '.Batch_Thumbs/'
		self.temp = os.getcwd() + '/.raw/'
		self.version = 'GTKRawGallery-0.9.3 - '
		self.formats = ['.jpg', '.jpeg', '.jpe', '.tiff', '.tif', '.png', '.xpm',
                                '.xbm', '.gif', '.ico', '.cur', '.ppm', '.pbm', '.pgm', '.pnm', '.pcx', '.bmp',
                                '.svg', '.svgz', '.svg.gz', '.ras', '.tga', '.targa', '.wmf', '.apm', '.wbmp']
                self.raw_formats = ['.cr2', '.nef', '.crw', '.raf', '.kdc', '.dcr', '.mrw', '.orf',
                                    '.ptx', '.pef', '.arw', '.srf', '.x3f', '.erf', '.dng']
                self.boxmodel = gtk.ListStore(str)
                self.boxmodel2 = gtk.ListStore(str)
		if '.thumbnails' not in os.listdir(os.getcwd()):
                        os.mkdir('.thumbnails')
                if '.raw' not in os.listdir(os.getcwd()):
                        os.mkdir('.raw')
                if '.GTKRawGallery' not in os.listdir(os.environ['HOME']):
                        os.mkdir(self.ark)
                if '.Thumbnails' not in os.listdir(self.ark):
                        os.mkdir(self.cache)
                if '.Batch_Thumbs' not in os.listdir(self.ark):
                        os.mkdir(self.batch_thumbs)
		self.cache_list = os.listdir(self.cache)
		
#=============  self.treeview1 structure ===========================================
															
		self.model = gtk.ListStore(gtk.gdk.Pixbuf, str)										
		(COL_PIXBUF, COL_STRING) = range(2)								
		cell = gtk.CellRendererText()
		pb_renderer = gtk.CellRendererPixbuf()
		self.column = gtk.TreeViewColumn()
		self.column.set_title('Albums')
		self.column.pack_start(pb_renderer, expand=False)
                self.column.add_attribute(pb_renderer, 'pixbuf', COL_PIXBUF)
                self.column.pack_start(cell, expand=True)
                self.column.add_attribute(cell, 'text', COL_STRING)
		self.column.set_resizable(True)										
		self.column.set_sort_column_id(COL_STRING)							
		self.treeview1.append_column(self.column)				
		self.treeview1.set_model(self.model)					
			
#=============  self.treeview2 structure ============================================
		
		(COL_PIXBUF, COL_STRING) = range(2)	
		self.treestore = gtk.TreeStore(gtk.gdk.Pixbuf, str)	
		self.folderpb = gtk.gdk.pixbuf_new_from_file('icons/stock_directory_24.png')
      		self.iter0 = self.treestore.append(None, [self.folderpb, '/'])
      		filelist = glob.glob('/*')
      		for item in filelist:
                        if os.path.isdir(item):
                                self.treestore.append(self.iter0, [self.folderpb, os.path.basename(item)])
		self.treeview2.set_model(self.treestore)
                self.column0 = gtk.TreeViewColumn("Directory Tree")
                self.treeview2.append_column( self.column0 )
		self.cellpb = gtk.CellRendererPixbuf()
        	self.cell = gtk.CellRendererText()
        	self.column0.pack_start(self.cellpb, False)
       		self.column0.add_attribute(self.cellpb, 'pixbuf', COL_PIXBUF)
       		self.column0.pack_start(self.cell, True)
       		self.column0.add_attribute(self.cell, 'text', COL_STRING)
		self.treeview2.expand_all()
		
#============== self.treeview3 structure =================================================

       		self.exifmodel = gtk.ListStore(str, str)
       		(COL_ITEM, COL_VALUE) = range(2)
       		cell = gtk.CellRendererText()										
		self.column_item = gtk.TreeViewColumn("TAG", cell, text=COL_ITEM)			
		self.column.set_resizable(True)												
		self.treeview3.append_column(self.column_item)				
                cell = gtk.CellRendererText()										
		self.column_value = gtk.TreeViewColumn("VALUE", cell, text=COL_VALUE)			
		self.column.set_resizable(True)													
		self.treeview3.append_column(self.column_value)		
		self.treeview3.set_model(self.exifmodel)
		
#============= self.treeview4 structure ==================================================
                
                self.batchmodel = gtk.ListStore(str, gtk.gdk.Pixbuf, 'gboolean', str, str)
		(COL_N, COL_PIX, COL_TOGGLE, COL_FILENAME, COL_COLOR) = range(5)
                self.renderer_number = gtk.CellRendererText()
                self.column_number = gtk.TreeViewColumn("Run", self.renderer_number, text=COL_N)
                self.column_number.set_cell_data_func (self.renderer_number, self.cell_data_function, None)
                self.treeview4.append_column(self.column_number)
                self.renderer_pix = gtk.CellRendererPixbuf()
                self.column_pix = gtk.TreeViewColumn("Preview", self.renderer_pix, pixbuf=COL_PIX)
                self.treeview4.append_column(self.column_pix)
                self.renderer_toggle = gtk.CellRendererToggle()
                self.renderer_toggle.set_property('activatable', True)
                self.renderer_toggle.connect('toggled', self.on_renderer_toggle_toggled, self.batchmodel)
                self.column_toggle = gtk.TreeViewColumn("Enabled", self.renderer_toggle)
		self.column_toggle.add_attribute(self.renderer_toggle, "activatable", 2)
		self.column_toggle.add_attribute(self.renderer_toggle, "active", 2)
		self.column_toggle.set_attributes(self.renderer_toggle, active=2)
                self.column_toggle.set_cell_data_func (self.renderer_toggle, self.cell_data_function, None)
                self.treeview4.append_column(self.column_toggle)
                self.renderer_filename = gtk.CellRendererText()
                self.column_filename = gtk.TreeViewColumn("Filename", self.renderer_filename, text=COL_FILENAME)
                self.column_filename.set_cell_data_func (self.renderer_filename, self.cell_data_function, None)
                self.treeview4.append_column(self.column_filename)
                self.renderer_color = gtk.CellRendererText()
                self.column_color = gtk.TreeViewColumn("Status", self.renderer_color, text=COL_COLOR)
                self.column_color.set_cell_data_func (self.renderer_color, self.cell_data_function, None)
                self.treeview4.append_column(self.column_color)
                self.treeview4.set_model(self.batchmodel)

#=============== self.treeview5 structure ==================================================
                
		self.tagmodel = gtk.ListStore('gboolean', str)
		self.tag_toggle = gtk.CellRendererToggle()
		self.tag_toggle.set_property('activatable', True)
		self.tag_toggle.connect('toggled', self.on_tag_toggle_toggled, self.tagmodel)
		self.column_tag_toggle = gtk.TreeViewColumn(None, self.tag_toggle)
		self.column_tag_toggle.set_attributes(self.tag_toggle, active=0)
		self.treeview5.append_column(self.column_tag_toggle)
		self.renderer_tag_name = gtk.CellRendererText()
                self.column_tag_name = gtk.TreeViewColumn("Tag List", self.renderer_tag_name, text=1)
		self.treeview5.append_column(self.column_tag_name)
		self.treeview5.set_model(self.tagmodel)

#=============== self.treeview6 structure =====================================================
		
                self.tagmodel2 = gtk.ListStore('gboolean', str)
		self.tag_toggle2 = gtk.CellRendererToggle()
		self.tag_toggle2.set_property('activatable', True)
		self.id81 = self.tag_toggle2.connect('toggled', self.on_tag_toggle_toggled, self.tagmodel2)
		self.column_tag_toggle2 = gtk.TreeViewColumn(None, self.tag_toggle2)
		self.column_tag_toggle2.set_attributes(self.tag_toggle2, active=0)
		self.treeview6.append_column(self.column_tag_toggle2)
		self.renderer_tag_name2 = gtk.CellRendererText()
                self.column_tag_name2 = gtk.TreeViewColumn("Tag List", self.renderer_tag_name2, text=1)
		self.treeview6.append_column(self.column_tag_name2)
		self.treeview6.set_model(self.tagmodel2)
		
		self.tagmodel3 = gtk.ListStore(str)
		cell = gtk.CellRendererText()
		self.combobox14.set_model(self.tagmodel3)
		self.combobox14.pack_start(cell, True)
  		self.combobox14.add_attribute(cell, 'text', 0)
  		self.combobox15.set_model(self.tagmodel3)
  		self.combobox15.pack_start(cell, True)
  		self.combobox15.add_attribute(cell, 'text', 0)  		
#==============================================================================================
  		
                self.load_settings_database()
                self.load_album_database()
		self.load_batch_database()
       		self.widgets_settings(self)
		load_t = time.time() - start_t
		if load_t > 3 :
                        t = 0
		else :
                        t = 3 - load_t
		time.sleep(t)
		self.window1.show()
		splash.hide()
		self.progressbar3.hide()
		self.button5.hide()
		self.load_last_path(self)
		self.add_patterns(self)
		self.hpaned1.handler_unblock(self.id28)
		self.scrolledwindow2.set_size_request(int(gtk.gdk.screen_width() * 0.85), -1)
		thread.start_new_thread(self.cache_control, ())
		
#======= Methods ==========================================================================
			
        def load_widgets(self, event):
                self.open_folder1 = self.wtree.get_widget('open_folder1')
		self.open_album1 = self.wtree.get_widget('open_album1')
		self.open1 = self.wtree.get_widget('open1')
		self.new1 = self.wtree.get_widget('new1')
		self.new2 = self.wtree.get_widget('new2')
		self.delete2 = self.wtree.get_widget('delete2')
		self.filechooser = self.wtree.get_widget('filechooserdialog1')
		self.filechooser2 = self.wtree.get_widget('filechooserdialog2')
		self.filechooserdialog3 = self.wtree.get_widget('filechooserdialog3')
		self.filechooserbutton1 = self.wtree.get_widget('filechooserbutton1')
		self.filechooserbutton2 = self.wtree.get_widget('filechooserbutton2')
		self.filechooserbutton3 = self.wtree.get_widget('filechooserbutton3')
		self.filechooserbutton4 = self.wtree.get_widget('filechooserbutton4')
		self.filechooserbutton5 = self.wtree.get_widget('filechooserbutton5')
		self.filechooserbutton6 = self.wtree.get_widget('filechooserbutton6')
		self.filechooserbutton7 = self.wtree.get_widget('filechooserbutton7')
		self.filter0 = gtk.FileFilter()
		self.filter1 = gtk.FileFilter()
		self.filter2 = gtk.FileFilter()
		self.dialog1 = self.wtree.get_widget('dialog1')
		self.dialog2 = self.wtree.get_widget('dialog2')
		self.dialog3 = self.wtree.get_widget('dialog3')
		self.dialog4 = self.wtree.get_widget('dialog4')
		self.dialog5 = self.wtree.get_widget('dialog5')
		self.dialog6 = self.wtree.get_widget('dialog6')
		self.dialog7 = self.wtree.get_widget('dialog7')
		self.dialog8 = self.wtree.get_widget('dialog8')
		self.dialog9 = self.wtree.get_widget('dialog9')
		self.dialog10 = self.wtree.get_widget('dialog10')
		self.dialog11 = self.wtree.get_widget('dialog11')
		self.dialog12 = self.wtree.get_widget('dialog12')
		self.dialog13 = self.wtree.get_widget('dialog13')
		self.dialog14 = self.wtree.get_widget('dialog14')
		self.dialog15 = self.wtree.get_widget('dialog15')
		self.dialog16 = self.wtree.get_widget('dialog16')
		self.dialog17 = self.wtree.get_widget('dialog17')
		self.dialog18 = self.wtree.get_widget('dialog18')
		self.dialog19 = self.wtree.get_widget('dialog19')
		self.dialog20 = self.wtree.get_widget('dialog20')
		self.dialog21 = self.wtree.get_widget('dialog21')
		self.dialog22 = self.wtree.get_widget('dialog22')
		self.dialog23 = self.wtree.get_widget('dialog23')
		self.dialog24 = self.wtree.get_widget('dialog24')
		self.dialog25 = self.wtree.get_widget('dialog25')
		self.label29 = self.wtree.get_widget('label29')
		self.label7 = self.wtree.get_widget('label7')
		self.label8 = self.wtree.get_widget('label17')
		self.label4 = self.wtree.get_widget('label4')
		self.label5 = self.wtree.get_widget('label5')
		self.label9 = self.wtree.get_widget('label9')
		self.label10 = self.wtree.get_widget('label10')
		self.label31 = self.wtree.get_widget('label31')
		self.label48 = self.wtree.get_widget('label48')
		self.label49 = self.wtree.get_widget('label49')
		self.label53 = self.wtree.get_widget('label53')
		self.label54 = self.wtree.get_widget('label54')
		self.label56 = self.wtree.get_widget('label56')
		self.label57 = self.wtree.get_widget('label57')
		self.label58 = self.wtree.get_widget('label58')
		self.label59 = self.wtree.get_widget('label59')
		self.label60 = self.wtree.get_widget('label60')
		self.label93 = self.wtree.get_widget('label93')
		self.label135 = self.wtree.get_widget('label135')
		self.label136 = self.wtree.get_widget('label136')
		self.label163 = self.wtree.get_widget('label163')
		self.delete1 = self.wtree.get_widget('delete1')
		self.frame1 = self.wtree.get_widget('frame1')
		self.hpaned1 = self.wtree.get_widget('hpaned1')
		self.hpaned2 = self.wtree.get_widget('hpaned2')
		self.vpaned2 = self.wtree.get_widget('vpaned2')
		self.delete_selection1 = self.wtree.get_widget('delete_selection1')
		self.add_selection1 = self.wtree.get_widget('add_selection1')
		self.add_to_album1 = self.wtree.get_widget('add_to_album1')
		self.comboboxentry1 = self.wtree.get_widget('comboboxentry1')
		self.comboboxentry2 = self.wtree.get_widget('comboboxentry2')
		self.comboboxentry5 = self.wtree.get_widget('comboboxentry5')
		self.combobox1 = self.wtree.get_widget('combobox1')
		self.combobox2 = self.wtree.get_widget('combobox2')
		self.combobox3 = self.wtree.get_widget('combobox3')
		self.combobox4 = self.wtree.get_widget('combobox4')
		self.combobox5 = self.wtree.get_widget('combobox5')
		self.combobox6 = self.wtree.get_widget('combobox6')
		self.combobox7 = self.wtree.get_widget('combobox7')
		self.combobox8 = self.wtree.get_widget('combobox8')
		self.combobox9 = self.wtree.get_widget('combobox9')
		self.combobox10 = self.wtree.get_widget('combobox10')
		self.combobox11 = self.wtree.get_widget('combobox11')
		self.combobox12 = self.wtree.get_widget('combobox12')
		self.combobox13 = self.wtree.get_widget('combobox13')
		self.combobox14 = self.wtree.get_widget('combobox14')
		self.combobox15 = self.wtree.get_widget('combobox15')
		self.entry1 = self.wtree.get_widget('entry1')
		self.entry2 = self.wtree.get_widget('entry2')
		self.entry3 = self.wtree.get_widget('entry3')
		self.entry4 = self.wtree.get_widget('entry4')
		self.entry5 = self.wtree.get_widget('entry5')
		self.entry6 = self.wtree.get_widget('entry6')
		self.entry7 = self.wtree.get_widget('entry7')
		self.entry8 = self.wtree.get_widget('entry8')
		self.entry9 = self.wtree.get_widget('entry9')
		self.entry10 = self.wtree.get_widget('entry10')
		self.entry11 = self.wtree.get_widget('entry11')
		self.entry12 = self.wtree.get_widget('entry12')
		self.entry13 = self.wtree.get_widget('entry13')
		self.menu3 = self.wtree.get_widget('menu3')
		self.menu5 = self.wtree.get_widget('menu5')
		self.menu6 = self.wtree.get_widget('menu6')
		self.menu8 = self.wtree.get_widget('menu8')
		self.boxentry = self.wtree.get_widget('comboboxentry-entry1')
		self.boxentry2 = self.wtree.get_widget('comboboxentry-entry2')
		self.window1 = self.wtree.get_widget('window1')
		self.window2 = self.wtree.get_widget('window2')
		self.window3 = self.wtree.get_widget('window3')
		self.window4 = self.wtree.get_widget('window4')
		self.window5 = self.wtree.get_widget('window5')
		self.window6 = self.wtree.get_widget('window6')
		self.window7 = self.wtree.get_widget('window7')
		self.window8 = self.wtree.get_widget('window8')
		self.window9 = self.wtree.get_widget('window9')
		self.statusbar1 = self.wtree.get_widget('statusbar1')
                self.statusbar2 = self.wtree.get_widget('statusbar2')
		self.statusbar3 = self.wtree.get_widget('statusbar3')
		self.statusbar4 = self.wtree.get_widget('statusbar4')
		self.progressbar1 = self.wtree.get_widget('progressbar1')
		self.progressbar2 = self.wtree.get_widget('progressbar2')
		self.progressbar3 = self.wtree.get_widget('progressbar3')
		self.progressbar4 = self.wtree.get_widget('progressbar4')
		self.progressbar5 = self.wtree.get_widget('progressbar5')
		self.radiobutton1 = self.wtree.get_widget('radiobutton1')
		self.radiobutton2 = self.wtree.get_widget('radiobutton2')
		self.radiobutton3 = self.wtree.get_widget('radiobutton3')
		self.radiobutton6 = self.wtree.get_widget('radiobutton6')
		self.radiobutton7 = self.wtree.get_widget('radiobutton7')
		self.radiobutton10 = self.wtree.get_widget('radiobutton10')
		self.radiobutton11 = self.wtree.get_widget('radiobutton11')
		self.checkbutton1 = self.wtree.get_widget('checkbutton1')
		self.checkbutton2 = self.wtree.get_widget('checkbutton2')
		self.checkbutton3 = self.wtree.get_widget('checkbutton3')
		self.checkbutton4 = self.wtree.get_widget('checkbutton4')
		self.checkbutton5 = self.wtree.get_widget('checkbutton5')
		self.checkbutton6 = self.wtree.get_widget('checkbutton6')
		self.checkbutton7 = self.wtree.get_widget('checkbutton7')
		self.checkbutton8 = self.wtree.get_widget('checkbutton8')
		self.checkbutton9 = self.wtree.get_widget('checkbutton9')
		self.checkbutton10 = self.wtree.get_widget('checkbutton10')
		self.checkbutton11 = self.wtree.get_widget('checkbutton11')
		self.checkbutton12 = self.wtree.get_widget('checkbutton12')
		self.checkbutton13 = self.wtree.get_widget('checkbutton13')
		self.checkbutton14 = self.wtree.get_widget('checkbutton14')
		self.checkbutton15 = self.wtree.get_widget('checkbutton15')
		self.checkbutton16 = self.wtree.get_widget('checkbutton16')
		self.checkbutton17 = self.wtree.get_widget('checkbutton17')
		self.checkbutton18 = self.wtree.get_widget('checkbutton18')
		self.checkbutton19 = self.wtree.get_widget('checkbutton19')
		self.checkbutton20 = self.wtree.get_widget('checkbutton20')
		self.checkbutton21 = self.wtree.get_widget('checkbutton21')
		self.checkbutton22 = self.wtree.get_widget('checkbutton22')
		self.checkbutton23 = self.wtree.get_widget('checkbutton23')
		self.checkbutton24 = self.wtree.get_widget('checkbutton24')
		self.checkbutton25 = self.wtree.get_widget('checkbutton25')
		self.checkbutton26 = self.wtree.get_widget('checkbutton26')
		self.checkbutton27 = self.wtree.get_widget('checkbutton27')
		self.checkbutton28 = self.wtree.get_widget('checkbutton28')
		self.checkbutton29 = self.wtree.get_widget('checkbutton29')
		self.checkbutton30 = self.wtree.get_widget('checkbutton30')
		self.checkbutton31 = self.wtree.get_widget('checkbutton31')
		self.image2 = self.wtree.get_widget('image2')
		self.image4 = self.wtree.get_widget('image4')
		self.image15 = self.wtree.get_widget('image15')
		self.image_open1 = self.wtree.get_widget('menu-item-image9')
		self.image_open2 = self.wtree.get_widget('menu-item-image10')
		self.image_hide_panel = self.wtree.get_widget('menu-item-image16')
		self.image_show_panel = self.wtree.get_widget('menu-item-image17')
		self.viewport1 = self.wtree.get_widget('viewport1')
		self.viewport2 = self.wtree.get_widget('viewport2')
		self.image1 = self.wtree.get_widget('image1')
		self.hscale1 = self.wtree.get_widget('hscale1')
		self.hscale2 = self.wtree.get_widget('hscale2')
		self.hscale3 = self.wtree.get_widget('hscale3')
		self.hscale4 = self.wtree.get_widget('hscale4')
		self.hscale5 = self.wtree.get_widget('hscale5')
		self.hscale6 = self.wtree.get_widget('hscale6')
		self.hscale7 = self.wtree.get_widget('hscale7')
		self.hscale8 = self.wtree.get_widget('hscale8')
		self.hscale9 = self.wtree.get_widget('hscale9')
		self.hscale10 = self.wtree.get_widget('hscale10')
		self.hscale11 = self.wtree.get_widget('hscale11')
		self.hscale12 = self.wtree.get_widget('hscale12')
		self.hscale13 = self.wtree.get_widget('hscale13')
		self.hscale14 = self.wtree.get_widget('hscale14')
		self.hscale15 = self.wtree.get_widget('hscale15')
		self.hscale16 = self.wtree.get_widget('hscale16')
		self.hscale17 = self.wtree.get_widget('hscale17')
		self.hscale18 = self.wtree.get_widget('hscale18')
		self.hscale19 = self.wtree.get_widget('hscale19')
		self.hscale20 = self.wtree.get_widget('hscale20')
		self.hscale21 = self.wtree.get_widget('hscale21')
		self.hscale22 = self.wtree.get_widget('hscale22')
		self.hscale23 = self.wtree.get_widget('hscale23')
		self.hscale24 = self.wtree.get_widget('hscale24')
		self.hscale27 = self.wtree.get_widget('hscale27')
		self.hscale26 = self.wtree.get_widget('hscale26')
		self.hscale29 = self.wtree.get_widget('hscale29')
		self.hscale30 = self.wtree.get_widget('hscale30')
		self.hscale31 = self.wtree.get_widget('hscale31')
		self.hscale32 = self.wtree.get_widget('hscale32')
		self.hscale33 = self.wtree.get_widget('hscale33')
		self.image52 = self.wtree.get_widget('image52')
		self.image11 = self.wtree.get_widget('image11')
		self.image12 = self.wtree.get_widget('image12')
		self.image13 = self.wtree.get_widget('image13')
		self.image14 = self.wtree.get_widget('image14')
		self.image33 = self.wtree.get_widget('image33')
		self.image36 = self.wtree.get_widget('image36')
		self.image40 = self.wtree.get_widget('image40')
		self.image43 = self.wtree.get_widget('image43')
		self.image46 = self.wtree.get_widget('image46')
		self.image19 = self.wtree.get_widget('image19')
		self.image49 = self.wtree.get_widget('image49')
		self.scrolledwindow2 = self.wtree.get_widget('scrolledwindow2')
		self.scrolledwindow3 = self.wtree.get_widget('scrolledwindow3')
		self.scrolledwindow5 = self.wtree.get_widget('scrolledwindow5')
		self.scrolledwindow4 = self.wtree.get_widget('scrolledwindow4')
		self.treeview1 = self.wtree.get_widget('treeview1')
		self.treeview2 = self.wtree.get_widget('treeview2')
		self.treeview3 = self.wtree.get_widget('treeview3')
		self.treeview4 = self.wtree.get_widget('treeview4')
		self.treeview5 = self.wtree.get_widget('treeview5')
		self.treeview6 = self.wtree.get_widget('treeview6')
		self.toolbutton1 = self.wtree.get_widget('toolbutton1')
		self.toolbutton6 = self.wtree.get_widget('toolbutton6')
		self.toolbutton7 = self.wtree.get_widget('toolbutton7')
		self.toolbutton8 = self.wtree.get_widget('toolbutton8')
		self.toolbutton9 = self.wtree.get_widget('toolbutton9')
		self.toolbutton10 = self.wtree.get_widget('toolbutton10')
		self.toolbutton11 = self.wtree.get_widget('toolbutton11')
		self.toolbutton12 = self.wtree.get_widget('toolbutton12')
		self.toolbutton13 = self.wtree.get_widget('toolbutton13')
		self.toolbutton14 = self.wtree.get_widget('toolbutton14')
		self.toolbutton15 = self.wtree.get_widget('toolbutton15')
		self.toolbutton16 = self.wtree.get_widget('toolbutton16')
		self.toolbutton17 = self.wtree.get_widget('toolbutton17')
		self.toolbutton18 = self.wtree.get_widget('toolbutton18')
		self.toolbutton19 = self.wtree.get_widget('toolbutton19')
		self.toolbutton20 = self.wtree.get_widget('toolbutton20')
		self.toolbutton21 = self.wtree.get_widget('toolbutton21')
		self.toolbutton23 = self.wtree.get_widget('toolbutton23')
		self.toolbutton24 = self.wtree.get_widget('toolbutton24')
		self.toolbutton25 = self.wtree.get_widget('toolbutton25')
		self.toolbutton26 = self.wtree.get_widget('toolbutton26')
		self.toolbutton27 = self.wtree.get_widget('toolbutton27')
		self.toolbutton28 = self.wtree.get_widget('toolbutton28')
		self.toolbutton29 = self.wtree.get_widget('toolbutton29')
		self.toolbutton30 = self.wtree.get_widget('toolbutton30')
		self.toolbutton31 = self.wtree.get_widget('toolbutton31')
		self.toolbutton32 = self.wtree.get_widget('toolbutton32')
		self.toolbutton33 = self.wtree.get_widget('toolbutton33')
		self.toolbutton34 = self.wtree.get_widget('toolbutton34')
		self.toolbutton35 = self.wtree.get_widget('toolbutton35')
		self.toolbutton39 = self.wtree.get_widget('toolbutton39')
		self.toolbutton40 = self.wtree.get_widget('toolbutton40')
		self.toolbutton41 = self.wtree.get_widget('toolbutton41')
		self.toolbutton42 = self.wtree.get_widget('toolbutton42')
		self.toolbutton43 = self.wtree.get_widget('toolbutton43')
		self.toolbutton44 = self.wtree.get_widget('toolbutton44')
		self.toolbutton46 = self.wtree.get_widget('toolbutton46')
		self.eventbox1 = self.wtree.get_widget('eventbox1')
		self.eventbox3 = self.wtree.get_widget('eventbox3')
		self.eventbox5 = self.wtree.get_widget('eventbox5')
		self.eventbox6 = self.wtree.get_widget('eventbox6')
		self.adj = self.hscale1.get_adjustment()
		self.jpg_quality = self.hscale2.get_adjustment()
		self.spinbutton1 = self.wtree.get_widget('spinbutton1')
		self.spinbutton2 = self.wtree.get_widget('spinbutton2')
		self.spinbutton3 = self.wtree.get_widget('spinbutton3')
		self.spinbutton4 = self.wtree.get_widget('spinbutton4')
		self.spinbutton5 = self.wtree.get_widget('spinbutton5')
		self.spinbutton6 = self.wtree.get_widget('spinbutton6')
		self.spinbutton7 = self.wtree.get_widget('spinbutton7')
		self.spinbutton8 = self.wtree.get_widget('spinbutton8')
		self.spinbutton9 = self.wtree.get_widget('spinbutton9')
		self.spinbutton10 = self.wtree.get_widget('spinbutton10')
		self.spinbutton11 = self.wtree.get_widget('spinbutton11')
		self.spinbutton12 = self.wtree.get_widget('spinbutton12')
		self.spinbutton13 = self.wtree.get_widget('spinbutton13')
		self.spinbutton14 = self.wtree.get_widget('spinbutton14')
		self.spinbutton15 = self.wtree.get_widget('spinbutton15')
		self.spinbutton16 = self.wtree.get_widget('spinbutton16')
		self.spinbutton17 = self.wtree.get_widget('spinbutton17')
		self.spinbutton18 = self.wtree.get_widget('spinbutton18')
		self.spinbutton19 = self.wtree.get_widget('spinbutton19')
		self.spinbutton20 = self.wtree.get_widget('spinbutton20')
		self.spinbutton21 = self.wtree.get_widget('spinbutton21')
		self.spinbutton22 = self.wtree.get_widget('spinbutton22')
		self.spinbutton23 = self.wtree.get_widget('spinbutton23')
		self.spinbutton24 = self.wtree.get_widget('spinbutton24')
		self.spinbutton25 = self.wtree.get_widget('spinbutton25')
		self.spinbutton26 = self.wtree.get_widget('spinbutton26')
		self.spinbutton27 = self.wtree.get_widget('spinbutton27')
		self.spinbutton28 = self.wtree.get_widget('spinbutton28')
		self.spinbutton29 = self.wtree.get_widget('spinbutton29')
		self.spinbutton30 = self.wtree.get_widget('spinbutton30')
		self.spinbutton31 = self.wtree.get_widget('spinbutton31')
		self.spinbutton32 = self.wtree.get_widget('spinbutton32')
		self.spinbutton33 = self.wtree.get_widget('spinbutton33')
		self.spinbutton34 = self.wtree.get_widget('spinbutton34')
		self.spinbutton35 = self.wtree.get_widget('spinbutton35')
		self.spinbutton36 = self.wtree.get_widget('spinbutton36')
		self.spinbutton37 = self.wtree.get_widget('spinbutton37')
		self.spinbutton38 = self.wtree.get_widget('spinbutton38')
		self.spinbutton40 = self.wtree.get_widget('spinbutton40')
		self.spinbutton41 = self.wtree.get_widget('spinbutton41')
		self.spinbutton43 = self.wtree.get_widget('spinbutton43')
		self.spinbutton44 = self.wtree.get_widget('spinbutton44')
		self.spinbutton46 = self.wtree.get_widget('spinbutton46')
		self.spinbutton47 = self.wtree.get_widget('spinbutton47')
		self.spinbutton48 = self.wtree.get_widget('spinbutton48')
		self.win6_okbutton = self.wtree.get_widget('win6_okbutton')
		self.win6_cancelbutton = self.wtree.get_widget('win6_cancelbutton')
		self.menutoolbutton1 = self.wtree.get_widget('menutoolbutton1')
		self.colorbutton1 = self.wtree.get_widget('colorbutton1')
		self.colorbutton2 = self.wtree.get_widget('colorbutton2')
		self.colorbutton3 = self.wtree.get_widget('colorbutton3')
		self.colorbutton4 = self.wtree.get_widget('colorbutton4')
		self.colorbutton5 = self.wtree.get_widget('colorbutton5')
		self.colorbutton6 = self.wtree.get_widget('colorbutton6')
		self.colorbutton7 = self.wtree.get_widget('colorbutton7')
		self.colorbutton8 = self.wtree.get_widget('colorbutton8')
		self.eb = gtk.EventBox()
		self.fontbutton1 = self.wtree.get_widget('fontbutton1')
		self.toolbar1 = self.wtree.get_widget('toolbar1')
		self.toolbar2 = self.wtree.get_widget('toolbar2')
		self.button4 = self.wtree.get_widget('button4')
		self.button5 = self.wtree.get_widget('button5')
		self.button18 = self.wtree.get_widget('button18')
		self.button19 = self.wtree.get_widget('button19')
		self.button30 = self.wtree.get_widget('button30')
		self.button31 = self.wtree.get_widget('button31')
		self.button32 = self.wtree.get_widget('button32')
		self.button33 = self.wtree.get_widget('button33')
		self.button34 = self.wtree.get_widget('button34')
		self.button36 = self.wtree.get_widget('button36')
		self.button39 = self.wtree.get_widget('button39')
		self.button40 = self.wtree.get_widget('button40')
		self.button42 = self.wtree.get_widget('button42')
		self.button43 = self.wtree.get_widget('button43')
		self.button45 = self.wtree.get_widget('button45')
		self.button46 = self.wtree.get_widget('button46')
		self.button53 = self.wtree.get_widget('button53')
		self.button54 = self.wtree.get_widget('button54')
		self.button55 = self.wtree.get_widget('button55')
		self.button56 = self.wtree.get_widget('button56')
		self.button57 = self.wtree.get_widget('button57')
		self.button58 = self.wtree.get_widget('button58')
		self.button59 = self.wtree.get_widget('button59')
		self.button60 = self.wtree.get_widget('button60')
		self.button61 = self.wtree.get_widget('button61')
		self.button62 = self.wtree.get_widget('button62')
		self.button63 = self.wtree.get_widget('button63')
		self.button64 = self.wtree.get_widget('button64')
		self.button65 = self.wtree.get_widget('button65')
		self.button66 = self.wtree.get_widget('button66')
		self.button67 = self.wtree.get_widget('button67')
		self.button68 = self.wtree.get_widget('button68')
		self.button69 = self.wtree.get_widget('button69')
		self.button70 = self.wtree.get_widget('button70')
		self.button71 = self.wtree.get_widget('button71')
		self.button72 = self.wtree.get_widget('button72')
		self.button73 = self.wtree.get_widget('button73')
		self.button74 = self.wtree.get_widget('button74')
		self.button75 = self.wtree.get_widget('button75')
		self.button76 = self.wtree.get_widget('button76')
		self.button80 = self.wtree.get_widget('button80')
		self.button81 = self.wtree.get_widget('button81')
		self.button83 = self.wtree.get_widget('button83')
		self.button84 = self.wtree.get_widget('button84')
		self.button87 = self.wtree.get_widget('button87')
		self.button89 = self.wtree.get_widget('button89')
		self.button90 = self.wtree.get_widget('button90')
		self.button92 = self.wtree.get_widget('button92')
		self.button93 = self.wtree.get_widget('button93')
		self.button94 = self.wtree.get_widget('button94')
		self.button95 = self.wtree.get_widget('button95')
		self.button97 = self.wtree.get_widget('button97')
		self.button99 = self.wtree.get_widget('button99')
		self.button100 = self.wtree.get_widget('button100')
		self.button101 = self.wtree.get_widget('button101')
		self.button103 = self.wtree.get_widget('button103')
		self.sort_by_name = self.wtree.get_widget('radiomenuitem1')
		self.sort_by_type = self.wtree.get_widget('radiomenuitem2')
		self.sort_by_reverse = self.wtree.get_widget('radiomenuitem3')
		self.sort_by_random = self.wtree.get_widget('radiomenuitem4')
		self.imagemenuitem2 = self.wtree.get_widget('imagemenuitem2')
		self.imagemenuitem3 = self.wtree.get_widget('imagemenuitem3')
		self.imagemenuitem5 = self.wtree.get_widget('menu-item-image21')
		self.imagemenuitem6 = self.wtree.get_widget('imagemenuitem6')
		self.imagemenuitem8 = self.wtree.get_widget('imagemenuitem8')
		self.imagemenuitem9 = self.wtree.get_widget('imagemenuitem9')
		self.imagemenuitem19 = self.wtree.get_widget('imagemenuitem19')
		self.imagemenuitem20 = self.wtree.get_widget('imagemenuitem20')
		self.menu_item_image23 = self.wtree.get_widget('menu-item-image23')
		self.menu_item_image33 = self.wtree.get_widget('menu-item-image33')
		self.menu_item_image34 = self.wtree.get_widget('menu-item-image34')
		self.menu_item_image35 = self.wtree.get_widget('menu-item-image35')
		self.menuitem14 = self.wtree.get_widget('menuitem14')
		self.menuitem15 = self.wtree.get_widget('menuitem15')
		self.menuitem16 = self.wtree.get_widget('menuitem16')
		self.menuitem17 = self.wtree.get_widget('menuitem17')
		self.menuitem18 = self.wtree.get_widget('menuitem18')
		self.menuitem19 = self.wtree.get_widget('menuitem19')
		self.menuitem20 = self.wtree.get_widget('menuitem20')
		self.menuitem21 = self.wtree.get_widget('menuitem21')
		self.notebook2 = self.wtree.get_widget('notebook2')
		self.tooltip = gtk.Tooltips()
                self.make_background_pixbuf(self)
		self.grey = gtk.gdk.pixbuf_new_from_file('icons/layer1.png')
		self.stock_cancel_img = gtk.image_new_from_stock(gtk.STOCK_CANCEL,gtk.ICON_SIZE_BUTTON)
		self.stock_stop_img = gtk.image_new_from_stock(gtk.STOCK_STOP,gtk.ICON_SIZE_BUTTON)
		self.stock_close_img = gtk.image_new_from_stock(gtk.STOCK_CLOSE,gtk.ICON_SIZE_BUTTON)
		self.stock_properties_img = gtk.image_new_from_stock(gtk.STOCK_PROPERTIES,gtk.ICON_SIZE_BUTTON)
		self.togglebutton1 = self.wtree.get_widget('togglebutton1')
		self.togglebutton2 = self.wtree.get_widget('togglebutton2')
		self.expander2 = self.wtree.get_widget('expander2')
		self.expander3 = self.wtree.get_widget('expander3')
		self.expander4 = self.wtree.get_widget('expander4')
		self.expander5 = self.wtree.get_widget('expander5')
		self.expander6 = self.wtree.get_widget('expander6')
		self.expander7 = self.wtree.get_widget('expander7')
		self.expander9 = self.wtree.get_widget('expander9')
		self.expander8 = self.wtree.get_widget('expander8')
		self.expander10 = self.wtree.get_widget('expander10')
		self.expander11 = self.wtree.get_widget('expander11')
		self.expander12 = self.wtree.get_widget('expander12')
		self.expander13 = self.wtree.get_widget('expander13')
		self.expander14 = self.wtree.get_widget('expander14')
		self.expander15 = self.wtree.get_widget('expander15')
		self.expander16 = self.wtree.get_widget('expander16')
		self.expander17 = self.wtree.get_widget('expander17')
		self.expander18 = self.wtree.get_widget('expander18')
		self.expander20 = self.wtree.get_widget('expander20')
		self.expander21 = self.wtree.get_widget('expander21')
		
	def widgets_settings(self, event):
                self.dialog11.set_default_response(gtk.RESPONSE_OK)
		self.dialog13.set_default_response(gtk.RESPONSE_OK)
		self.dialog1.set_default_response(gtk.RESPONSE_OK)
		self.dialog13.set_default_response(gtk.RESPONSE_OK)
		self.dialog1.set_transient_for(self.window1)
		self.dialog19.set_transient_for(self.window1)
		self.dialog1.set_transient_for(self.dialog4)
		self.dialog16.set_transient_for(self.filechooser2)
		self.dialog18.set_transient_for(self.filechooser2)
		self.window5.set_transient_for(self.filechooser2)
		self.window8.set_transient_for(self.window1)
		self.context_id1 = self.statusbar1.get_context_id('win2_percentage')
		self.context_id2 = self.statusbar2.get_context_id('dimensions')
		self.context_id3 = self.statusbar3.get_context_id('tot. photos')
		self.context_id4 = self.statusbar4.get_context_id('win1_percentage')
		self.image52.set_from_file('icons/open_album.png')
		self.image11.set_from_file('icons/layout-gallery.png')
		self.image12.set_from_file('icons/layout-bottom.png')
		self.image13.set_from_file('icons/sound.png')
		self.image14.set_from_file('icons/video.png')
		self.image33.set_from_file('icons/object-flip-horizontal.png')
		self.image40.set_from_file('icons/object-flip-vertical.png')
		self.image43.set_from_file('icons/object-rotate-right.png')
		self.image46.set_from_file('icons/object-rotate-left.png')
		self.image49.set_from_file('icons/resize.png')
		self.image_open1.set_from_file('icons/open_album.png')
		self.image_open2.set_from_file('icons/open_photo.png')
		self.image_hide_panel.set_from_file('icons/hide-panel.png')
		self.image_show_panel.set_from_file('icons/show-panel.png')
		self.imagemenuitem5.set_from_file('icons/bottom-panel.png')
		self.menu_item_image23.set_from_file('icons/open_photo.png')
		self.menu_item_image33.set_from_file('icons/mime-image.png')
		self.menu_item_image34.set_from_file('icons/hide-pane.png')
		self.menu_item_image35.set_from_file('icons/mime-image.png')
		image10 = gtk.Image()
		image10.set_from_file('icons/rotate_ccw.png')
		self.toolbutton10.set_icon_widget(image10)
		image10.show()
                image11 = gtk.Image()
		image11.set_from_file('icons/rotate_cw.png')
		self.toolbutton11.set_icon_widget(image11)
		image11.show()
		image18 = gtk.Image()
		image18.set_from_file('icons/select_all.png')
		self.toolbutton18.set_icon_widget(image18)
		image18.show()
		image19 = gtk.Image()
		image19.set_from_file('icons/unselect.png')
		self.toolbutton19.set_icon_widget(image19)
		image19.show()
		image20 = gtk.Image()
		image20.set_from_file('icons/inverted.png')
		self.toolbutton20.set_icon_widget(image20)
		image20.show()
		image26 = gtk.Image()
		image26.set_from_file('icons/hide-panel.png')
		self.toolbutton26.set_icon_widget(image26)
		image26.show()
		image27 = gtk.Image()
		image27.set_from_file('icons/show-panel.png')
		self.toolbutton27.set_icon_widget(image27)
		image27.show()
		image28 = gtk.Image()
		image28.set_from_file('icons/hide-pane.png')
		self.toolbutton28.set_icon_widget(image28)
		image28.show()
		image29 = gtk.Image()
		image29.set_from_file('icons/bottom-panel.png')
		self.toolbutton29.set_icon_widget(image29)
		image29.show()
		image30 = gtk.Image()
		image30.set_from_file('icons/linear-hist.png')
		self.togglebutton1.add(image30)
		image30.show()
		image31 = gtk.Image()
		image31.set_from_file('icons/log-hist.png')
		self.togglebutton2.add(image31)
		image31.show()
		image32 = gtk.Image()
		image32.set_from_file('icons/rotate_ccw.png')
		self.toolbutton42.set_icon_widget(image32)
		image32.show()
                image33 = gtk.Image()
		image33.set_from_file('icons/rotate_cw.png')
		self.toolbutton43.set_icon_widget(image33)
		image33.show()
		image35 = gtk.Image()
		image35.set_from_file('icons/playlist.png')
		self.toolbutton46.set_icon_widget(image35)
		image35.show()
		self.nero = gtk.gdk.color_parse('#000000')
		self.selection_color = self.colorbutton5.get_color()
		self.colorbase = gtk.gdk.color_parse('#EFEFEF')
		self.viewport1.modify_bg(gtk.STATE_NORMAL, self.image_background_color)
		self.viewport2.modify_bg(gtk.STATE_NORMAL, self.treeview_color)
		self.window3.modify_bg(gtk.STATE_NORMAL, self.nero)
		self.window4.modify_bg(gtk.STATE_NORMAL, self.nero)
		self.window1.modify_bg(gtk.STATE_NORMAL, self.toolbar_color)
		self.window2.modify_bg(gtk.STATE_NORMAL, self.toolbar_color)
		self.toolbar1.modify_bg(gtk.STATE_NORMAL, self.toolbar_color)
		self.toolbar2.modify_bg(gtk.STATE_NORMAL, self.toolbar_color)
		self.eventbox1.modify_bg(gtk.STATE_NORMAL, self.gallery_color)
		self.treeview1.modify_base(gtk.STATE_NORMAL, self.treeview_color)
		self.treeview2.modify_base(gtk.STATE_NORMAL, self.treeview_color)
		self.treeview3.modify_base(gtk.STATE_NORMAL, self.treeview_color)
		self.eventbox3.modify_bg(gtk.STATE_NORMAL, self.treeview_color)
		self.eventbox5.modify_bg(gtk.STATE_NORMAL, self.treeview_color)
		self.eventbox6.modify_bg(gtk.STATE_NORMAL, self.treeview_color)
		self.fontbutton1.set_font_name(self.font)
		self.treeview1.modify_font(self.font_desc)	
		self.window1.set_icon_from_file('icons/logo.png')
		self.window2.set_icon_from_file('icons/logo.png')
		self.window5.set_icon_from_file('icons/logo.png')
		self.window6.set_icon_from_file('icons/logo.png')
		self.window7.set_icon_from_file('icons/logo.png')
		self.window8.set_icon_from_file('icons/logo.png')
		self.dialog1.set_icon_from_file('icons/logo.png')
		self.dialog2.set_icon_from_file('icons/logo.png')
		self.dialog3.set_icon_from_file('icons/logo.png')
		self.dialog4.set_icon_from_file('icons/logo.png')
		self.dialog5.set_icon_from_file('icons/logo.png')
		self.dialog6.set_icon_from_file('icons/logo.png')
		self.dialog8.set_icon_from_file('icons/logo.png')
		self.dialog10.set_icon_from_file('icons/logo.png')
		self.dialog11.set_icon_from_file('icons/logo.png')
		self.dialog12.set_icon_from_file('icons/logo.png')
		self.dialog13.set_icon_from_file('icons/logo.png')
		self.dialog14.set_icon_from_file('icons/logo.png')
		self.dialog15.set_icon_from_file('icons/logo.png')
		self.dialog16.set_icon_from_file('icons/logo.png')
		self.dialog17.set_icon_from_file('icons/logo.png')
		self.dialog18.set_icon_from_file('icons/logo.png')
		self.dialog19.set_icon_from_file('icons/logo.png')
		self.dialog20.set_icon_from_file('icons/logo.png')
		self.dialog21.set_icon_from_file('icons/logo.png')
		self.dialog22.set_icon_from_file('icons/logo.png')
		self.dialog23.set_icon_from_file('icons/logo.png')
		self.dialog24.set_icon_from_file('icons/logo.png')
		self.dialog25.set_icon_from_file('icons/logo.png')
		self.filechooser.set_icon_from_file('icons/logo.png')
		self.filechooser2.set_icon_from_file('icons/logo.png')
		self.filechooserdialog3.set_icon_from_file('icons/logo.png')
		self.filechooserbutton1.set_current_folder(self.ark[:-1])
		self.filechooserbutton2.set_current_folder(os.environ['HOME'])
		self.filechooser2.set_current_folder(os.environ['HOME'])
		self.filechooserdialog3.set_current_folder(os.environ['HOME'])
		self.entry4.set_text(self.ark[:-1])
		self.entry5.set_text(os.environ['HOME'])
		self.entry8.set_text(os.environ['HOME'])
		self.window1.set_title(self.version[:-2])
		self.window1.move(0, 0)
		self.window2.set_default_size(gtk.gdk.screen_width(), gtk.gdk.screen_height())
		self.scrolledwindow3.set_size_request(int(gtk.gdk.screen_width() * 0.68), -1)
		self.hpaned1.set_position(int(gtk.gdk.screen_width() * 0.15))
		self.menutoolbutton1.set_menu(self.menu3)
		self.filter0.set_name('Sound files')
		self.filter1.set_name('Image files') 
		self.filter2.set_name('ICC Profile')
		self.combobox1.handler_block(self.id50)
		self.combobox1.set_active(0)
		self.combobox1.handler_unblock(self.id50)
		self.togglebutton1.handler_block(self.id63)
		self.togglebutton1.set_active(True)
		self.togglebutton1.handler_unblock(self.id63)
		self.combobox6.set_active(0)
		self.combobox7.set_active(0)
		self.combobox8.set_active(0)
		self.combobox9.set_active(0)
		self.combobox11.set_active(0)
		self.combobox12.set_active(1)
		self.combobox13.set_active(0)
		self.combobox14.set_active(0)
		self.combobox15.set_active(0)
		self.spinbutton30.handler_block(self.id77)
		self.spinbutton38.handler_block(self.id78)
			
	def setup_signal_handlers(self, event):
                self.toolbutton10.connect('clicked', self.sx_rotation, 0)
                self.toolbutton11.connect('clicked', self.dx_rotation, 0)
                self.toolbutton13.connect("clicked", self.slideshow, 1)
		self.id1 = self.toolbutton16.connect("clicked", self.reduce_gallery)
		self.id2 = self.toolbutton17.connect("clicked", self.enlarge_gallery)
		self.id3 = self.treeview1.connect("row_activated", self.show_album)
		self.id4 = self.open1.connect("activate", self.Open)
		self.id5 = self.open_folder1.connect("activate", self.show_filechooserdialog1)
		self.id6 = self.open_album1.connect("activate", self.open_album)
		self.id7 = self.treeview2.connect("row_activated", self.get_folder)
		self.id8 = self.toolbutton1.connect("clicked", self.show_filechooserdialog1)
		self.id9 = self.toolbutton14.connect("clicked", self.add_album,None)
		self.id10 = self.toolbutton15.connect("clicked", self.delete_album)
		self.id11 = self.toolbutton18.connect("clicked", self.select_all)
		self.id12 = self.toolbutton19.connect("clicked", self.unselect)
		self.id13 = self.toolbutton20.connect("clicked", self.inverted_selection)
		self.id14 = self.new1.connect('activate', self.add_album, None)
		self.id15 = self.delete2.connect('activate', self.delete_album)
		self.id16 = self.add_selection1.connect('activate', self.pre_add_selection)
		self.id17 = self.delete_selection1.connect('activate', self.delete_selection)
		self.id18 = self.new2.connect('activate', self.add_album, None)
		self.id19 = self.toolbutton21.connect("clicked", self.slideshow, 1, 2)
		self.id20 = self.filechooserbutton4.connect("current_folder_changed", self.on_filechooserbutton4_current_folder_changed)
		self.id21 = self.filechooserbutton5.connect("current_folder_changed", self.on_filechooserbutton5_current_folder_changed)
		self.id22 = self.hpaned2.connect('notify', self.autoresize)
		self.id23 = self.toolbutton26.connect('clicked', self.set_panel, 'hide')
		self.id24 = self.toolbutton27.connect('clicked', self.set_panel, 'show')
		self.id26 = self.toolbutton29.connect('clicked', self.make_bottom_panel)
		self.id27 = self.vpaned2.connect('notify', self.autoresize2)
		self.id28 = self.hpaned1.connect('notify', self.autoresize2)
		self.id29 = self.eventbox1.connect("button_press_event", self.eventbox1_handler)
		self.id30 = self.toolbutton30.connect('clicked', self.fullscreen_mode)
		self.id31 = self.toolbutton31.connect('clicked', self.first_b_photo)
		self.id32 = self.toolbutton32.connect('clicked', self.previous_b_photo)
		self.id33 = self.toolbutton33.connect('clicked', self.next_b_photo)
		self.id34 = self.toolbutton34.connect('clicked', self.last_b_photo)
		self.id35 = self.toolbutton6.connect('clicked', self.zoom_in_photo, 0)
                self.id36 = self.toolbutton7.connect('clicked', self.zoom_out_photo, 0)
		self.id37 = self.toolbutton8.connect('clicked', self.zoom_fit_photo, 0)
                self.id38 = self.toolbutton9.connect('clicked', self.zoom_1_photo, 0)
		self.id39 = self.toolbutton28.connect('clicked', self.hide_pane)
		self.id40 = self.toolbutton35.connect('clicked', self.close_window2)
		self.id42 = self.combobox5.connect('changed' ,self.first_to_load_raw_preview)
		self.id43 = self.spinbutton4.connect('button-release-event', self.first_to_load_raw_preview)
		self.id44 = self.spinbutton5.connect('button-release-event', self.first_to_load_raw_preview)
		self.id45 = self.spinbutton6.connect('button-release-event', self.first_to_load_raw_preview)
		self.id46 = self.spinbutton7.connect('button-release-event', self.first_to_load_raw_preview)
		self.id47 = self.spinbutton8.connect('button-release-event', self.first_to_load_raw_preview)
		self.id48 = self.spinbutton9.connect('button-release-event', self.first_to_load_raw_preview)
		self.id49 = self.spinbutton1.connect('button-release-event', self.first_to_load_raw_preview)
		self.id65 = self.spinbutton11.connect('button-release-event', self.first_to_load_raw_preview)
		self.id79 = self.spinbutton35.connect('button-release-event', self.first_to_load_raw_preview)
		self.id50 = self.combobox1.connect('changed', self.on_combobox1_changed)
		self.id51 = self.hscale3.connect('button_release_event', self.first_to_load_raw_preview)
		self.id52 = self.radiobutton11.connect('toggled', self.first_to_load_raw_preview)
		self.id53 = self.checkbutton8.connect('toggled', self.first_to_load_raw_preview)
		self.id54 = self.checkbutton9.connect('toggled', self.first_to_load_raw_preview)
		self.id55 = self.checkbutton10.connect('toggled', self.first_to_load_raw_preview)
		self.id56 = self.checkbutton11.connect('toggled', self.first_to_load_raw_preview)
		self.id57 = self.checkbutton12.connect('toggled', self.first_to_load_raw_preview)
		self.id58 = self.checkbutton13.connect('toggled', self.first_to_load_raw_preview)
		self.id59 = self.checkbutton14.connect('toggled', self.first_to_load_raw_preview)
		self.id60 = self.combobox2.connect('changed', self.first_to_load_raw_preview)
		self.id61 = self.combobox3.connect('changed', self.first_to_load_raw_preview)
		self.id62 = self.combobox4.connect('changed', self.first_to_load_raw_preview)
		self.id63 = self.togglebutton1.connect('toggled', self.on_togglebutton1_toggled)
		self.id64 = self.togglebutton2.connect('toggled', self.on_togglebutton1_toggled)
		self.id66 = self.hscale15.connect('button_release_event', self.first_to_load_raw_preview)
		self.id67 = self.checkbutton16.connect('toggled', self.first_to_load_raw_preview)
		self.id68 = self.button53.connect('clicked', self.transform, 'flop')
		self.id69 = self.button56.connect('clicked', self.transform, 'flip')
		self.id70 = self.button59.connect('clicked', self.transform, 'rotate 90')
		self.id71 = self.button62.connect('clicked', self.transform, 'rotate -90')
		self.id72 = self.spinbutton19.connect('value-changed', self.on_spinbutton19_value_changed)
		self.id73 = self.spinbutton23.connect('value-changed', self.on_spinbutton23_value_changed)
		self.id74 = self.spinbutton24.connect('value-changed', self.on_spinbutton24_value_changed)
		self.id75 = self.spinbutton26.connect('value-changed', self.on_spinbutton26_value_changed)
		self.id77 = self.spinbutton30.connect('value-changed', self.on_spinbutton30_value_changed)
		self.id78 = self.spinbutton38.connect('value-changed', self.on_spinbutton38_value_changed)
		self.id80 = self.checkbutton26.connect('toggled', self.on_channel_mixer_changed, None)
		self.id76 = self.checkbutton23.connect('toggled', self.first_to_load_raw_preview)
		self.hpaned1.handler_block(self.id28)
		self.window1.connect('delete-event', self.destroy)
		self.window2.connect('delete-event', self.on_delete_event)
		self.window5.connect('delete-event', self.on_delete_event)
		self.window6.connect('delete-event', self.on_delete_event)
		self.dialog6.connect('delete-event', self.on_delete_event)
		self.filechooserbutton1.connect("current_folder_changed",\
                                                lambda w: self.entry4.set_text(self.filechooserbutton1.get_current_folder()))
		self.filechooserbutton2.connect("current_folder_changed",\
                                                lambda w: self.entry5.set_text(self.filechooserbutton2.get_current_folder()))
		self.filechooser2.connect("current_folder_changed",\
                                          lambda w: self.entry8.set_text(self.filechooser2.get_current_folder()))
                self.filechooserdialog3.connect("current_folder_changed",\
                                                lambda w: self.entry6.set_text(self.filechooserdialog3.get_current_folder()))
		self.imagemenuitem2.connect('activate', self.set_panel, 'hide')
		self.imagemenuitem3.connect('activate', self.set_panel, 'show')
		self.toolbutton40.connect('clicked', self.zoom_fit_photo, 1)
		self.toolbutton41.connect('clicked', self.zoom_1_photo, 1)
		self.toolbutton42.connect('clicked', self.sx_rotation, 1)
		self.toolbutton43.connect('clicked', self.dx_rotation, 1)
		self.viewport1_id1 = self.viewport1.connect('motion_notify_event', self.hand_image)
		self.viewport1_id2 = self.viewport1.connect('button_press_event', self.on_scrolledwindow_release_event)
                self.viewport1_id3 = self.viewport1.connect('button_release_event', self.on_scrolledwindow_release_event)
                self.button18.connect('clicked', self.reset_black_level, True)
                self.button19.connect('clicked', self.reset_white_level, True)
                self.button30.connect('clicked', self.reset_gamma, True)
                self.button32.connect('clicked', self.reset_brightness, True)
                self.button31.connect('clicked', self.reset_saturation, True)
                self.button87.connect('clicked', self.reset_hue, True)
                self.button39.connect('clicked', self.reset_color_balance, True)
		self.button43.connect('clicked', self.reset_contrast, True)
		self.button60.connect('clicked', self.reset_mixer)
		self.button99.connect('clicked', self.reset_red_mixer, True)
		self.button100.connect('clicked', self.reset_green_mixer, True)
		self.button101.connect('clicked', self.reset_blue_mixer, True)
		self.button46.connect('clicked', self.reset_midtones_contrast, True)
		self.expander2.connect('activate', self.on_expander_activate, True)
		self.expander3.connect('activate', self.on_expander_activate, True)
		self.expander4.connect('activate', self.on_expander_activate, True)
		self.expander5.connect('activate', self.on_expander_activate, True)
		self.expander6.connect('activate', self.on_expander_activate, True)
		self.expander7.connect('activate', self.on_expander_activate, True)
		self.expander8.connect('activate', self.on_expander_activate, True)
		self.expander9.connect('activate', self.on_expander_activate, True)
		self.expander10.connect('activate', self.on_expander_activate, True)
		self.expander11.connect('activate', self.on_expander_activate, True)
		self.expander12.connect('activate', self.on_expander_activate, True)
		self.expander13.connect('activate', self.on_expander_activate, True)
		self.expander14.connect('activate', self.on_expander_activate, True)
		self.expander15.connect('activate', self.on_expander_activate, True)
		self.expander16.connect('activate', self.on_expander_activate, True)
		self.expander17.connect('activate', self.on_expander_activate, True)
		self.expander18.connect('activate', self.on_expander_activate, True)
		self.expander20.connect('activate', self.on_expander_activate, True)
		self.expander21.connect('activate', self.on_expander_activate, True)
		self.button33.connect('enter_notify_event', self.show_overexposed_pixels, 'under')
		self.button34.connect('enter_notify_event', self.show_overexposed_pixels, 'over')
		self.button33.connect('leave_notify_event', self.on_exposure_buttons_leaved)
		self.button34.connect('leave_notify_event', self.on_exposure_buttons_leaved)
		self.button71.connect('clicked', self.apply_tags, 'add')
		self.button73.connect('clicked', self.apply_tags, 'remove')
		self.toolbutton46.connect('clicked' , self.show_batch_queue)
		self.combobox10.connect('changed' , self.on_combobox10_changed)

################################ IMAGE TOOLS METHODS #####################################################################

        def on_color_spinbutton_released(self, obj, event):   
                if obj == self.spinbutton10:
                        thread.start_new_thread(self.first_to_change_colors, (self.on_level_changed, self.hscale4, None))
		elif obj == self.spinbutton12:
                        thread.start_new_thread(self.first_to_change_colors, (self.on_level_changed, self.hscale5, None))
		elif obj == self.spinbutton13:
                        thread.start_new_thread(self.first_to_change_colors, (self.on_level_changed, self.hscale6, None))
		elif obj == self.spinbutton14:
                        thread.start_new_thread(self.first_to_change_colors, (self.on_brightness_and_saturation_changed, self.hscale7, event))
		elif obj == self.spinbutton15:
                        thread.start_new_thread(self.first_to_change_colors, (self.on_brightness_and_saturation_changed, self.hscale8, event))
		elif obj == self.spinbutton16:
                        thread.start_new_thread(self.first_to_change_colors, (self.color_balance, self.hscale9, event))
		elif obj == self.spinbutton17:
                        thread.start_new_thread(self.first_to_change_colors, (self.color_balance, self.hscale10, event))
		elif obj == self.spinbutton18:
                        thread.start_new_thread(self.first_to_change_colors, (self.color_balance, self.hscale11, event))
		elif obj == self.spinbutton20:
                        thread.start_new_thread(self.first_to_change_colors, (self.on_contrast_changed, self.hscale12, event))
		elif obj == self.spinbutton21:
                        thread.start_new_thread(self.first_to_change_colors, (self.on_midtones_contrast_changed, self.hscale13, event))
		elif obj == self.spinbutton22:
                        thread.start_new_thread(self.first_to_change_colors, (self.on_midtones_contrast_changed, self.hscale14, event))
                elif obj == self.spinbutton27 or obj == self.spinbutton28:
                        thread.start_new_thread(self.first_to_change_colors, (self.fine_rotation, obj, event))
                elif obj == self.spinbutton37:
                        thread.start_new_thread(self.first_to_change_colors,(self.on_brightness_and_saturation_changed, self.hscale18, event))
                elif obj == self.spinbutton48:
                        thread.start_new_thread(self.first_to_change_colors,(self.on_channel_mixer_changed, self.hscale31, None))
                elif obj == self.spinbutton47:
                        thread.start_new_thread(self.first_to_change_colors,(self.on_channel_mixer_changed, self.hscale32, None))
                elif obj == self.spinbutton46:
                        thread.start_new_thread(self.first_to_change_colors,(self.on_channel_mixer_changed, self.hscale33, None))
			
        def first_to_change_colors(self, fun, obj, event):
                self.pila.append(0)
                time.sleep(0.3)
                if len(self.pila) > 1:
			self.pila.pop()
                else:
			fun(obj, event)
			self.pila = []

	def on_hscale_scrolled(self, obj, event):
                return True

	def on_spinbutton_scrolled(self, obj, event):
                return True

	def on_hscale3_change_value(self, obj, event, value):
                self.spinbutton11.set_value(value)
                
	def on_hscale4_change_value(self, obj, event, value):
                self.spinbutton10.set_value(value)

	def on_hscale5_change_value(self, obj, event, value):
                self.spinbutton12.set_value(value)	

	def on_hscale6_change_value(self, obj, event, value):
                self.spinbutton13.set_value(value)
	
	def on_hscale7_change_value(self, obj, event, value):
                self.spinbutton14.set_value(value)
		
	def on_hscale8_change_value(self, obj, event, value):
                self.spinbutton15.set_value(value)
		
	def on_hscale9_change_value(self, obj, event, value):
                self.spinbutton16.set_value(value)
		
	def on_hscale10_change_value(self, obj, event, value):
                self.spinbutton17.set_value(value)
		
	def on_hscale11_change_value(self, obj, event, value):
                self.spinbutton18.set_value(value)
		
	def on_hscale12_change_value(self, obj, event, value):
                self.spinbutton20.set_value(value)
		
	def on_hscale13_change_value(self, obj, event, value):
                self.spinbutton21.set_value(value)
		
	def on_hscale14_change_value(self, obj, event, value):
                self.spinbutton22.set_value(value)
		
	def on_hscale15_change_value(self, obj, event, value):
                self.spinbutton1.set_value(value)

	def on_hscale16_change_value(self, obj, event, value):
                self.spinbutton25.set_value(value)

	def on_hscale17_change_value(self, obj, event, value):
                self.spinbutton29.set_value(value)

	def on_hscale18_change_value(self, obj, event, value):
                self.spinbutton37.set_value(value)
	
	def on_hscale19_change_value(self, obj, event, value):
                self.spinbutton31.set_value(value)
	
	def on_hscale20_change_value(self, obj, event, value):
                self.spinbutton33.set_value(value)
	
	def on_hscale21_change_value(self, obj, event, value):
                self.spinbutton32.set_value(value)
	
	def on_hscale22_change_value(self, obj, event, value):
                self.spinbutton34.set_value(value)
	
	def on_hscale24_change_value(self, obj, event, value):
                self.spinbutton36.set_value(value)

	def on_hscale26_change_value(self, obj, event, value):
                self.spinbutton41.set_value(value)

	def on_hscale27_change_value(self, obj, event, value):
                self.spinbutton40.set_value(value)

	def on_hscale29_change_value(self, obj, event, value):
                self.spinbutton43.set_value(value)

	def on_hscale30_change_value(self, obj, event, value):
                self.spinbutton44.set_value(value)

	def on_hscale31_change_value(self, obj, event, value):
                self.spinbutton48.set_value(value)

	def on_hscale32_change_value(self, obj, event, value):
                self.spinbutton47.set_value(value)

	def on_hscale33_change_value(self, obj, event, value):
                self.spinbutton46.set_value(value)
		
	def on_spinbutton1_value_changed(self, obj):
                self.hscale15.get_adjustment().value = obj.get_value()
		self.hscale15.queue_draw()

	def on_spinbutton10_value_changed(self, obj):
                self.hscale4.get_adjustment().value = obj.get_value()
		self.hscale4.queue_draw()
		
	def on_spinbutton11_value_changed(self, obj):
                self.hscale3.get_adjustment().value = obj.get_value()
		self.hscale3.queue_draw()

        def on_spinbutton12_value_changed(self, obj):
                self.hscale5.get_adjustment().value = obj.get_value()
		self.hscale5.queue_draw()

        def on_spinbutton13_value_changed(self, obj):
                self.hscale6.get_adjustment().value = obj.get_value()
		self.hscale6.queue_draw()
		
        def on_spinbutton14_value_changed(self, obj):
                self.hscale7.get_adjustment().value = obj.get_value()
		self.hscale7.queue_draw()

        def on_spinbutton15_value_changed(self, obj):
                self.hscale8.get_adjustment().value = obj.get_value()
		self.hscale8.queue_draw()

        def on_spinbutton16_value_changed(self, obj):
                self.hscale9.get_adjustment().value = obj.get_value()
		self.hscale9.queue_draw()

        def on_spinbutton17_value_changed(self, obj):
                self.hscale10.get_adjustment().value = obj.get_value()
		self.hscale10.queue_draw()
		
        def on_spinbutton18_value_changed(self, obj):
                self.hscale11.get_adjustment().value = obj.get_value()
		self.hscale11.queue_draw()

        def on_spinbutton20_value_changed(self, obj):
                self.hscale12.get_adjustment().value = obj.get_value()
		self.hscale12.queue_draw()

        def on_spinbutton21_value_changed(self, obj):
                self.hscale13.get_adjustment().value = obj.get_value()
		self.hscale13.queue_draw()

        def on_spinbutton22_value_changed(self, obj):
                self.hscale14.get_adjustment().value = obj.get_value()
		self.hscale14.queue_draw()

	def on_spinbutton25_value_changed(self, obj):
                self.hscale16.get_adjustment().value = obj.get_value()
		self.hscale16.queue_draw()

	def on_spinbutton29_value_changed(self, obj):
                self.hscale17.get_adjustment().value = obj.get_value()
		self.hscale17.queue_draw()
		
	def on_spinbutton30_value_changed(self, obj):
		self.on_drawing_area_expose_event(self.drawing_area, None, True)
		
	def on_spinbutton31_value_changed(self, obj):
                self.hscale19.get_adjustment().value = obj.get_value()
		self.hscale19.queue_draw()
		
	def on_spinbutton32_value_changed(self, obj):
                self.hscale21.get_adjustment().value = obj.get_value()
		self.hscale21.queue_draw()
		
	def on_spinbutton33_value_changed(self, obj):
                self.hscale20.get_adjustment().value = obj.get_value()
		self.hscale20.queue_draw()
		
	def on_spinbutton34_value_changed(self, obj):
                self.hscale22.get_adjustment().value = obj.get_value()
		self.hscale22.queue_draw()
		
	def on_spinbutton36_value_changed(self, obj):
                self.hscale24.get_adjustment().value = obj.get_value()
		self.hscale24.queue_draw()

	def on_spinbutton37_value_changed(self, obj):
                self.hscale18.get_adjustment().value = obj.get_value()
		self.hscale18.queue_draw()

	def on_spinbutton48_value_changed(self, obj):
                self.hscale31.get_adjustment().value = obj.get_value()
		self.hscale31.queue_draw()

	def on_spinbutton47_value_changed(self, obj):
                self.hscale32.get_adjustment().value = obj.get_value()
		self.hscale32.queue_draw()

	def on_spinbutton46_value_changed(self, obj):
                self.hscale33.get_adjustment().value = obj.get_value()
		self.hscale33.queue_draw()
		
	def on_spinbutton38_value_changed(self, obj):
		self.on_drawing_area_expose_event(self.drawing_area, None, True)
		
	def on_spinbutton19_value_changed(self, obj):
                self.spinbutton23.set_value(obj.get_value() / self.ratio)

        def on_spinbutton23_value_changed(self, obj):
                self.spinbutton19.set_value(obj.get_value() * self.ratio)

        def on_spinbutton24_value_changed(self, obj):
                self.spinbutton26.set_value(obj.get_value())

        def on_spinbutton26_value_changed(self, obj):
                self.spinbutton24.set_value(obj.get_value())

        def on_spinbutton40_value_changed(self, obj):
                self.hscale27.get_adjustment().value = obj.get_value()
		self.hscale27.queue_draw()

	def on_spinbutton41_value_changed(self, obj):
                self.hscale26.get_adjustment().value = obj.get_value()
		self.hscale26.queue_draw()

	def on_spinbutton43_value_changed(self, obj):
                self.hscale29.get_adjustment().value = obj.get_value()
		self.hscale29.queue_draw()

	def on_spinbutton44_value_changed(self, obj):
                self.hscale30.get_adjustment().value = obj.get_value()
		self.hscale30.queue_draw()

	def on_checkbutton18_toggled(self, *obj):
                if self.checkbutton18.get_active():
                        self.spinbutton19.handler_unblock(self.id72)
                        self.spinbutton23.handler_unblock(self.id73)
                else:
                        self.spinbutton19.handler_block(self.id72)
                        self.spinbutton23.handler_block(self.id73)

        def on_checkbutton19_toggled(self, *obj):
                if self.checkbutton19.get_active():
                        self.spinbutton24.handler_unblock(self.id74)
                        self.spinbutton26.handler_unblock(self.id75)
                else:
                        self.spinbutton24.handler_block(self.id74)
                        self.spinbutton26.handler_block(self.id75)

        def on_checkbutton20_toggled(self, *obj):
                if not self.checkbutton20.get_active() and not self.workflow_copy:
                        self.label136.set_text('There is not a workflow to save.\nPlease, make a new one!')
                        self.dialog25.show()
                        response = self.dialog25.run()
                        if response == gtk.RESPONSE_CLOSE or response == gtk.RESPONSE_DELETE_EVENT:
                                self.dialog25.hide()
			
	def on_checkbutton21_toggled(self, *obj):
		if self.checkbutton21.get_active(): 
			self.combobox12.set_sensitive(False)
			self.spinbutton30.handler_unblock(self.id77)
			self.spinbutton38.handler_unblock(self.id78)
			self.on_drawing_area_expose_event(self.drawing_area, None, True)
		else:                               
			self.combobox12.set_sensitive(True)
			self.spinbutton30.handler_block(self.id77)
			self.spinbutton38.handler_block(self.id78)
			self.on_drawing_area_expose_event(self.drawing_area, None, True)

	def on_checkbutton24_toggled(self, *obj):
		if self.checkbutton24.get_active():
                        self.draw_grid(False)
		else:
                        self.image1.set_from_pixbuf(self.pblist[self.pbindex])
                        self.image1.show()

        def show_overexposed_pixels(self, obj, event, data):
                self.overexposed = True
                outfile = os.getcwd() + '/.temp/overexposed'
		if self.workflow_started:
                	wand = MagickImage(self.wand.get_image())
		else:
                        self.pblist[self.pbindex].save(outfile, 'jpeg')
                        wand = MagickImage(outfile)
                if data == 'over':
                        wand.opaque_paint(Color('white'), Color('black'), 0)
                else:
                        wand.opaque_paint(Color('black'), Color('white'), 0)
                pixbuf = self.scale_pixbuf(*self.wand2pixbuf(wand))
                while self.overexposed:
                        self.image1.set_from_pixbuf(pixbuf)
                        while gtk.events_pending():
                                gtk.main_iteration(False)
                        time.sleep(0.5)
                        self.image1.set_from_pixbuf(self.pblist[self.pbindex])
                        while gtk.events_pending():
                                gtk.main_iteration(False)
                        if not self.overexposed:
                                break
                        time.sleep(0.5)
		if os.path.isfile(outfile):
			os.remove(outfile)
                del wand, pixbuf

        def on_exposure_buttons_leaved(self, obj, event):
                self.overexposed = False
	
	def on_combobox10_changed(self, event):
		if self.combobox10.get_active() == 0:
                        self.hscale23.set_sensitive(True)
		else:
                        self.hscale23.set_sensitive(False)

        def on_combobox6_changed(self, event):
                adj4 = self.hscale4.get_adjustment()
                adj5 = self.hscale5.get_adjustment()
                adj6 = self.hscale6.get_adjustment()
                channel = self.combobox6.get_active_text()
                adj4.value, adj6.value, adj5.value = self.RGB_levels[channel][0], self.RGB_levels[channel][1], self.RGB_levels[channel][2]
		self.spinbutton10.set_value(adj4.value)
		self.spinbutton12.set_value(adj5.value)
		self.spinbutton13.set_value(adj6.value) 
		
	def on_combobox13_changed(self, event):
		channel = self.combobox13.get_active_text()
		adj31 = self.hscale31.get_adjustment()
                adj32 = self.hscale32.get_adjustment()
                adj33 = self.hscale33.get_adjustment()
                adj31.value, adj32.value, adj33.value = self.mixer_levels[channel][0], self.mixer_levels[channel][1], self.mixer_levels[channel][2]
		self.spinbutton48.set_value(adj31.value)
		self.spinbutton47.set_value(adj32.value)
		self.spinbutton46.set_value(adj33.value)

        def reset_black_level(self, obj, data):
		gtk.gdk.threads_enter()
		time.sleep(0.1)
                self.hscale4.get_adjustment().set_value(0)
		self.spinbutton10.set_value(0)
                channel = self.combobox6.get_active_text()
                self.RGB_levels[channel][0]=0
                if data:
                        self.wand = MagickImage(self.wand_list[self.wand_index].get_image())
                        self.on_level_changed(self.hscale4, None)
		self.image_was_changed = False
		gtk.gdk.threads_leave()

        def reset_white_level(self, obj, data):
		gtk.gdk.threads_enter()
		time.sleep(0.1)
                self.hscale5.get_adjustment().set_value(100)
		self.spinbutton12.set_value(100)
                channel = self.combobox6.get_active_text()
                self.RGB_levels[channel][2] = 100
                if data:
                        self.wand = MagickImage(self.wand_list[self.wand_index].get_image())
                        self.on_level_changed(self.hscale5, None)
		self.image_was_changed = False
		gtk.gdk.threads_leave()

        def reset_gamma(self, obj, data):
		gtk.gdk.threads_enter()
		time.sleep(0.1)
                self.hscale6.get_adjustment().set_value(1.00)
		self.spinbutton13.set_value(1.00)
                channel = self.combobox6.get_active_text()
                self.RGB_levels[channel][1] = 1.00
                if data:
                        self.wand = MagickImage(self.wand_list[self.wand_index].get_image())
                        self.on_level_changed(self.hscale6, None)
		self.image_was_changed = False
		gtk.gdk.threads_leave()
		
	def reset_levels(self, data):
		self.reset_black_level(self.button18, data)
		self.reset_white_level(self.button19, data)
		self.reset_gamma(self.button30, data)
		self.image_was_changed = False
		if self.expander17.get_expanded():
			width = self.pblist[self.pbindex].get_width()
			height = self.pblist[self.pbindex].get_height()
			self.drawable.draw_pixbuf(self.gc,self.pblist[self.pbindex], 0, 0,\
                                                  int((self.rect.width - width)/2), int((self.rect.height - height) / 2))
			self.drawing_area.queue_draw()
		elif self.expander8.get_expanded():
			self.draw_grid(False)
		elif self.window2_closed:
			self.image1.clear()
		else:
                	self.image1.set_from_pixbuf(self.pblist[self.pbindex])
			self.image1.show()

        def reset_brightness(self, obj, data):
		gtk.gdk.threads_enter()
		time.sleep(0.1)
                self.hscale7.get_adjustment().set_value(0)
		self.spinbutton14.set_value(0)
                self.bright_sat[0] = 0
                while gtk.events_pending(): gtk.main_iteration(False)
                if data:
                        self.wand = MagickImage(self.wand_list[self.wand_index].get_image())
                        self.on_brightness_and_saturation_changed(self.hscale7, None)
		self.image_was_changed = False
		gtk.gdk.threads_leave()

        def reset_saturation(self, obj, data):
		gtk.gdk.threads_enter()
		time.sleep(0.1)
                self.hscale8.get_adjustment().set_value(0)
		self.spinbutton15.set_value(0)
                self.bright_sat[1] = 0
                while gtk.events_pending(): gtk.main_iteration(False)
                if data:
                        self.wand = MagickImage(self.wand_list[self.wand_index].get_image())
                        self.on_brightness_and_saturation_changed(self.hscale8, None)
		self.image_was_changed = False
		gtk.gdk.threads_leave()

	def reset_hue(self, obj, data):
		gtk.gdk.threads_enter()
		time.sleep(0.1)
                self.hscale18.get_adjustment().set_value(0)
		self.spinbutton37.set_value(0)
                self.bright_sat[2] = 0
                while gtk.events_pending(): gtk.main_iteration(False)
                if data:
                        self.wand = MagickImage(self.wand_list[self.wand_index].get_image())
                        self.on_brightness_and_saturation_changed(self.hscale18, None)
		self.image_was_changed = False
		gtk.gdk.threads_leave()
		
	def reset_brightness_and_saturation(self, data):
		self.reset_saturation(self.button31, data)
		self.reset_brightness(self.button32, data)
		self.reset_hue(self.button87, data)
		if self.expander17.get_expanded():
			width = self.pblist[self.pbindex].get_width()
			height = self.pblist[self.pbindex].get_height()
			self.drawable.draw_pixbuf(self.gc, self.pblist[self.pbindex], 0, 0,\
                                                  int((self.rect.width - width)/2), int((self.rect.height - height) / 2))
			self.drawing_area.queue_draw()
		elif self.expander8.get_expanded():
			self.draw_grid(False)
		else:
                	self.image1.set_from_pixbuf(self.pblist[self.pbindex])
			self.image1.show()

        def reset_color_balance(self, obj, data):
		gtk.gdk.threads_enter()
		time.sleep(0.1)
                self.hscale9.get_adjustment().set_value(0)
                self.hscale10.get_adjustment().set_value(0)
                self.hscale11.get_adjustment().set_value(0)
		self.spinbutton16.set_value(0)
		self.spinbutton17.set_value(0)
		self.spinbutton18.set_value(0)
                self.c_balance= [0, 0, 0]
                while gtk.events_pending():
                        gtk.main_iteration(False)
                if data:
                        self.wand = MagickImage(self.wand_list[self.wand_index].get_image())
                        self.color_balance(self.hscale9, None)
		self.image_was_changed = False
		gtk.gdk.threads_leave()
		if self.expander17.get_expanded():
			width = self.pblist[self.pbindex].get_width()
			height = self.pblist[self.pbindex].get_height()
			self.drawable.draw_pixbuf(self.gc, self.pblist[self.pbindex], 0, 0,\
                                                  int((self.rect.width - width)/2), int((self.rect.height - height)/2))
			self.drawing_area.queue_draw()
		elif self.expander8.get_expanded():
			self.draw_grid(False)
		else:
                	self.image1.set_from_pixbuf(self.pblist[self.pbindex])
			self.image1.show()
		
	def reset_contrast(self, obj, data):
		gtk.gdk.threads_enter()
		time.sleep(0.1)
		self.window2.window.set_cursor(self.watch)
		while gtk.events_pending():
                        gtk.main_iteration(False)
		self.hscale12.get_adjustment().set_value(0)
		self.spinbutton20.set_value(0)
		while gtk.events_pending():
                        gtk.main_iteration(False)
		if data:
                        self.wand = MagickImage(self.wand_list[self.wand_index].get_image())
			width, height = self.wand.size
			if width > self.rect.width or height > self.rect.height:
				self.pblist[self.pbindex] = self.scale_pixbuf(*self.wand2pixbuf(self.wand))
			else:
				self.pblist[self.pbindex] = self.wand2pixbuf(self.wand)[0]
		self.image_was_changed = False
		if self.expander17.get_expanded():
			width = self.pblist[self.pbindex].get_width()
			height = self.pblist[self.pbindex].get_height()
			self.drawable.draw_pixbuf(self.gc,self.pblist[self.pbindex], 0, 0,\
                                                  int((self.rect.width - width)/2), int((self.rect.height - height) / 2))
			self.drawing_area.queue_draw()
		elif self.expander8.get_expanded():
			self.draw_grid(False)
		else:
                	self.image1.set_from_pixbuf(self.pblist[self.pbindex])
			self.image1.show()
		self.get_channel()
                self.window2.window.set_cursor(None)
		gtk.gdk.threads_leave()
		
	def reset_midtones_contrast(self, obj, data):
		gtk.gdk.threads_enter()
		time.sleep(0.1)
		self.window2.window.set_cursor(self.watch)
		while gtk.events_pending():
                        gtk.main_iteration(False)
		self.hscale13.get_adjustment().set_value(0)
		self.hscale14.get_adjustment().set_value(50)
		self.spinbutton21.set_value(0)
		self.spinbutton22.set_value(50)
		while gtk.events_pending():
                        gtk.main_iteration(False)
		if data:
                        self.wand = MagickImage(self.wand_list[self.wand_index].get_image())
			width, height = self.wand.size
			if width > self.rect.width or height > self.rect.height:
				self.pblist[self.pbindex] = self.scale_pixbuf(*self.wand2pixbuf(self.wand))
			else:
				self.pblist[self.pbindex] = self.wand2pixbuf(self.wand)[0]
		self.image_was_changed = False
		if self.expander17.get_expanded():
			width = self.pblist[self.pbindex].get_width()
			height = self.pblist[self.pbindex].get_height()
			self.drawable.draw_pixbuf(self.gc, self.pblist[self.pbindex], 0, 0,\
                                                  int((self.rect.width - width)/2), int((self.rect.height - height) / 2))
			self.drawing_area.queue_draw()
		elif self.expander8.get_expanded():
			self.draw_grid(False)
		else:
                	self.image1.set_from_pixbuf(self.pblist[self.pbindex])
			self.image1.show()
		self.get_channel()
                self.window2.window.set_cursor(None)
		gtk.gdk.threads_leave()

	def reset_unsharp_mask(self):
                self.hscale27.get_adjustment().set_value(1.0)
		self.spinbutton40.set_value(1.0)
		self.hscale26.get_adjustment().set_value(0)
		self.spinbutton41.set_value(0)
		self.hscale29.get_adjustment().set_value(1.0)
		self.spinbutton43.set_value(1.0)
		self.hscale30.get_adjustment().set_value(0.05)
		self.spinbutton44.set_value(0.05)
		while gtk.events_pending():
                        gtk.main_iteration(False)
		
	def reset_expander(self):
		for item in self.expander_list:
			if item.get_expanded(): 
				if item == self.expander2:
                                        self.reset_levels(False)
				elif item == self.expander3:
                                        self.reset_brightness_and_saturation(False)
				elif item == self.expander4:
                                        self.reset_color_balance(self.button39, False)
				elif item == self.expander5:
                                        self.reset_contrast(self.button43, False)
				elif item == self.expander6:
                                        self.reset_midtones_contrast(self.button46, False)
				elif item == self.expander7:
                                        self.undo_handler(self.button65)
				elif item == self.expander8:
                                        self.undo_handler(self.button54)
				elif item == self.expander9:
                                        self.undo_handler(self.button72)
				elif item == self.expander10:
                                        self.undo_handler(self.button57)
				elif item == self.expander11:
                                        self.undo_handler(self.button68)
				elif item == self.expander12:
                                        self.undo_handler(self.button61)
				elif item == self.expander13:
                                        self.undo_handler(self.button74)
				elif item == self.expander14:
                                        self.undo_handler(self.button80)
				elif item == self.expander15:
                                        self.undo_handler(self.button83)
				elif item == self.expander16:
                                        self.undo_handler(self.button89)
				elif item == self.expander17:
                                        self.undo_handler(self.button93)
				elif item == self.expander18:
                                        self.undo_handler(self.button94)
				elif item == self.expander20:
                                        self.reset_mixer(False)
				elif item == self.expander21:
                                        self.undo_handler(self.button92)
		if os.path.splitext(self.list[self.indice])[1] in self.formats:
			self.pblist[self.previous_index] = self.original_pixbuf

	def show_dialog21(self, data=None):
		if not self.checkbutton15.get_active():
			self.dialog21.show()
			response = self.dialog21.run()
			if response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_DELETE_EVENT:
				self.dialog21.hide()
				while gtk.events_pending():
                                        gtk.main_iteration(False)
				return True
			elif response == gtk.RESPONSE_OK:
				self.dialog21.hide()
				if data:
                                        self.window2.hide()
				while gtk.events_pending():
                                        gtk.main_iteration(False)
				self.reset_expander()
				self.workflow_started = False
				self.history= []
				self.wand_list= []
				self.wand_index = 0
				self.magick_size = 0
				self.size_history= [0] * 100
				self.set_toolbuttons_23_39_sensitivity()
				return False
		else:
                        if data:
                                self.window2.hide()
			self.reset_expander()
			self.workflow_started = False
			self.history= []
			self.wand_list= []
			self.wand_index = 0
			self.magick_size = 0
			self.size_history= [0] * 100
			self.set_toolbuttons_23_39_sensitivity()
			return False 
		
	def set_sensitivity(self, format):
		for item in [self.toolbutton6, self.toolbutton7, self.toolbutton8,\
                             self.toolbutton9, self.toolbutton10, self.toolbutton11]:
			if self.workflow_started and not self.checkbutton17.get_active():
				item.set_sensitive(False)
			else:   item.set_sensitive(True)
		if self.workflow_started:
			self.toolbutton12.set_sensitive(False)
			self.toolbutton13.set_sensitive(False)
		else:
			self.toolbutton12.set_sensitive(True)
			self.toolbutton13.set_sensitive(True)	

	def set_filenames(self):
                format = os.path.splitext(self.list[self.indice])[1]
		if not self.workflow_started:
			if not self.checkbutton17.get_active():
				if format.lower() in self.formats:
					if format.lower() in ['.jpg', '.jpeg']:
						self.pblist[self.pbindex].save(self.temp + self.fname, 'jpeg')
					elif format.lower() not in ['.jpg', '.jpeg']:
						self.pblist[self.pbindex].save(self.temp + self.fname, format.lower()[1:])
				else:   
					self.pblist[self.pbindex].save(self.temp + self.fname, 'tiff')
                if format.lower() in self.formats:
			if not self.checkbutton17.get_active():
				self.infile =  self.temp + self.fname
			else:
                        	self.infile = self.list[self.indice]
                else:
                        self.infile = self.temp + self.fname
			
		if not self.workflow_started:			
                	self.wand = MagickImage(self.infile)
                        self.wand_list += [ MagickImage(self.wand.get_image()) ]	
		else:
                        self.wand = MagickImage(self.wand_list[self.wand_index].get_image())
		return  format
		
	def show_image1(self):
		if self.wand:
			width, height = self.wand.size
			if width > self.rect.width or height > self.rect.height:
				self.pblist[self.pbindex] = self.scale_pixbuf(*self.wand2pixbuf(self.wand))
			else:
				self.pblist[self.pbindex] = self.wand2pixbuf(self.wand)[0]
		if self.expander8.get_expanded():
			self.draw_grid(False)
		else:
			self.image1.set_from_pixbuf(self.pblist[self.pbindex])
			self.image1.show()
		while gtk.events_pending():
                        gtk.main_iteration(False)	

        def on_level_changed(self, obj, event):
                self.window2.window.set_cursor(self.watch)
		while gtk.events_pending():
                        gtk.main_iteration(False)
		value4 = self.hscale4.get_adjustment().value
                value5 = self.hscale5.get_adjustment().value
                value6 = self.hscale6.get_adjustment().value
                channel = self.combobox6.get_active_text()
		if [value4, value6, value5] == self.RGB_levels[channel] and event: 
			self.window2.window.set_cursor(None)
			return False
		format = self.set_filenames()
                self.RGB_levels[channel] = [value4, value6, value5]
                for item in self.level_hist:
                        if item[0] == channel:
                                item[1] = self.RGB_levels[channel]
                                break
                else:   
			self.level_hist.append( [channel, self.RGB_levels[channel] ] )
                self.adjust_levels()
		if not self.workflow_started:
                        self.original_pixbuf = self.pblist[self.pbindex].copy()
		self.show_image1()
		self.get_channel()
                self.window2.window.set_cursor(None)
		self.image_was_changed = True 
		self.workflow_started = True
		self.set_sensitivity(format)

	def adjust_levels(self):
		for item in self.level_hist:
			if item[1] == [0.0, 1.0, 100.0]:
                                del self.level_hist[self.level_hist.index(item)]
                for item in self.level_hist:
                        if item[0] == 'RGB':
                                channel = api.AllChannels
                        elif item[0] == 'Red':
                                channel = api.RedChannel
                        elif item[0] == 'Green':
                                channel = api.GreenChannel
                        elif item[0] == 'Blue':
                                channel = api.BlueChannel
                        self.wand.adjust_levels(item[1][0] * Q_RANGE / 100, item[1][1], item[1][2] * Q_RANGE / 100, channel)
		
	def apply_normalize(self, obj):
		self.window2.window.set_cursor(self.watch)
                while gtk.events_pending():
                        gtk.main_iteration(False)
                format = self.set_filenames()
		self.wand.normalize()
		if not self.workflow_started:
                        self.original_pixbuf = self.pblist[self.pbindex].copy()
	 	self.show_image1()
		self.get_channel()
		self.image_was_changed = True
		self.workflow_started = True
		self.set_sensitivity(format)
		self.button92.set_sensitive(True)
		self.window2.window.set_cursor(None)

	def on_channel_mixer_changed(self, obj, event):
                self.window2.window.set_cursor(self.watch)
		while gtk.events_pending():
                        gtk.main_iteration(False)
		value31 = self.hscale31.get_adjustment().value
                value32 = self.hscale32.get_adjustment().value
                value33 = self.hscale33.get_adjustment().value
                channel = self.combobox13.get_active_text()
		if [value31, value32, value33] == self.mixer_levels[channel] and event: 
			self.window2.window.set_cursor(None)
			return False
		format = self.set_filenames()
                self.mixer_levels[channel] = [value31, value32, value33]
                self.mix_channels()
		if not self.workflow_started:
                        self.original_pixbuf = self.pblist[self.pbindex].copy()
		self.show_image1()
		self.get_channel()
                self.window2.window.set_cursor(None)
		self.image_was_changed = True 
		self.workflow_started = True
		self.set_sensitivity(format)

	def mix_channels(self):
                red = self.mixer_levels['Red']
                green = self.mixer_levels['Green']
                blue = self.mixer_levels['Blue']
                self.matrix=(red[0] / 100, red[1] / 100, red[2] / 100, green[0] / 100, green[1] / 100, green[2] / 100,\
                blue[0] / 100, blue[1] / 100, blue[2] / 100)
                self.wand.recolor(3, self.matrix)
                if self.checkbutton26.get_active():
                        self.wand._set_colorspace(api.GRAYColorspace)

        def reset_mixer(self, data):
		self.combobox13.set_active(0)
		self.hscale31.get_adjustment().set_value(100)
                self.spinbutton48.set_value(100)
		self.hscale32.get_adjustment().set_value(0)
                self.spinbutton47.set_value(0)
		self.hscale33.get_adjustment().set_value(0)
                self.spinbutton46.set_value(0)
                self.mixer_levels = {'Red' : [100, 0, 0], 'Green' : [0, 100, 0], 'Blue' : [0, 0, 100]}
		self.checkbutton26.set_active(False)
		self.on_channel_mixer_changed(None, None)
		self.image_was_changed = False
		if self.expander17.get_expanded():
			width = self.pblist[self.pbindex].get_width()
			height = self.pblist[self.pbindex].get_height()
			self.drawable.draw_pixbuf(self.gc, self.pblist[self.pbindex], 0, 0,\
                                                  int((self.rect.width - width) / 2), int((self.rect.height - height) / 2))
			self.drawing_area.queue_draw()
		elif self.expander8.get_expanded():
			self.draw_grid(False)
		else:
                	self.image1.set_from_pixbuf(self.pblist[self.pbindex])
			self.image1.show()

        def reset_red_mixer(self, obj, data):
		gtk.gdk.threads_enter()
		time.sleep(0.1)
		channel = self.combobox13.get_active_text()
		if channel == 'Red':
                        value = 100
                else:
                        value = 0
                self.hscale31.get_adjustment().set_value(value)
                self.spinbutton48.set_value(value)
                self.mixer_levels[channel][0] = value
                if data:
                        self.wand = MagickImage(self.wand_list[self.wand_index].get_image())
                        self.on_channel_mixer_changed(self.hscale31, None)
		self.image_was_changed = False
		gtk.gdk.threads_leave()

	def reset_green_mixer(self, obj, data):
		gtk.gdk.threads_enter()
		time.sleep(0.1)
		channel = self.combobox13.get_active_text()
		if channel == 'Green':
                        value = 100
                else:
                        value = 0
                self.hscale32.get_adjustment().set_value(value)
                self.spinbutton47.set_value(value)
                self.mixer_levels[channel][1] = value
                if data:
                        self.wand = MagickImage(self.wand_list[self.wand_index].get_image())
                        self.on_channel_mixer_changed(self.hscale32, None)
		self.image_was_changed = False
		gtk.gdk.threads_leave()

	def reset_blue_mixer(self, obj, data):
		gtk.gdk.threads_enter()
		time.sleep(0.1)
		channel = self.combobox13.get_active_text()
		if channel == 'Blue':
                        value = 100
                else:
                        value = 0
                self.hscale33.get_adjustment().set_value(value)
                self.spinbutton46.set_value(value)
                self.mixer_levels[channel][2] = value
                if data:
                        self.wand = MagickImage(self.wand_list[self.wand_index].get_image())
                        self.on_channel_mixer_changed(self.hscale33, None)
		self.image_was_changed = False
		gtk.gdk.threads_leave()

	def save_mixer(self):
		self.wand_index += 1
		if self.wand_index == len(self.wand_list):
                        self.wand_list += [ MagickImage(self.wand.get_image()) ]
                else:
                        self.wand_list[self.wand_index] = MagickImage(self.wand.get_image())
                        del self.wand_list[self.wand_index+1:]
                        del self.history[self.wand_index - 1:]
                        self.size_history[self.wand_index:] = [self.size_history[self.wand_index] for i in xrange(self.wand_index,100)]
		self.set_toolbuttons_23_39_sensitivity()
		while gtk.events_pending():
                        gtk.main_iteration(False)
		thread.start_new_thread(self.reset_red_mixer, (self.button99, False))
		thread.start_new_thread(self.reset_green_mixer, (self.button100, False))
		thread.start_new_thread(self.reset_blue_mixer, (self.button101, False))
		self.mixer_levels = {'Red':[100, 0, 0], 'Green':[0, 100, 0], 'Blue':[0, 0, 100]}
                self.combobox13.set_active(0)
		if self.checkbutton26.get_active():
			grayscale = True
		else:
			grayscale = False
		self.history.append( ['recolor', self.matrix, grayscale] )
		self.image_was_changed = False
		self.checkbutton26.handler_block(self.id80)
		self.checkbutton26.set_active(False)
		self.checkbutton26.handler_unblock(self.id80)
		if self.expander8.get_expanded(): 
			self.draw_grid(False)
		gc.collect()

        def on_brightness_and_saturation_changed(self, obj, event):
		value7 = self.hscale7.get_adjustment().value
                value8 = self.hscale8.get_adjustment().value
                value18 = self.hscale18.get_adjustment().value
		if self.bright_sat == [value7, value8, value18] and event:
                        return False
		self.bright_sat = [value7, value8, value18]
                self.window2.window.set_cursor(self.watch)
		while gtk.events_pending():
                        gtk.main_iteration(False)
		format = self.set_filenames()
		self.wand.modulate(100 + value7, 100 + value8, 100 + value18)
		if not self.workflow_started:
                        self.original_pixbuf = self.pblist[self.pbindex].copy()
		self.show_image1()
		self.get_channel()
                self.window2.window.set_cursor(None)
		self.image_was_changed = True  
		self.workflow_started = True
		self.set_sensitivity(format)

        def color_balance(self, obj, event):
		adj9 = self.hscale9.get_adjustment()
		adj10 = self.hscale10.get_adjustment()
		adj11 = self.hscale11.get_adjustment()
		value9, value10, value11 = adj9.value, adj10.value, adj11.value
		if not event:
                        adj9.value, adj10.value, adj11.value = 0, 0, 0
			value9, value10, value11 = 0, 0, 0
		if self.c_balance == [value9, value10, value11] and event:
                        return False
		self.c_balance = [value9, value10, value11]
                self.window2.window.set_cursor(self.watch)
		while gtk.events_pending():
                        gtk.main_iteration(False)
		format = self.set_filenames()
		if value9 != 0:
                        self.wand.evaluate('Multiply', 1 + value9 / 100, api.RedChannel)
		if value10 != 0:
                        self.wand.evaluate('Multiply', 1 + value10 / 100, api.GreenChannel)
		if value11 != 0:
                        self.wand.evaluate('Multiply', 1 + value11 / 100, api.BlueChannel)
		if not self.workflow_started:
                        self.original_pixbuf = self.pblist[self.pbindex].copy()
		self.show_image1()
		self.get_channel()
                self.window2.window.set_cursor(None)
		self.button33.set_sensitive(True) 
		self.image_was_changed = True 
		self.workflow_started = True
		self.set_sensitivity(format)
		
	def on_contrast_changed(self, obj, event):
		adj12 = self.hscale12.get_adjustment()
		value12 = adj12.value
		if not event:
                        value12 = adj12.value = 0
		if self.contrast == value12 and event:
                        return False
		self.contrast = value12
		self.window2.window.set_cursor(self.watch)
		while gtk.events_pending():
                        gtk.main_iteration(False)
		format = self.set_filenames()
		self.wand.adjust_levels(value12, 1.0, Q_RANGE - value12 * Q_RANGE / 100)
		if not self.workflow_started:
                        self.original_pixbuf = self.pblist[self.pbindex].copy()
		self.show_image1()
		self.get_channel()
                self.window2.window.set_cursor(None)
		self.image_was_changed = True
		self.workflow_started = True
		self.set_sensitivity(format)

	def wand2pixbuf(self, wand):
                width, height = wand.size[0], wand.size[1]
                type_ = wand.get_type()
                if 'Matte' in type_:
                        map_ = "RGBA"
                else:
                        map_ = "RGB"
                array_ = numpy.empty(width * height * len(map_)).astype(int)   
                array_ = wand.get_pixels(0, 0, width, height, map_, array_)
                array_ = array_.reshape(height, width, len(map_))
                pil_img = Image.fromarray(array_, map_)
                IS_RGBA = pil_img.mode == 'RGBA'
                pixbuf = gtk.gdk.pixbuf_new_from_data(pil_img.tostring(), gtk.gdk.COLORSPACE_RGB, IS_RGBA,\
                                8, pil_img.size[0], pil_img.size[1], (IS_RGBA and 4 or 3) * pil_img.size[0])
		return pixbuf, float(width) / float(height)
		
	def scale_pixbuf(self, pixbuf, ratio):
		if ratio > 1:
                        return pixbuf.scale_simple(self.rect.width, int(self.rect.width / ratio), gtk.gdk.INTERP_BILINEAR)
                else:
                        return pixbuf.scale_simple(int(self.rect.height * ratio), self.rect.height, gtk.gdk.INTERP_BILINEAR)
		
	def on_midtones_contrast_changed(self, obj, event):
		adj13 = self.hscale13.get_adjustment()
		adj14 = self.hscale14.get_adjustment()
		value13, value14 = adj13.value, adj14.value
		if not event:
                        adj13.value, adj14.value = 0, 50
			value13, value14 =0, 50
		if self.mid_contrast==[value13, value14] and event:
                        return False
		self.mid_contrast = [value13, value14]
		self.window2.window.set_cursor(self.watch)
		while gtk.events_pending():
                        gtk.main_iteration(False)
		format = self.set_filenames()
		if value13 < 0: 
			sharpen = False
			value13 = abs(value13 - 1)
		else: 
			sharpen = True
			value13 = value13 + 1
		self.sigmoidal_contrast_args=(sharpen, value13, value14 * Q_RANGE / 100)
		self.wand.sigmoidal_contrast(*self.sigmoidal_contrast_args)
		if not self.workflow_started:
                        self.original_pixbuf = self.pblist[self.pbindex].copy()
		self.show_image1()
		self.get_channel()
                self.window2.window.set_cursor(None)
		self.image_was_changed = True
		self.workflow_started = True
		self.set_sensitivity(format)
		
	def save_levels(self):
		if self.RGB_levels['RGB'] == [0,1.0,100] and self.RGB_levels['Red'] == [0,1.0,100] and self.RGB_levels['Green'] == [0,1.0,100]\
		and self.RGB_levels['Blue'] == [0, 1.0, 100]:
			self.expander2.set_expanded(False)
			return True
		self.wand_index += 1
		if self.wand_index == len(self.wand_list):
                        self.wand_list += [ MagickImage(self.wand.get_image()) ]
                else:
                        self.wand_list[self.wand_index]=MagickImage(self.wand.get_image())
                        del self.wand_list[self.wand_index + 1:]
                        del self.history[self.wand_index - 1:]
                        self.size_history[self.wand_index:]=[self.size_history[self.wand_index] for i in xrange(self.wand_index,100)]
		self.set_toolbuttons_23_39_sensitivity()
		while gtk.events_pending():
                        gtk.main_iteration(False)
		thread.start_new_thread(self.reset_black_level, (self.button18, False))
		thread.start_new_thread(self.reset_white_level, (self.button19, False))
		thread.start_new_thread(self.reset_gamma, (self.button30, False))
		self.RGB_levels = {'RGB' : [0,1.0,100], 'Red' : [0, 1.0, 100], 'Green' : [0, 1.0, 100], 'Blue' : [0, 1.0, 100]}
                self.combobox6.set_active(0)
                channel_type={'RGB' : api.AllChannels, 'Red' : api.RedChannel, 'Green' : api.GreenChannel, 'Blue' : api.BlueChannel}
		for item in self.level_hist:
			self.history.append( ['adjust_levels',\
                        (item[1][0] * Q_RANGE / 100, item[1][1], item[1][2] * Q_RANGE / 100, channel_type[item[0]])] )
		self.level_hist = []
		self.image_was_changed = False
		if self.expander8.get_expanded():
                        self.draw_grid(False)
		gc.collect()
		   
	def save_brightness_and_saturation(self):
		if self.bright_sat == [0, 0, 0]:
			self.expander3.set_expanded(False)
			return True
		self.wand_index  +=  1
		if self.wand_index == len(self.wand_list):
                        self.wand_list += [ MagickImage(self.wand.get_image()) ]
                else:
                        self.wand_list[self.wand_index] = MagickImage(self.wand.get_image())
                        del self.wand_list[self.wand_index + 1:]
                        del self.history[self.wand_index - 1:]
                        self.size_history[self.wand_index:] = [self.size_history[self.wand_index] for i in xrange(self.wand_index, 100)]
                self.history.append( ['modulate', (100 + self.bright_sat[0], 100 + self.bright_sat[1], 100 + self.bright_sat[2])] )
		self.set_toolbuttons_23_39_sensitivity()
		while gtk.events_pending():
                        gtk.main_iteration(False)
		thread.start_new_thread(self.reset_brightness, (self.button32, False))
		thread.start_new_thread(self.reset_saturation, (self.button31, False))
		thread.start_new_thread(self.reset_hue, (self.button87, False))
		self.bright_sat = [0, 0, 0]
		self.image_was_changed = False
		if self.expander8.get_expanded():
                        self.draw_grid(False)
		gc.collect()
		
	def save_color_balance(self):              
		if self.c_balance == [0, 0, 0]:
			self.expander4.set_expanded(False)
			return True
		self.wand_index +=  1
		if self.wand_index == len(self.wand_list):
                        self.wand_list += [ MagickImage(self.wand.get_image()) ]
                else:
                        self.wand_list[self.wand_index] = MagickImage(self.wand.get_image())
                        del self.wand_list[self.wand_index + 1:]
                        del self.history[self.wand_index - 1:]
                        self.size_history[self.wand_index:] = [self.size_history[self.wand_index] for i in xrange(self.wand_index, 100)]
		self.history.append( [['evaluate', ('Multiply', 1 + self.c_balance[0] / 100, api.RedChannel)],\
		['evaluate', ('Multiply', 1 + self.c_balance[1] / 100, api.GreenChannel)],\
                ['evaluate', ('Multiply', 1 + self.c_balance[2] / 100, api.BlueChannel)]] )
		self.set_toolbuttons_23_39_sensitivity()
		while gtk.events_pending():
                        gtk.main_iteration(False)
		thread.start_new_thread(self.reset_color_balance, (self.button39, False))
		self.c_balance = [0, 0, 0]
		self.image_was_changed = False
		if self.expander8.get_expanded():
                        self.draw_grid(False)
		gc.collect()
		
	def save_contrast(self):
		if self.contrast == 0:
			self.expander5.set_expanded(False)
			return True
		self.wand_index += 1
		if self.wand_index == len(self.wand_list):
                        self.wand_list+=[ MagickImage(self.wand.get_image()) ]
                else:
                        self.wand_list[self.wand_index] = MagickImage(self.wand.get_image())
                        del self.wand_list[self.wand_index + 1:]
                        del self.history[self.wand_index - 1:]
                        self.size_history[self.wand_index:] = [self.size_history[self.wand_index] for i in xrange(self.wand_index, 100)]
		self.history.append(['adjust_levels', (self.contrast * Q_RANGE / 100, 1.0, Q_RANGE - self.contrast * Q_RANGE / 100)])
		self.set_toolbuttons_23_39_sensitivity()
		while gtk.events_pending():
                        gtk.main_iteration(False)
		thread.start_new_thread(self.reset_contrast, (self.button43, False))
		self.image_was_changed = False
		if self.expander8.get_expanded():
                        self.draw_grid(False)
		gc.collect()
		
	def save_midtones_contrast(self):
		adj13_value = self.hscale13.get_adjustment().value
		adj14_value = self.hscale14.get_adjustment().value
		if adj13_value == 0 and adj14_value == 50:
			self.expander6.set_expanded(False)
			return True
		self.wand_index += 1
		if self.wand_index == len(self.wand_list):
                        self.wand_list += [ MagickImage(self.wand.get_image()) ]
                else:
                        self.wand_list[self.wand_index] = MagickImage(self.wand.get_image())
                        del self.wand_list[self.wand_index + 1:]
                        del self.history[self.wand_index - 1:]
                        self.size_history[self.wand_index:] = [self.size_history[self.wand_index] for i in xrange(self.wand_index,100)]
		self.history.append( ['sigmoidal_contrast', self.sigmoidal_contrast_args] )
		self.set_toolbuttons_23_39_sensitivity()
		thread.start_new_thread(self.reset_midtones_contrast, (self.button46, False))
		self.image_was_changed = False
		if self.expander8.get_expanded():
                        self.draw_grid(False)
		gc.collect()

	def save_workflow(self, obj):
		expanded = False
                for item in self.expander_list:
                        if item.get_expanded():
                                expanded = True
                                break
                if expanded:
                        self.on_expander_activate(item, False, True)
		if self.history:
                	self.workflow_copy = self.history[:self.wand_index]
                	if not self.checkbutton22.get_active():
                                self.label135.set_text('The workflow was saved for next conversion!')
                        	self.dialog24.show()
                        	response = self.dialog24.run()
                        	if response == gtk.RESPONSE_CLOSE or response == gtk.RESPONSE_DELETE_EVENT:
                                        self.dialog24.hide()
		else:
                        self.label136.set_text('There is not a workflow to save.\nPlease, make a new one!')
			self.dialog25.show()
			gtk.gdk.beep()
                        response = self.dialog25.run()
                        if response == gtk.RESPONSE_CLOSE or response == gtk.RESPONSE_DELETE_EVENT:
                                self.dialog25.hide()

        def set_scale_size(self):
                if self.size_history[self.wand_index]:
                        size = self.size_history[self.wand_index]
                        size = [int(size[0]), int(size[1])]
                else:
                        size = self.image_size.split('x')
                        size = [int(size[0]), int(size[1])]
                self.entry11.set_text(str(size[0]))
                self.entry12.set_text(str(size[1]))
		self.spinbutton19.handler_block(self.id72)
                self.spinbutton23.handler_block(self.id73)
                self.spinbutton19.get_adjustment().upper = 99999
                self.spinbutton23.get_adjustment().upper = 99999
                self.spinbutton19.set_value(size[0])
                self.spinbutton23.set_value(size[1])
                self.spinbutton19.get_adjustment().upper = size[0]
                self.spinbutton23.get_adjustment().upper = size[1]
		self.spinbutton19.handler_unblock(self.id72)
                self.spinbutton23.handler_unblock(self.id73)
                self.ratio = float(size[0]) / float(size[1])
		
	def save_changes(self):
		if not self.image_was_changed:
                        return True
		for item in self.expander_list:
			if item.get_expanded():
				break
		if item == self.expander2:
			self.save_levels()
		elif item == self.expander3:
			self.save_brightness_and_saturation()
		elif item == self.expander4:
			self.save_color_balance()
		elif item == self.expander5:
			self.save_contrast()
		elif item == self.expander6:
			self.save_midtones_contrast()
		elif item == self.expander7:
			self.save_scale() 
		elif item == self.expander8:
			self.save_fine_rotation()     
		elif item == self.expander9:
			self.save_img_border()
		elif item == self.expander10:
			self.save_sharpen()  
		elif item == self.expander11:
			self.save_blur()
		elif item == self.expander12:
			self.save_add_noise()
		elif item == self.expander13:
			self.save_reduce_noise()
		elif item == self.expander14:
			self.save_median() 
		elif item == self.expander15:
			self.save_sepia_tone()
		elif item == self.expander16:
			self.save_grayscale()
		elif item == self.expander17:
			self.save_crop()
		elif item == self.expander18:
			self.save_unsharp_mask()
		elif item == self.expander20:
			self.save_mixer()
		elif item == self.expander21:
			self.save_normalize()

	def undo_workflow(self, obj):
                if self.workflow_started and self.wand_index > 0:
			self.window2.window.set_cursor(self.watch)
			while gtk.events_pending():
                                gtk.main_iteration(False)
			self.save_changes()
                        self.wand_index -= 1
                        image_copy = self.wand_list[self.wand_index].get_image()
                        self.wand = MagickImage(image_copy)
                        size = self.wand._get_size()
                        if size[0] <= self.rect.width and size[1] <= self.rect.height and not self.expander17.get_expanded():
                                self.pblist[self.pbindex] = self.wand2pixbuf(self.wand)[0]
                        else:
                                self.pblist[self.pbindex] = self.scale_pixbuf(*self.wand2pixbuf(self.wand))
			if self.expander17.get_expanded():
				width = self.pblist[self.pbindex].get_width()
				height = self.pblist[self.pbindex].get_height()
				self.drawable.draw_pixbuf(self.gc, self.pblist[self.pbindex], 0, 0,\
                                                          int((self.rect.width - width) / 2), int((self.rect.height - height) / 2))
				self.drawing_area.queue_draw()
				self.x, self.y = self.x1, self.y1
			else:
                		self.image1.set_from_pixbuf(self.pblist[self.pbindex])
				self.image1.show()
			if self.expander7.get_expanded():
                                self.set_scale_size()        
			self.set_sensitivity(os.path.splitext(self.list[self.indice])[1])
			self.set_toolbuttons_23_39_sensitivity()
			if self.expander17.get_expanded():
				self.set_zoom_sensitivity(False)
			if self.border_count > 0:
				self.border_count -=1
			if not self.border_count:
				self.button72.set_sensitive(False)
			if self.crop_count > 0:
				self.crop_count -=1
			if not self.crop_count:
				self.button93.set_sensitive(False)
			self.window2.window.set_cursor(None)

	def redo_workflow(self, obj):
                if self.workflow_started and self.wand_index < len(self.wand_list) - 1:
			self.window2.window.set_cursor(self.watch)
			while gtk.events_pending():
                                gtk.main_iteration(False)
			if self.image_was_changed:
				self.save_changes()
				self.window2.window.set_cursor(None)
				return True
                        self.wand_index += 1
                        image_copy = self.wand_list[self.wand_index].get_image()
                        self.wand = MagickImage(image_copy)
                        size = self.wand._get_size()
                        if size[0] <= self.rect.width and size[1] <= self.rect.height and not self.expander17.get_expanded():
                                self.pblist[self.pbindex] = self.wand2pixbuf(self.wand)[0]
                        else:
                                self.pblist[self.pbindex] = self.scale_pixbuf(*self.wand2pixbuf(self.wand))
			if self.expander17.get_expanded():
				width = self.pblist[self.pbindex].get_width()
				height = self.pblist[self.pbindex].get_height()
				self.drawable.draw_pixbuf(self.gc, self.pblist[self.pbindex], 0, 0,\
                                                          int((self.rect.width - width)/2), int((self.rect.height - height) / 2))
				self.drawing_area.queue_draw()
				self.x, self.y = self.x1, self.y1
			else:
                		self.image1.set_from_pixbuf(self.pblist[self.pbindex])
				self.image1.show()
			if self.expander7.get_expanded():
                                self.set_scale_size()	
			self.set_sensitivity(os.path.splitext(self.list[self.indice])[1])
			self.set_toolbuttons_23_39_sensitivity()
			if self.expander17.get_expanded():
				self.set_zoom_sensitivity(False)
			self.window2.window.set_cursor(None)
			
	def set_toolbuttons_23_39_sensitivity(self):
		index = self.wand_index
		length = len(self.wand_list) - 1
		if length in [-1, 0]:
			self.toolbutton23.set_sensitive(False)
			self.toolbutton39.set_sensitive(False)
		elif length == 1:
                        if self.wand_index == 0:
                                self.toolbutton23.set_sensitive(False)
                                self.toolbutton39.set_sensitive(True)
                        else:
                                self.toolbutton23.set_sensitive(True)
                                self.toolbutton39.set_sensitive(False)
		else:
			if 0 < index < length: 
				self.toolbutton23.set_sensitive(True)
				self.toolbutton39.set_sensitive(True)
			elif 0 <= index < length:
				self.toolbutton23.set_sensitive(False)
				self.toolbutton39.set_sensitive(True)
			elif 0 < index <= length:
				self.toolbutton23.set_sensitive(True)
				self.toolbutton39.set_sensitive(False)
		
	def on_expander_activate(self, obj, data, nothreads=None):
		if obj.get_expanded() and self.image_was_changed:
			if not data:
                                obj.set_expanded(data)
			if obj == self.expander2:
                                if nothreads:
                                        self.save_levels()
                                else:
                                        thread.start_new_thread(self.save_levels, ())
			elif obj == self.expander3:
                                if nothreads:
                                        self.save_brightness_and_saturation()
                                else:
                                        thread.start_new_thread(self.save_brightness_and_saturation, ())
			elif obj == self.expander4:
                                if nothreads:
                                        self.save_color_balance()
                                else:
                                        thread.start_new_thread(self.save_color_balance, ())
			elif obj == self.expander5:
                                if nothreads:
                                        self.save_contrast()
                                else:
                                        thread.start_new_thread(self.save_contrast, ())
			elif obj == self.expander6:
                                if nothreads:
                                        self.save_midtones_contrast()
                                else:
                                        thread.start_new_thread(self.save_midtones_contrast, ())
			elif obj == self.expander7:
                                if nothreads:
                                        self.save_scale()
                                else:
                                        thread.start_new_thread(self.save_scale, ()) 
			elif obj == self.expander8:
                                if nothreads:
                                        self.save_fine_rotation()
                                else:
                                        thread.start_new_thread(self.save_fine_rotation, ())  
				self.image1.set_from_pixbuf(self.pblist[self.pbindex])
				self.image1.show()     
			elif obj == self.expander9:
                                if nothreads:
                                        self.save_img_border()
                                else:
                                        thread.start_new_thread(self.save_img_border, ()) 
			elif obj == self.expander10:
                                if nothreads:
                                        self.save_sharpen()
                                else:
                                        thread.start_new_thread(self.save_sharpen, ())  
			elif obj == self.expander11:
                                if nothreads:
                                        self.save_blur()
                                else:
                                        thread.start_new_thread(self.save_blur, ())
			elif obj == self.expander12:
                                if nothreads:
                                        self.save_add_noise()
                                else:
                                        thread.start_new_thread(self.save_add_noise, ()) 
			elif obj == self.expander13:
                                if nothreads:
                                        self.save_reduce_noise()
                                else:
                                        thread.start_new_thread(self.save_reduce_noise, ())
			elif obj == self.expander14:
                                if nothreads:
                                        self.save_median()
                                else:
                                        thread.start_new_thread(self.save_median, ()) 
			elif obj == self.expander15:
                                if nothreads:
                                        self.save_sepia_tone()
                                else:
                                        thread.start_new_thread(self.save_sepia_tone, ())
			elif obj == self.expander16:
                                if nothreads:
                                        self.save_grayscale()
                                else:
                                        thread.start_new_thread(self.save_grayscale, ())
			elif obj == self.expander17:
				self.destroy_drawingarea()
                                self.image1.set_from_pixbuf(self.pblist[self.pbindex])
				self.image1.show()
				if nothreads:
                                        self.save_crop()
                                else:
                                        thread.start_new_thread(self.save_crop, ())
			elif obj == self.expander18:
                                if nothreads:
                                        self.save_unsharp_mask()
                                else:
                                        thread.start_new_thread(self.save_unsharp_mask, ())
			elif obj == self.expander20:
                                if nothreads:
                                        self.save_mixer()
                                else:
                                        thread.start_new_thread(self.save_mixer, ())
			elif obj == self.expander21:
                                if nothreads:
                                        self.save_normalize()
                                else:
                                        thread.start_new_thread(self.save_normalize, ())
		elif obj.get_expanded() and not self.image_was_changed:
                        if obj == self.expander17:
                                self.destroy_drawingarea()
				self.show_image1()
			elif obj == self.expander8:
				self.image1.set_from_pixbuf(self.pblist[self.pbindex])
				self.image1.show()
			self.crop_count = 0
			self.border_count = 0
		elif not obj.get_expanded():
			if obj == self.expander7:		
                                self.set_scale_size()
                        	self.button65.set_sensitive(False)
			elif obj == self.expander8:
				self.button54.set_sensitive(False)
                        	self.spinbutton27.set_value(0)
                        	self.spinbutton28.set_value(0.0)
                                self.draw_grid(True)
			elif obj == self.expander9:
                        	self.button72.set_sensitive(False)
			elif obj == self.expander10:
				self.button57.set_sensitive(False)
                        	self.button58.set_sensitive(True)
                        	self.spinbutton25.set_value(1.0)
                        	self.spinbutton29.set_value(0)
			elif obj == self.expander11:
				self.button68.set_sensitive(False)
                        	self.button70.set_sensitive(True)
                        	self.spinbutton32.set_value(0)
                        	self.spinbutton33.set_value(0)
			elif obj == self.expander12:
				self.button61.set_sensitive(False)
                        	self.button63.set_sensitive(True)
			elif obj == self.expander13:
				self.button74.set_sensitive(False)
                        	self.button75.set_sensitive(True)
                        	self.spinbutton34.set_value(0)
			elif obj == self.expander14:
				self.button80.set_sensitive(False)
                        	self.button81.set_sensitive(True)
                        	self.spinbutton36.set_value(0)
			elif obj == self.expander15:
				self.button83.set_sensitive(False)
                        	self.button84.set_sensitive(True)
                        	self.spinbutton31.set_value(80)
			elif obj == self.expander16:
				self.button89.set_sensitive(False)
                        	self.button90.set_sensitive(True)
                        elif obj == self.expander17:
				self.button93.set_sensitive(False)
                        	self.button97.set_sensitive(True)
                                self.make_drawingarea()
                        elif obj == self.expander18:
				self.button94.set_sensitive(False)
                        	self.button95.set_sensitive(True)
                        	self.reset_unsharp_mask()
			elif obj == self.expander21:
				self.button92.set_sensitive(False)
                        	self.button103.set_sensitive(True)
			for item in self.expander_list:
				if item.get_expanded() and item != obj:
					if self.image_was_changed: 
						self.on_expander_activate(item, False)
						if item == self.expander8 and self.checkbutton24.get_active():
                                                        self.image1.set_from_pixbuf(self.pblist[self.pbindex])
							self.image1.show()
					else: 
						item.set_expanded(False)
						if item == self.expander17:
							self.destroy_drawingarea()
                                			self.image1.set_from_pixbuf(self.pblist[self.pbindex])
							self.image1.show()
							if obj == self.expander8:
								self.draw_grid(False)
						elif item == self.expander8 and self.checkbutton24.get_active():
                                                        self.image1.set_from_pixbuf(self.pblist[self.pbindex])
							self.image1.show()

	def undo_handler(self, obj):
                gtk.gdk.threads_enter()
                self.window2.window.set_cursor(self.watch)
                while gtk.events_pending():
                        gtk.main_iteration(False)
                if obj == self.button65:
                        self.button65.set_sensitive(False)
                elif obj == self.button72:
                        self.button72.set_sensitive(False)
                        self.button69.set_sensitive(True)
                elif obj == self.button54:
                        self.button54.set_sensitive(False)
                        self.spinbutton27.set_value(0)
                        self.spinbutton28.set_value(0)
                        if not self.expander8.get_expanded():
                                self.image1.set_from_pixbuf(self.pblist[self.pbindex])
				self.image1.show()
                elif obj == self.button57:
                        self.button57.set_sensitive(False)
                        self.button58.set_sensitive(True)
                        self.spinbutton25.set_value(1)
                        self.spinbutton29.set_value(0)
                elif obj == self.button68:
                        self.button68.set_sensitive(False)
                        self.button70.set_sensitive(True)
                        self.spinbutton32.set_value(0)
                        self.spinbutton33.set_value(0)
                elif obj == self.button61:
                        self.button61.set_sensitive(False)
                        self.button63.set_sensitive(True)
                elif obj == self.button74:
                        self.button74.set_sensitive(False)
                        self.button75.set_sensitive(True)
                        self.spinbutton34.set_value(0)
                elif obj == self.button80:
                        self.button80.set_sensitive(False)
                        self.button81.set_sensitive(True)
                        self.spinbutton36.set_value(0)
                elif obj == self.button83:
                        self.button83.set_sensitive(False)
                        self.button84.set_sensitive(True)
                        self.spinbutton31.set_value(80)
                elif obj == self.button89:
                        self.button89.set_sensitive(False)
                        self.button90.set_sensitive(True)
                elif obj == self.button92:
                        self.button92.set_sensitive(False)
                        self.button103.set_sensitive(True)
                elif obj == self.button93:
                        self.button93.set_sensitive(False)
                        self.button97.set_sensitive(True)
                        if not self.expander17.get_expanded():
                        	self.destroy_drawingarea()
                elif obj == self.button94:
                        self.button94.set_sensitive(False)
                        self.button95.set_sensitive(True)
                        self.reset_unsharp_mask()
                self.wand = MagickImage(self.wand_list[self.wand_index].get_image())
		width, height = self.wand.size
		if width > self.rect.width or height > self.rect.height:
			self.pblist[self.pbindex] = self.scale_pixbuf(*self.wand2pixbuf(self.wand))
		else:
			self.pblist[self.pbindex] = self.wand2pixbuf(self.wand)[0]
		if self.expander17.get_expanded():
			width = self.pblist[self.pbindex].get_width()
			height = self.pblist[self.pbindex].get_height()
			self.drawable.draw_pixbuf(self.gc, self.pblist[self.pbindex], 0, 0,\
                                                  int((self.rect.width - width)/2), int((self.rect.height - height) / 2))
			self.drawing_area.queue_draw()
			self.x, self.y = self.x1, self.y1
		elif self.expander8.get_expanded():
			self.draw_grid(False)
		else:
                	self.image1.set_from_pixbuf(self.pblist[self.pbindex])
			self.image1.show()
                while gtk.events_pending():
                        gtk.main_iteration(False)
                self.get_channel()
		self.image_was_changed = False
		self.window2.window.set_cursor(None)
		gtk.gdk.threads_leave()

	def block_viewport1_signals(self):
                self.viewport1.handler_block(self.viewport1_id1)
                self.viewport1.handler_block(self.viewport1_id2)
                self.viewport1.handler_block(self.viewport1_id3)

        def unblock_viewport1_signals(self):
                self.viewport1.handler_unblock(self.viewport1_id1)
                self.viewport1.handler_unblock(self.viewport1_id2)
                self.viewport1.handler_unblock(self.viewport1_id3)

        def set_zoom_sensitivity(self, data):
                self.toolbutton6.set_sensitive(data)
                self.toolbutton7.set_sensitive(data)
                self.toolbutton8.set_sensitive(data)
                self.toolbutton9.set_sensitive(data)
                self.toolbutton10.set_sensitive(data)
                self.toolbutton11.set_sensitive(data)
		self.toolbutton12.set_sensitive(data)
		self.toolbutton13.set_sensitive(data)
		self.button53.set_sensitive(data)
		self.button56.set_sensitive(data)
		self.button59.set_sensitive(data)
		self.button62.set_sensitive(data)
                if data:
                        self.hpaned2.handler_unblock(self.id22)
		else:
                        self.hpaned2.handler_block(self.id22)

        def draw_grid(self, data):
                if self.checkbutton24.get_active():
                        self.block_viewport1_signals()
                        pixmap, mask = self.pblist[self.pbindex].render_pixmap_and_mask()
                        color = pixmap.get_colormap().alloc_color('red')
                        gc = pixmap.new_gc(foreground = color)
                        width, height = pixmap.get_size()
                        for x in xrange(0, width, 30):
                                pixmap.draw_line(gc, x, 0, x, height)
                        for y in xrange(0, height, 30):
                                pixmap.draw_line(gc, 0, y, width, y)
                        self.image1.set_from_pixmap(pixmap, mask)
		else:
			self.image1.set_from_pixbuf(self.pblist[self.pbindex])
                self.image1.show()
	
        def make_drawingarea(self):
                self.set_zoom_sensitivity(False)
                self.block_viewport1_signals()
                self.zoom_fit_photo(None, False)
                self.image1.destroy()
                self.drawing_area = gtk.DrawingArea()
                self.viewport1.add(self.drawing_area)
		self.drawing_area.modify_bg(gtk.STATE_NORMAL, self.image_background_color)
                self.drawing_area.add_events(gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON1_MOTION_MASK | gtk.gdk.POINTER_MOTION_HINT_MASK)
                self.drawing_area.connect('expose_event', self.on_drawing_area_expose_event, False)
                self.drawing_area.connect('size_allocate', self.on_drawing_area_size_allocate)
                self.drawing_area.connect('button_press_event', self.on_drawing_area_button_press_event)
		self.combobox12_id = self.combobox12.connect('changed', self.on_drawing_area_expose_event, self.drawing_area,True)	
                self.drawing_area.show()

        def on_drawing_area_size_allocate(self, obj, allocation):
		self.rect = self.viewport1.allocation
		width = self.pblist[self.pbindex].get_width()
                height = self.pblist[self.pbindex].get_height()
		self.x_offset, self.y_offset = (self.rect.width - width) / 2, (self.rect.height - height) / 2
		self.drawing_area.set_size_request(width, height)
		if self._id and self.drawing_area.handler_is_connected(self._id):
                        self.drawing_area.disconnect(self._id)
		self._id = self.drawing_area.connect('motion_notify_event', self.on_drawing_area_motion_notify_event,\
		(self.rect.width - width) / 2 + 1,self.rect.width - (self.rect.width - width) / 2 - 1,(self.rect.height - height) / 2 + 1,\
		self.rect.height - (self.rect.height - height) / 2 - 1)

        def on_drawing_area_expose_event(self, obj, event, data):
                width = self.pblist[self.pbindex].get_width()
                height = self.pblist[self.pbindex].get_height()
                self.drawable = self.drawing_area.window
                self._color = self.drawable.get_colormap().alloc_color(self.colorbutton7.get_color())
                self.gc = self.drawable.new_gc(foreground=self._color,line_style=gtk.gdk.LINE_SOLID)
		self.drawing_area.set_size_request(width, height)
                self.drawable.draw_pixbuf(self.gc, self.pblist[self.pbindex], 0, 0,int((self.rect.width - width) / 2),\
										int((self.rect.height - height) / 2))
                if data:
                        self.draw_rectangle_with_ratio()
                self.drawing_area.show()

        def draw_rectangle_with_ratio(self):
                width = self.pblist[self.pbindex].get_width()
                height = self.pblist[self.pbindex].get_height()
		if not self.checkbutton21.get_active():
                	ratio = self.combobox12.get_active()
                	if ratio == 0:
				self.crop_ratio = 1
                        	h = w = min(width / 2, height / 2)
                	elif ratio == 1:
				self.crop_ratio = 3 / 2.0
                        	w = min(width / 2, height / 2)
                        	h = w / self.crop_ratio
                	elif ratio == 2:
				self.crop_ratio = 2 / 3.0
                        	h = min(width / 2, height / 2)
                        	w = h * self.crop_ratio
                	elif ratio == 3:
				self.crop_ratio = 4 / 3.0
                        	w = min(width / 2, height / 2)
                        	h = w / self.crop_ratio
                	elif ratio == 4:
				self.crop_ratio = 3 / 4.0
                        	h = min(width / 2, height / 2)
                        	w = h * self.crop_ratio
                	elif ratio == 5:
				self.crop_ratio = 5 / 4.0
                        	w = min(width / 2, height / 2)
                        	h = w / self.crop_ratio	
                	elif ratio == 6:
				self.crop_ratio = 4 / 5.0
                        	h = min(width / 2, height / 2)
                        	w = h * self.crop_ratio
                        elif ratio == 7:
				self.crop_ratio = 7 / 5.0
                        	w = min(width / 2, height / 2)
                        	h = w / self.crop_ratio	
                	elif ratio == 8:
				self.crop_ratio = 5 / 7.0
                        	h = min(width / 2, height / 2)
                        	w = h * self.crop_ratio
                        elif ratio == 9:
				self.crop_ratio = 3 / 1.0
                        	w = min(width / 2, height / 2)
                        	h = w / self.crop_ratio	
                	elif ratio == 10:
				self.crop_ratio = 1 / 3.0
                        	h = min(width / 2, height / 2)
                        	w = h * self.crop_ratio
                	elif ratio == 11:
				self.crop_ratio = 0
                        	w = width / 2
                        	h = height / 2
		else:
			self.crop_ratio = self.spinbutton30.get_value() / self.spinbutton38.get_value()
			if self.crop_ratio > 1:
				w = min(width / 2, height / 2)
                        	h = w / self.crop_ratio
			else:
				h = min(width / 2, height / 2)
                        	w = h * self.crop_ratio
                self.x,  self.y = int(self.rect.width / 2 - w / 2), int(self.rect.height / 2 - h / 2)
                self.x1, self.y1 = self.x + int(w), self.y + int(h) 
                self.drawable.draw_rectangle(self.gc, False, self.x, self.y, int(w), int(h))
                
        def on_drawing_area_button_press_event(self, obj, event):
                if event.button == 1:
                        width = self.pblist[self.pbindex].get_width()
                        height = self.pblist[self.pbindex].get_height()
			self.rect = self.viewport1.allocation
			x0, x1, y0, y1 = (self.rect.width - width) / 2 + 1,self.rect.width - (self.rect.width - width) / 2 - 1,\
			(self.rect.height - height) / 2 + 1, self.rect.height - (self.rect.height - height) / 2 - 1
                        self.x, self.y = self.x1, self.y1 = event.x, event.y
			self.drawable.draw_pixbuf(self.gc, self.pblist[self.pbindex], 0, 0, int(x0), int(y0))
			if x0 < self.x < x1 and y0 < self.y < y1 :
                                self.drawable.draw_line(self.gc, int(x0), int(event.y), int(x1), int(event.y))
                                self.drawable.draw_line(self.gc, int(event.x), int(y0), int(event.x), int(y1))
                        			
        def on_drawing_area_motion_notify_event(self, obj, event, x0, x1, y0, y1):
                width = self.pblist[self.pbindex].get_width()
                height = self.pblist[self.pbindex].get_height()
		if x0 < self.x < x1 and y0 < self.y < y1 and x0 < event.x < x1 and y0 < event.y < y1:
			if event.x > self.x and event.y > self.y:
				if self.crop_ratio:
					if (event.x - self.x) / (event.y - self.y) > self.crop_ratio:
						event.x = self.crop_ratio * (event.y - self.y) + self.x
					else:
                                                event.y = (1 / self.crop_ratio) * (event.x - self.x) + self.y
				self.drawable.draw_pixbuf(self.gc, self.pblist[self.pbindex], 0, 0,\
                                                          int((self.rect.width - width)/2), int((self.rect.height - height) / 2))
                		self.drawable.draw_rectangle(self.gc, False, int(self.x), int(self.y), int(event.x - self.x), int(event.y - self.y))
                		self.drawing_area.show()
                		self.x1, self.y1 = event.x, event.y

        def destroy_drawingarea(self):
                self.drawing_area.destroy()
                self.image1 = gtk.Image()
                self.viewport1.add(self.image1)
                self.unblock_viewport1_signals()
                self.viewport1.modify_bg(gtk.STATE_NORMAL, self.image_background_color)
                self.set_zoom_sensitivity(True)
                self.set_sensitivity(os.path.splitext(self.list[self.indice])[1])
                self.combobox12.disconnect(self.combobox12_id)
                
        def scale(self, obj):
		self.window2.window.set_cursor(self.watch)
                while gtk.events_pending():
                        gtk.main_iteration(False)
                width = self.spinbutton19.get_value()
                height = self.spinbutton23.get_value()
                if int(self.entry11.get_text()) == width and int(self.entry12.get_text()) == height:
                        pass
                else:
			format = self.set_filenames()
                        if width > self.pblist[self.pbindex].get_width() and height > self.pblist[self.pbindex].get_height():
                                        time.sleep(1) 
					self.image_was_changed = True
                        		self.workflow_started = True
                        		self.set_sensitivity(format)
                        		self.button65.set_sensitive(True)
					self.window2.window.set_cursor(None)
					return True 
			self.scale_args = long(width), long(height)
                        if self.checkbutton25.get_active():
                                self.wand.thumbnail(*self.scale_args)
                        else:
                                self.wand.scale(*self.scale_args)
			if not self.workflow_started:
                                self.original_pixbuf = self.pblist[self.pbindex].copy()
			self.show_image1()
                        self.get_channel()
		        self.image_was_changed = True
                        self.workflow_started = True
                        self.set_sensitivity(format)
                        self.button65.set_sensitive(True)
                self.window2.window.set_cursor(None)

        def save_scale(self):
                gtk.gdk.threads_enter()
                self.button65.set_sensitive(False)
                self.image_was_changed = False
                self.wand_index += 1
		if self.wand_index == len(self.wand_list):
                        self.wand_list += [ MagickImage(self.wand.get_image()) ]
                else:
                        self.wand_list[self.wand_index]=MagickImage(self.wand.get_image())
                        del self.wand_list[self.wand_index + 1:]
                        del self.history[self.wand_index - 1:]
                        self.size_history[self.wand_index:] = [self.size_history[self.wand_index] for i in xrange(self.wand_index, 100)]
		self.set_toolbuttons_23_39_sensitivity()
		if self.checkbutton25.get_active():
                        self.history.append( ['thumbnail', self.scale_args] )
                else:
                        self.history.append( ['scale', self.scale_args] )
		if self.expander8.get_expanded():
                        self.draw_grid(False)
		self.magick_size = [str(self.scale_args[0]), str(self.scale_args[1])]
		self.entry11.set_text(self.magick_size[0])
                self.entry12.set_text(self.magick_size[1])
                self.spinbutton19.get_adjustment().upper = int(self.magick_size[0])
                self.spinbutton23.get_adjustment().upper = int(self.magick_size[1])
                self.size_history[self.wand_index:] = [self.scale_args for i in xrange(self.wand_index,100)]
                gc.collect()
                gtk.gdk.threads_leave()
                        
	def transform(self, obj, data):
                self.window2.window.set_cursor(self.watch)
		while gtk.events_pending():
                        gtk.main_iteration(False)
		format = self.set_filenames()
		if data == 'flip':
			self.wand.flip()
			self.history += [[ 'flip',() ]]
                elif data == 'flop':
			self.wand.flop()
			self.history += [[ 'flop',() ]]
                elif data == 'rotate 90':
			self.wand.rotate(90.0, None)
			self.history += [[ 'rotate', (90.0, None) ]]
                elif data == 'rotate -90':
			self.wand.rotate(-90.0, None)
			self.history += [[ 'rotate', (-90.0, None) ]]
		self.wand_index += 1
                if self.wand_index == len(self.wand_list):
                        self.wand_list+= [MagickImage(self.wand.get_image()) ]
                else:
                        self.wand_list[self.wand_index] = MagickImage(self.wand.get_image())
                        del self.wand_list[self.wand_index + 1:]
                        del self.history[self.wand_index - 1:]
                        self.size_history[self.wand_index:] = [self.size_history[self.wand_index] for i in xrange(self.wand_index,100)]
		self.set_toolbuttons_23_39_sensitivity()
		if not self.workflow_started:
                        self.original_pixbuf = self.pblist[self.pbindex].copy()
		self.show_image1()
		self.get_channel()
		self.workflow_started = True
		self.set_sensitivity(format)
		self.window2.window.set_cursor(None)
                        
	def apply_img_border(self, obj):
                self.window2.window.set_cursor(self.watch)
                while gtk.events_pending():
                        gtk.main_iteration(False)
		format = self.set_filenames()
		color = self.colorbutton6.get_color()
		self.bordercolor = 'rgb(' + str(color.red * 255 / Q_RANGE) + ',' + str(color.green * 255 / Q_RANGE) + ',' + str(color.blue * 255 / Q_RANGE)+')'
                self.IM_border_args = (self.bordercolor, long(self.spinbutton24.get_value()), long(self.spinbutton26.get_value()))
		self.wand.border(Color(self.bordercolor), *self.IM_border_args[1:])
		if not self.workflow_started:
                        self.original_pixbuf = self.pblist[self.pbindex].copy()
		self.show_image1()
		self.get_channel()
		self.image_was_changed = True
		self.workflow_started = True
		self.set_sensitivity(format)
		self.button72.set_sensitive(True)
                self.save_img_border()
                self.border_count +=1
		self.window2.window.set_cursor(None)

	def save_img_border(self, obj=None):
                gtk.gdk.threads_enter()
		self.button69.set_sensitive(True)
                self.wand_index += 1
                if self.wand_index == len(self.wand_list):
                        self.wand_list += [ MagickImage(self.wand.get_image()) ]
                else:
                        self.wand_list[self.wand_index] = MagickImage(self.wand.get_image())
                        del self.wand_list[self.wand_index + 1:]
                        del self.history[self.wand_index - 1:]
                        self.size_history[self.wand_index:] = [self.size_history[self.wand_index] for i in xrange(self.wand_index,100)]
		self.set_toolbuttons_23_39_sensitivity()
                self.image_was_changed = False
                self.history.append( ['border', self.IM_border_args] )
		if self.expander8.get_expanded():
                        self.draw_grid(False)
		gc.collect()
                gtk.gdk.threads_leave()

        def fine_rotation(self, obj, event):
                self.window2.window.set_cursor(self.watch)
                while gtk.events_pending():
                        gtk.main_iteration(False)
                format = self.set_filenames()
                self.fine_degree = self.spinbutton27.get_value() + self.spinbutton28.get_value()
		self.wand.rotate(self.fine_degree, None)
		if not self.workflow_started:
                        self.original_pixbuf = self.pblist[self.pbindex].copy()
		self.show_image1()
		self.get_channel()
		self.image_was_changed = True
		self.workflow_started = True
		self.set_sensitivity(format)
		self.button54.set_sensitive(True)
		self.window2.window.set_cursor(None)

	def save_fine_rotation(self):
                gtk.gdk.threads_enter()
                self.button54.set_sensitive(False)
		self.spinbutton27.set_value(0)
		self.spinbutton28.set_value(0)
                self.wand_index += 1
                if self.wand_index == len(self.wand_list):
                        self.wand_list += [ MagickImage(self.wand.get_image()) ]
                else:
                        self.wand_list[self.wand_index] = MagickImage(self.wand.get_image())
                        del self.wand_list[self.wand_index + 1:]
                        del self.history[self.wand_index - 1:]
                        self.size_history[self.wand_index:]=[self.size_history[self.wand_index] for i in xrange(self.wand_index,100)]
		self.set_toolbuttons_23_39_sensitivity()
                self.image_was_changed = False
                self.history.append( ['rotate', (self.fine_degree, None)] )
                gc.collect()
                gtk.gdk.threads_leave()

        def apply_crop(self,obj):
                if (self.x, self.y) == (self.x1, self.y1):
                        self.label136.set_text('You must select a rectangle first!')
                        self.dialog25.show()
			gtk.gdk.beep()
			response = self.dialog25.run()
			if response == gtk.RESPONSE_CLOSE or response == gtk.RESPONSE_DELETE_EVENT:
                                self.dialog25.hide()
                        return True
                self.window2.window.set_cursor(self.watch)
                while gtk.events_pending():
                        gtk.main_iteration(False)
                format = self.set_filenames()
		i_size = self.wand._get_size()
		width = float(self.x1 - self.x) / self.pblist[self.pbindex].get_width()
		height = float(self.y1 - self.y) / self.pblist[self.pbindex].get_height()
		w_offset = float(self.x - self.x_offset) / self.pblist[self.pbindex].get_width()
		h_offset = float(self.y - self.y_offset) / self.pblist[self.pbindex].get_height()
		w = width * i_size[0]
		h = height * i_size[1]
		x_offset = w_offset * i_size[0]
		y_offset = h_offset * i_size[1]
		crop_args = (long(w), long(h)), (long(x_offset), long(y_offset))
		repage_args = (long(w), long(h)), (0, 0)
		self.crop_args = (width, height), (w_offset, h_offset)
		self.repage_args = (width, height), (0, 0)
		self.wand.crop(*crop_args)
		self.wand.set_page(*repage_args)
		if not self.workflow_started:
                        self.original_pixbuf = self.pblist[self.pbindex].copy()
		rect = self.viewport1.allocation
		self.pblist[self.pbindex] = self.scale_pixbuf(*self.wand2pixbuf(self.wand))
                self.drawing_area.queue_draw()
                self.on_drawing_area_size_allocate(self.drawing_area, rect)
                while gtk.events_pending():
                        gtk.main_iteration(False)
		self.get_channel()
		self.image_was_changed = True
		self.workflow_started = True
		self.button93.set_sensitive(True)
                self.save_crop()
                self.crop_count += 1
		self.window2.window.set_cursor(None)
		
        def save_crop(self, obj=None):
                gtk.gdk.threads_enter()
		self.button97.set_sensitive(True)
                self.wand_index += 1
                if self.wand_index == len(self.wand_list):
                        self.wand_list += [ MagickImage(self.wand.get_image()) ]
                else:
                        self.wand_list[self.wand_index] = MagickImage(self.wand.get_image())
                        del self.wand_list[self.wand_index + 1:]
                        del self.history[self.wand_index - 1:]
                        self.size_history[self.wand_index:] = [self.size_history[self.wand_index] for i in xrange(self.wand_index,100)]
                size = self.size_history[self.wand_index]
		if not size:
			size = self.image_size.split('x')
                        size = [int(size[0]), int(size[1])]
                crop_size=[int(self.crop_args[0][0] * size[0]), int(self.crop_args[0][1] * size[1])]
                self.size_history[self.wand_index:] = [ crop_size for i in xrange(self.wand_index, 100)]
		self.set_toolbuttons_23_39_sensitivity()
                self.image_was_changed = False
		self.history.append([['_get_size', None], ['crop', self.crop_args], ['set_page', self.repage_args]])
		self.x, self.y = self.x1, self.y1
		gc.collect()
                gtk.gdk.threads_leave()
		
	def apply_effect(self, fun, args):
		fun(self.wand, *args)
		self.stop_progressbar2.set()

        def apply_sharpen(self, obj):
                self.window2.window.set_cursor(self.watch)
		self.progressbar2.set_text('Sharpening...')
		self.window5.show()
                while gtk.events_pending():
                        gtk.main_iteration(False)
                format = self.set_filenames()
                sigma = self.hscale16.get_adjustment().value
                radius = float(self.hscale17.get_adjustment().value)
		fun = MagickImage.sharpen
		self.sharpen_args = (radius, sigma, None)
                thread.start_new_thread(self.apply_effect, (fun, self.sharpen_args))
		self.pulse_progressbar2()
		if not self.workflow_started:
                        self.original_pixbuf = self.pblist[self.pbindex].copy()
		self.show_image1()
		self.get_channel()
		self.image_was_changed = True
		self.workflow_started = True
		self.set_sensitivity(format)
		self.button57.set_sensitive(True)
		self.window2.window.set_cursor(None)
		self.window5.hide()
		self.progressbar2.set_fraction(0)

	def save_sharpen(self):
                gtk.gdk.threads_enter()
                self.button57.set_sensitive(False)
                self.wand_index += 1
                if self.wand_index == len(self.wand_list):
                        self.wand_list += [ MagickImage(self.wand.get_image() )]
                else:
                        self.wand_list[self.wand_index] = MagickImage(self.wand.get_image())
                        del self.wand_list[self.wand_index + 1:]
                        del self.history[self.wand_index - 1:]
                        self.size_history[self.wand_index:] = [self.size_history[self.wand_index] for i in xrange(self.wand_index,100)]
		self.set_toolbuttons_23_39_sensitivity()
                self.image_was_changed = False
                self.history.append(['sharpen', self.sharpen_args])
		if self.expander8.get_expanded():
                        self.draw_grid(False)
		gc.collect()
                gtk.gdk.threads_leave()

        def apply_unsharp_mask(self, obj):
                self.window2.window.set_cursor(self.watch)
		self.progressbar2.set_text('Unsharp Mask...')
		self.window5.show()
                while gtk.events_pending():
                        gtk.main_iteration(False)
                format = self.set_filenames()
                sigma = self.hscale27.get_adjustment().value
                radius = float(self.hscale26.get_adjustment().value)
                amount = self.hscale29.get_adjustment().value
                threshold = self.hscale30.get_adjustment().value
		fun = MagickImage.unsharp_mask
		self.unsharp_args=(radius, sigma, amount, threshold)
                thread.start_new_thread(self.apply_effect, (fun, self.unsharp_args))
		self.pulse_progressbar2()
		if not self.workflow_started:
                        self.original_pixbuf = self.pblist[self.pbindex].copy()
		self.show_image1()
		self.get_channel()
		self.image_was_changed = True
		self.workflow_started = True
		self.set_sensitivity(format)
		self.button94.set_sensitive(True)
		self.window2.window.set_cursor(None)
		self.window5.hide()
		self.progressbar2.set_fraction(0)

        def save_unsharp_mask(self):
                gtk.gdk.threads_enter()
                self.button94.set_sensitive(False)
                self.wand_index += 1
                if self.wand_index == len(self.wand_list):
                        self.wand_list += [ MagickImage(self.wand.get_image()) ]
                else:
                        self.wand_list[self.wand_index] = MagickImage(self.wand.get_image())
                        del self.wand_list[self.wand_index + 1:]
                        del self.history[self.wand_index - 1:]
                        self.size_history[self.wand_index:] = [self.size_history[self.wand_index] for i in xrange(self.wand_index,100)]
		self.set_toolbuttons_23_39_sensitivity()
                self.image_was_changed = False
                self.history.append( ['unsharp_mask', self.unsharp_args] )
		if self.expander8.get_expanded():
                        self.draw_grid(False)
		gc.collect()
                gtk.gdk.threads_leave()
	
	def apply_blur(self, obj):
		self.window2.window.set_cursor(self.watch)
		self.progressbar2.set_text('Blurring...')
		self.window5.show()
                while gtk.events_pending():
                        gtk.main_iteration(False)
                format = self.set_filenames()
                sigma = self.hscale20.get_adjustment().value
                radius = self.hscale21.get_adjustment().value
                mode = self.combobox8.get_active()
                if mode == 0:
                        operator = None
		else:
                        operator = True
		fun = MagickImage.blur
		self.blur_args=(radius, sigma, operator)
		thread.start_new_thread(self.apply_effect, (fun, self.blur_args))
		self.pulse_progressbar2()
		if not self.workflow_started:
                        self.original_pixbuf = self.pblist[self.pbindex].copy()
		self.show_image1()
		self.get_channel()
		self.image_was_changed = True
		self.workflow_started = True
		self.set_sensitivity(format)
		self.button68.set_sensitive(True)
		self.window2.window.set_cursor(None)
		self.window5.hide()
		self.progressbar2.set_fraction(0)
		
	def save_blur(self):
                gtk.gdk.threads_enter()
                self.button68.set_sensitive(False)
                self.wand_index += 1
                if self.wand_index == len(self.wand_list):
                        self.wand_list += [ MagickImage(self.wand.get_image()) ]
                else:
                        self.wand_list[self.wand_index] = MagickImage(self.wand.get_image())
                        del self.wand_list[self.wand_index + 1:]
                        del self.history[self.wand_index - 1:]
                        self.size_history[self.wand_index:] = [self.size_history[self.wand_index] for i in xrange(self.wand_index,100)]
		self.set_toolbuttons_23_39_sensitivity()
                self.image_was_changed = False
                self.history.append( ['blur', self.blur_args] )
		if self.expander8.get_expanded():
                        self.draw_grid(False)
		gc.collect()
                gtk.gdk.threads_leave()
		
	def apply_noise(self, obj):
		self.window2.window.set_cursor(self.watch)
		self.progressbar2.set_text('Noising...')
		self.window5.show()
                while gtk.events_pending():
                        gtk.main_iteration(False)
                format = self.set_filenames()
                noise_type = self.combobox11.get_active() + 1
		fun = MagickImage.add_noise
		self.add_noise_args = (noise_type,)
		thread.start_new_thread(self.apply_effect, (fun, self.add_noise_args))
		self.pulse_progressbar2()
		if not self.workflow_started:
                        self.original_pixbuf = self.pblist[self.pbindex].copy()
		self.show_image1()
		self.get_channel()
		self.image_was_changed = True
		self.workflow_started = True
		self.set_sensitivity(format)
		self.button61.set_sensitive(True)
		self.window2.window.set_cursor(None)
		self.window5.hide()
		self.progressbar2.set_fraction(0)
		
	def save_add_noise(self):
		gtk.gdk.threads_enter()
                self.button61.set_sensitive(False)
                self.wand_index += 1
                if self.wand_index == len(self.wand_list):
                        self.wand_list += [ MagickImage(self.wand.get_image()) ]
                else:
                        self.wand_list[self.wand_index] = MagickImage(self.wand.get_image())
                        del self.wand_list[self.wand_index + 1:]
                        del self.history[self.wand_index - 1:]
                        self.size_history[self.wand_index:] = [self.size_history[self.wand_index] for i in xrange(self.wand_index,100)]
		self.set_toolbuttons_23_39_sensitivity()
                self.image_was_changed = False
                self.history.append( ['add_noise', self.add_noise_args] )
		if self.expander8.get_expanded():
                        self.draw_grid(False)
		gc.collect()
                gtk.gdk.threads_leave()
	
	def apply_reduce_noise(self, obj):
		self.window2.window.set_cursor(self.watch)
		self.progressbar2.set_text('Denoising...')
		self.window5.show()
                while gtk.events_pending():
                        gtk.main_iteration(False)
                format = self.set_filenames()
                radius = self.hscale22.get_adjustment().value
		fun = MagickImage.reduce_noise
		self.reduce_noise_args = (radius,)
		thread.start_new_thread(self.apply_effect, (fun, self.reduce_noise_args))
		self.pulse_progressbar2()
		if not self.workflow_started:
                        self.original_pixbuf = self.pblist[self.pbindex].copy()
		self.show_image1()
		self.get_channel()
		self.image_was_changed = True
		self.workflow_started = True
		self.set_sensitivity(format)
		self.button74.set_sensitive(True)
		self.window2.window.set_cursor(None)
		self.window5.hide()
		self.progressbar2.set_fraction(0)
		
	def save_reduce_noise(self):
		gtk.gdk.threads_enter()
                self.button74.set_sensitive(False)
                self.wand_index += 1
                if self.wand_index == len(self.wand_list):
                        self.wand_list += [ MagickImage(self.wand.get_image()) ]
                else:
                        self.wand_list[self.wand_index]=MagickImage(self.wand.get_image())
                        del self.wand_list[self.wand_index + 1:]
                        del self.history[self.wand_index - 1:]
                        self.size_history[self.wand_index:] = [self.size_history[self.wand_index] for i in xrange(self.wand_index,100)]
		self.set_toolbuttons_23_39_sensitivity()
                self.image_was_changed = False
                self.history.append( ['reduce_noise', self.reduce_noise_args] )
		if self.expander8.get_expanded():
                        self.draw_grid(False)
		gc.collect()
                gtk.gdk.threads_leave()
	
	def apply_median_filter(self, obj):
		self.window2.window.set_cursor(self.watch)
		self.progressbar2.set_text('Median Filter...')
		self.window5.show()
                while gtk.events_pending():
                        gtk.main_iteration(False)
                format = self.set_filenames()
                radius = self.hscale24.get_adjustment().value
		fun = MagickImage.median_filter
		self.median_args = (radius,)
		thread.start_new_thread(self.apply_effect, (fun, self.median_args))
		self.pulse_progressbar2()
		if not self.workflow_started:
                        self.original_pixbuf = self.pblist[self.pbindex].copy()
		self.show_image1()
		self.get_channel()
		self.image_was_changed = True
		self.workflow_started = True
		self.set_sensitivity(format)
		self.button80.set_sensitive(True)
		self.window2.window.set_cursor(None)
		self.window5.hide()
		self.progressbar2.set_fraction(0)
	
	def save_median(self):
		gtk.gdk.threads_enter()
                self.button80.set_sensitive(False)
                self.wand_index += 1
                if self.wand_index == len(self.wand_list):
                        self.wand_list += [ MagickImage(self.wand.get_image()) ]
                else:
                        self.wand_list[self.wand_index] = MagickImage(self.wand.get_image())
                        del self.wand_list[self.wand_index + 1:]
                        del self.history[self.wand_index - 1:]
                        self.size_history[self.wand_index:] = [self.size_history[self.wand_index] for i in xrange(self.wand_index,100)]
		self.set_toolbuttons_23_39_sensitivity()
                self.image_was_changed = False
                self.history.append( ['median_filter', self.median_args] )
		if self.expander8.get_expanded():
                        self.draw_grid(False)
		gc.collect()
                gtk.gdk.threads_leave()
			
	def apply_sepia_tone(self, obj):
		self.window2.window.set_cursor(self.watch)
		self.progressbar2.set_text('Sepia Tone...')
		self.window5.show()
                while gtk.events_pending():
                        gtk.main_iteration(False)
                format = self.set_filenames()
                threshold = self.hscale19.get_adjustment().value * Q_RANGE / 100
		fun = MagickImage.sepia_tone
		self.sepia_tone_args = (threshold,)
		thread.start_new_thread(self.apply_effect, (fun, self.sepia_tone_args))
		self.pulse_progressbar2()
		if not self.workflow_started:
                        self.original_pixbuf = self.pblist[self.pbindex].copy()
		self.show_image1()
		self.get_channel()
		self.image_was_changed = True
		self.workflow_started = True
		self.set_sensitivity(format)
		self.button83.set_sensitive(True)
		self.window2.window.set_cursor(None)
		self.window5.hide()
		self.progressbar2.set_fraction(0)
	
	def save_sepia_tone(self):
		gtk.gdk.threads_enter()
                self.button83.set_sensitive(False)
                self.wand_index += 1
                if self.wand_index == len(self.wand_list):
                        self.wand_list += [ MagickImage(self.wand.get_image()) ]
                else:
                        self.wand_list[self.wand_index] = MagickImage(self.wand.get_image())
                        del self.wand_list[self.wand_index + 1:]
                        del self.history[self.wand_index - 1:]
                        self.size_history[self.wand_index:] = [self.size_history[self.wand_index] for i in xrange(self.wand_index,100)]
		self.set_toolbuttons_23_39_sensitivity()
                self.image_was_changed = False
                self.history.append( ['sepia_tone', self.sepia_tone_args] )
		if self.expander8.get_expanded():
                        self.draw_grid(False)
		gc.collect()
                gtk.gdk.threads_leave()
	
	def grayscale(self, obj):
		self.window2.window.set_cursor(self.watch)
                while gtk.events_pending():
                        gtk.main_iteration(False)
                format = self.set_filenames()
		self.wand._set_colorspace(api.GRAYColorspace)
		if not self.workflow_started:
                        self.original_pixbuf = self.pblist[self.pbindex].copy()
		self.show_image1()
		self.get_channel()
		self.image_was_changed = True
		self.workflow_started = True
		self.set_sensitivity(format)
		self.button89.set_sensitive(True)
		self.window2.window.set_cursor(None)
	
	def save_grayscale(self):
		gtk.gdk.threads_enter()
                self.button89.set_sensitive(False)
                self.wand_index += 1
                if self.wand_index == len(self.wand_list):
                        self.wand_list += [ MagickImage(self.wand.get_image()) ]
                else:
                        self.wand_list[self.wand_index] = MagickImage(self.wand.get_image())
                        del self.wand_list[self.wand_index + 1:]
                        del self.history[self.wand_index - 1:]
                        self.size_history[self.wand_index:] = [self.size_history[self.wand_index] for i in xrange(self.wand_index,100)]
		self.set_toolbuttons_23_39_sensitivity()
                self.image_was_changed = False
                self.history.append( ['_set_colorspace', (api.GRAYColorspace,)] )
		if self.expander8.get_expanded():
                        self.draw_grid(False)
		gc.collect()
                gtk.gdk.threads_leave()
		
	def save_normalize(self):
		gtk.gdk.threads_enter()
                self.button92.set_sensitive(False)
                self.wand_index += 1
                if self.wand_index == len(self.wand_list):
                        self.wand_list += [ MagickImage(self.wand.get_image()) ]
                else:
                        self.wand_list[self.wand_index] = MagickImage(self.wand.get_image())
                        del self.wand_list[self.wand_index + 1:]
                        del self.history[self.wand_index - 1:]
                        self.size_history[self.wand_index:] = [self.size_history[self.wand_index] for i in xrange(self.wand_index,100)]
		self.set_toolbuttons_23_39_sensitivity()
                self.image_was_changed = False
                self.history.append( ['normalize', ()] )
		if self.expander8.get_expanded():
                        self.draw_grid(False)
		gc.collect()
                gtk.gdk.threads_leave()
		
	def get_real_path(self, fname):
		format = os.path.splitext(fname)[1]
                if self.version + 'Albums/' not in self.window1.get_title() :
                        if format.lower() in self.raw_formats:
                                filename = self.rawpath[fname]
                        else:
                                filename = fname
                elif self.version + 'Albums/' in self.window1.get_title() :
                        if format.lower() in self.raw_formats:
				filename = fname.replace('/thumb','').replace('.thumb.jpg','')
                        else:
                                filename = fname
		return filename
			
	def show_batch_queue(self, obj):
		if self.window7.get_property('visible'): 
			if self.window7_was_iconified:
				self.window7.present()
			else:
				self.on_delete_event(self.window7, None)
		else:                                    
			self.window7.show()

	def on_renderer_toggle_toggled(self, cell, path, model):
                if model[path][4] in [None, 'not found!']:
                        model[path][2] = not model[path][2]
                else:
                        gtk.gdk.beep()

        def cell_data_function(self, column, cell, model, _iter, data=None):
                value = model.get_value(_iter, 4)
		if value == None:
                        color = 'white'
		elif value == 'processing...':
                        color = 'yellow'
		elif value == 'not found!':
                        color = 'red'
		else:
                        color = 'green'
		cell.set_property('cell_background', color)

        def add_to_batch_queue(self, obj):              # Adds item to batch manager
		expanded = False
                for item in self.expander_list:
                        if item.get_expanded():
                                expanded = True
                                break
                if expanded:
                        self.on_expander_activate(item, False, True) 
		filename = self.get_real_path(self.list[self.indice])
		if not self.batch_queue.has_key(filename):
                        pixbuf = self.pblist[self.pbindex].copy()
                        width, height = float(pixbuf.get_width()), float(pixbuf.get_height())
			if width > height:
                        	pixbuf = pixbuf.scale_simple(int(50.0 * (width / height)), 50, gtk.gdk.INTERP_BILINEAR)
			else:
				pixbuf = pixbuf.scale_simple(int(50.0 * (width / height)), 50, gtk.gdk.INTERP_BILINEAR)
                        pixbuf.save(self.batch_thumbs + os.path.basename(filename) + '.jpg', "jpeg", {"quality" : "100"})
                	self.batch_iter = self.batchmodel.append([len(self.batchmodel) + 1, pixbuf, True, filename, None] )
                        self.treeview4.set_model(self.batchmodel)
                        if os.path.splitext(filename)[1].lower() in self.raw_formats:
                                dcraw_cmd = self.make_dcraw_command()
                        else:
                                dcraw_cmd = (None, None, None)
                	self.batch_queue[filename] = [self.history[:self.wand_index], dcraw_cmd]
                	if not self.checkbutton22.get_active():
                                self.label135.set_text('The file was added to batch queue!')
                                gtk.gdk.beep()
                        	self.dialog24.show()
                        	response = self.dialog24.run()
                        	if response == gtk.RESPONSE_CLOSE or response == gtk.RESPONSE_DELETE_EVENT:
                                        self.dialog24.hide()
                        del pixbuf
                else:
                        gtk.gdk.beep()
                        self.label136.set_text('Impossible to add two equal items!')
                        self.dialog25.show()
                        response = self.dialog25.run()
                        if response == gtk.RESPONSE_CLOSE or response == gtk.RESPONSE_DELETE_EVENT:
                                self.dialog25.hide()
	           
        def remove_from_batch_queue(self, obj):         # Removes all checked items on batch manager
                filename = None
                for row in self.batchmodel:
                        if row[2]:
				del self.batch_queue[row[3]]
				filename = row[3]
				self.batchmodel.remove(row.iter)
                        	thread.start_new_thread(os.remove, (self.batch_thumbs + os.path.basename(filename) + '.jpg',))
                i=0
                for row in self.batchmodel:
                        row[0] = i + 1
                        i += 1
		
	def on_button36_clicked(self, obj):             # Selects/Unselects all items on batch manager
                if obj.get_label() == 'Select All':
                        obj.set_label('Unselect All')
			value = True
                else:
                        obj.set_label('Select All')
			value = False
		for row in self.batchmodel:
                        row[2] = value
		  
	def on_button42_clicked(self, obj):             # Closes/Stops batch processor
                if obj.get_label() == 'gtk-close':
                        self.on_delete_event(self.window7, None)
                        self.tooltip.set_tip(obj, 'Close Batch Manager', None)
                else:
                        self.stop_batch_process = True
			self.batchmodel.set_value(self.batch_iter, 4, 'stopping...')
			gobject.idle_add(self.button42.set_label, 'gtk-close')
                	gobject.idle_add(self.button42.set_property, 'image', self.stock_close_img)
				
	def on_button45_clicked(self, obj):             # Starts the batch processor
                if len(self.batchmodel):
			obj.set_sensitive(False)
                        self.button36.set_sensitive(False)
                        self.button40.set_sensitive(False)
                        self.combobox10.set_sensitive(False)
                        self.filechooserbutton7.set_sensitive(False)
                        self.hscale23.set_sensitive(False)
                        self.button42.set_label('gtk-stop')
                        self.button42.set_property('image', self.stock_stop_img)
                        self.tooltip.set_tip(self.button42, 'Stop Batch Processor', None)
                        thread.start_new_thread(self.start_batch_processor, ())

        def get_process_options(self, infile, extension, dest):
                history, dcraw_cmd = self.batch_queue[infile]
                format = os.path.splitext(infile)[1]
                fname = os.path.basename(infile).split('.')[0]
                tempfile = os.getcwd() + '/.thumbnails/_tempfile'
                if format.lower() in self.raw_formats:
                        raw = True
                else:
                        raw = False
                if extension == 0:
                        outfile = dest + '/' + fname + '.jpg'
                        depth = None
                        quality = self.hscale23.get_adjustment().value
                        if raw:
                                tupla = (infile, tempfile)
				if dcraw_cmd[2]:
					tupla = (dcraw_cmd[2],) + tupla
				if dcraw_cmd[1]:
					tupla = (dcraw_cmd[1],) + tupla
                                data = True
                        else:
                                tupla = (0, infile)
                                data = False
                elif extension == 1:
                        outfile = dest + '/' + fname + '.png'
                        depth = None
                        quality = None
                        if raw:
                                tupla = (infile, tempfile)
				if dcraw_cmd[2]:
					tupla = (dcraw_cmd[2],) + tupla
				if dcraw_cmd[1]:
					tupla = (dcraw_cmd[1],) + tupla
                                data = True
                        else:
                                tupla = (0, infile)
                                data = False
                elif extension == 2:
                        outfile = dest + '/' + fname + '.tiff'
                        depth = 8
                        quality = None
                        if raw:
                                tupla = (infile, tempfile)
				if dcraw_cmd[2]:
					tupla = (dcraw_cmd[2],) + tupla
				if dcraw_cmd[1]:
					tupla = (dcraw_cmd[1],) + tupla
                                data = True
                        else:
                                tupla = (0, infile)
                                data = False
                elif extension == 3:
                        outfile = dest + '/' + fname + '.tiff'
                        depth = 16
                        quality = None
                        if raw:
                                tupla = (infile, tempfile)
				if dcraw_cmd[2]:
					tupla = (dcraw_cmd[2],) + tupla
				if dcraw_cmd[1]:
					tupla = (dcraw_cmd[1],) + tupla
                                data = True
                        else:
                                tupla = (0, infile)
                                data = False
                elif extension == 4:
                        outfile = dest + '/' + fname + '.tiff'
                        depth = int(QUANTUM[1:])
                        quality = None
                        if raw:
                                tupla = (infile, tempfile)
				if dcraw_cmd[2]:
					tupla = (dcraw_cmd[2],) + tupla
				if dcraw_cmd[1]:
					tupla = (dcraw_cmd[1],) + tupla
                                data = True
                        else:
                                tupla = (0, infile)
                                data = False
                elif extension == 5:
                        outfile = dest + '/' + fname + '.bmp'
                        depth = None
                        quality = None
                        if raw:
                                tupla = (infile, tempfile)
				if dcraw_cmd[2]:
					tupla = (dcraw_cmd[2],) + tupla
				if dcraw_cmd[1]:
					tupla = (dcraw_cmd[1],) + tupla
                                data = True
                        else:
                                tupla = (0, infile)
                                data = False
                return history, dcraw_cmd[0], tupla, outfile, data, depth, quality, True

        def start_batch_processor(self):
		gtk.gdk.threads_enter()
                dest = self.filechooserbutton7.get_current_folder()
                extension = self.combobox10.get_active()
		self.batch_iter = self.batchmodel.get_iter_first()
                while self.batch_iter:
                        if self.batchmodel.get_value(self.batch_iter, 2):
                                infile = self.batchmodel.get_value(self.batch_iter, 3)
				if not os.path.isfile(infile):
					self.batchmodel.set_value(self.batch_iter, 4, 'not found!')
					self.batchmodel.set_value(self.batch_iter, 2, False)
					self.batch_iter = self.batchmodel.iter_next(self.batch_iter)
					continue	
                                self.batchmodel.set_value(self.batch_iter, 4, 'processing...')
                                process_options = self.get_process_options(infile, extension, dest)
                                self.process(*process_options)
				self.overwrite_thumbnail(process_options[3])
				self.batchmodel.set_value(self.batch_iter, 4, 'completed')
				self.batchmodel.set_value(self.batch_iter, 2, False)
                                self.batch_iter = self.batchmodel.iter_next(self.batch_iter)
                                if self.stop_batch_process:
                                        self.batch_iter = None
			else:
				self.batch_iter = self.batchmodel.iter_next(self.batch_iter)
                gobject.idle_add(self.button36.set_sensitive, True)
                gobject.idle_add(self.button40.set_sensitive, True)
                gobject.idle_add(self.button45.set_sensitive, True)
                gobject.idle_add(self.combobox10.set_sensitive, True)
                gobject.idle_add(self.filechooserbutton7.set_sensitive, True)
                gobject.idle_add(self.hscale23.set_sensitive, True)
                gobject.idle_add(self.button42.set_label, 'gtk-close')
                gobject.idle_add(self.button42.set_property, 'image', self.stock_close_img)
		gobject.idle_add(self.tooltip.set_tip, self.button42, 'Close Batch Manager', None)
                self.stop_batch_process = None
		if self.checkbutton27.get_active():
			for row in self.batchmodel:
                                del self.batch_queue[row[3]]
			self.batchmodel.clear()
		else:
			selected = False
                        for row in self.batchmodel:
				if row[4] != 'not found!':
                                	gobject.idle_add(self.batchmodel.set_value, row.iter, 4, None)
				if row[2]:
					selected = True
			if not selected:
				self.button36.set_label('Select All')
		gtk.gdk.threads_leave()
		
	def show_tag_manager(self, obj):
		self.window8.show()
		return True
		
	def on_tag_toggle_toggled(self, cell, path, model):
		model[path][0] = not model[path][0]
		if model == self.tagmodel2:
                        while gtk.events_pending():
                                gtk.main_iteration(False)
                        if model[path][0]:
                                data = 'add'
                        else:
                                data = 'remove'
                        self.process_metadata(self.list[self.indice], [model[path][1]], data)

        def get_iptc_keywords(self, filename, format):
		info = ''
		try:
			info = commands.getoutput('exiftool -q -s -s -s -1IPTC:Keywords "%s"' % filename)
		except IOError:
			print 'tag not found!'
                if info and 'Warning' not in info:
                        if ',' in info:
                                return info.split(', ')
                        else:
                                return [info]
                else:
                	return []
                        
        def process_metadata(self, item, tag_list, data):
                filename = self.get_real_path(item)
                info_list = self.get_iptc_keywords(filename, os.path.splitext(filename)[1])
		if data == 'add':	
			for tag in tag_list:
				if tag not in info_list:
					try:
						os.system('exiftool -overwrite_original -Keywords+="%s" "%s"' % (tag,filename))
					except:
						print filename, 'not writable!'
		else:
			for tag in tag_list:
				if tag in info_list:
					try:
						os.system('exiftool -overwrite_original -Keywords-="%s" "%s"' % (tag,filename))
					except:
						print filename, 'not writable!'
                        
	def apply_tags(self, obj, data):        # updates metadata of selected images with checked tags
		if not self.selected:
			if self.radiobutton6.get_active():
				return True
			else:
				selected = self.list[self.indice]
		else:
			selected = self.selected
		self.window8.hide()
		tag_list = []
		for row in self.tagmodel:
			if row[0]:
				tag_list += [row[1]]
				row[0] = False
		self.progressbar2.set_text('Updating Metadata...')
		fraction = 0.99 / len(selected)
		self.window5.show()
		while gtk.events_pending():
                        gtk.main_iteration(False)
		for item in selected:
                        self.process_metadata(item, tag_list, data)		
			self.progressbar2.set_fraction(self.progressbar2.get_fraction() + fraction)
			while gtk.events_pending():
                                gtk.main_iteration(False)
			if len(selected) == 1:
				time.sleep(0.1)
		self.window5.hide()
		self.progressbar2.set_fraction(0)

	def delete_tag(self, obj):      # removes selection from tag list
                if obj == self.button55:
                        treeview1 = self.treeview5
                        treeview2 = self.treeview6
                elif obj == self.button76:
                        treeview1 = self.treeview6
                        treeview2 = self.treeview5
                selection = treeview1.get_selection()
                model, iter_ = selection.get_selected()
                if iter_:
                        path = model.get_path(iter_)
                        tag = model.get_value(iter_,1)
                        toggle = model.get_value(iter_,0)
                        if model == self.tagmodel2 and toggle:
                                gtk.gdk.beep()
                        else:
                                model.remove(iter_)
				for row in self.tagmodel3:
					if row[0] == tag:
                                		self.tagmodel3.remove(row.iter)
                                for row in treeview2.get_model():
                                        if row[1] == tag:
                                                treeview2.get_model().remove(row.iter) 
				del self.settings['tags'][self.settings['tags'].index(tag)]       

        def new_tag(self, obj):         # adds new item to tag list
                self.dialog19.show()
                response = self.dialog19.run()
                if response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_DELETE_EVENT:
                        self.dialog19.hide()
                elif response == gtk.RESPONSE_OK:
                        tag = self.entry13.get_text()
                        self.dialog19.hide()
                        if tag and tag not in self.settings['tags']:
                                self.treeview5.get_model().append([False, tag])
                                self.treeview6.get_model().append([False, tag])
                                self.tagmodel3.append([tag])
				self.settings['tags'].append(tag)
		
	def show_tags(self, format):
                filename = self.get_real_path(self.list[self.indice])
                tag_list = self.get_iptc_keywords(filename, format)
                unknown_tags = []
		for row in self.tagmodel2:
			row[0] = False
                if tag_list:
                        for row in self.tagmodel2:
                                if row[1] in tag_list:
                                        self.tag_toggle2.handler_block(self.id81)
                                        row[0] = True
                                        self.tag_toggle2.handler_unblock(self.id81)
                        for item in tag_list:
                                if item not in self.settings['tags']:
                                        unknown_tags += [item]
                        if unknown_tags:
                                for tag in  unknown_tags:
                                        self.tag_toggle2.handler_block(self.id81)
                                        self.treeview5.get_model().append([False, tag])
                                        self.treeview6.get_model().append([True, tag])
                                        self.tagmodel3.append([tag])
                                        self.settings['tags'].append(tag)
                                        self.tag_toggle2.handler_unblock(self.id81)

        def on_combotag_changed(self, obj):
                active = obj.get_active()
                if obj == self.combobox14:
                        self.combobox15.set_active(active)
                else:
                        self.combobox14.set_active(active)
			
	def on_checkbutton28_toggled(self, obj):
		if obj.get_active():
			self.checkbutton30.set_active(True)
			self.checkbutton31.set_sensitive(True)
			self.combobox15.set_sensitive(True)
			self.checkbutton29.set_sensitive(True)
			self.combobox14.set_sensitive(True)
			
		else:
			self.checkbutton30.set_active(False)
			self.checkbutton31.set_sensitive(False)
			self.combobox15.set_sensitive(False)
			self.checkbutton29.set_sensitive(False)
			self.combobox14.set_sensitive(False)
			
	def on_checkbutton29_toggled(self, obj):
		if obj.get_active():
			self.checkbutton31.set_active(True)
		else:
			self.checkbutton31.set_active(False)
			
	def on_checkbutton30_toggled(self, obj):
		if obj.get_active():
			self.checkbutton28.set_active(True)
			self.checkbutton29.set_sensitive(True)
			self.combobox15.set_sensitive(True)
			self.checkbutton31.set_sensitive(True)
			self.combobox14.set_sensitive(True)
			self.label5.set_sensitive(True)
		else:
			self.checkbutton28.set_active(False)
			self.checkbutton31.set_sensitive(False)
			self.combobox15.set_sensitive(False)
			self.checkbutton29.set_sensitive(False)
			self.combobox14.set_sensitive(False)
			self.label5.set_sensitive(False)
			
	def on_checkbutton31_toggled(self, obj):
		if obj.get_active():
			self.checkbutton29.set_active(True)
		else:
			self.checkbutton29.set_active(False)
	
########## END OF IMAGE TOOLS METHODS ################################################################################################

        def load_last_path(self, event):
		if self.checkbutton3.get_active():
                        if self.settings.has_key('switch') and self.settings['switch']:
                                if self.settings['switch'] == 'cartella':
					try:
                                        	self.open_last_folder(self.settings['last_folder_path'])
					except:
                                                pass
                                elif self.settings['switch'] == 'album':
					try:
                                        	self.open_last_album(self.settings['last_album_path'])
					except:
                                                pass

	def make_background_pixbuf(self, event):
                width, height = 800, 600
                surface = cairo.ImageSurface(cairo.FORMAT_RGB24, width, height)
                cr = cairo.Context(surface)
                cr.rectangle(0, 0, width, height)
                cr.clip()
		cr.set_source_rgb(0, 0, 0)
		cr.rectangle(0, 0, width, height)
        	cr.fill()
        	data = surface.get_data()  
		stride = surface.get_stride()
		pixbuf = gtk.gdk.pixbuf_new_from_data(data, gtk.gdk.COLORSPACE_RGB, False, 8, width, height, stride)
		self.background = pixbuf.scale_simple(gtk.gdk.screen_width(), gtk.gdk.screen_height(), gtk.gdk.INTERP_BILINEAR)
		del pixbuf, cr, surface
		gc.collect()

	def add_patterns(self, event):
		output = commands.getoutput('sox -h')
		formats = output.split(':')[-1].split(' ')[1:-1]
		for item in formats:
			self.filter0.add_pattern("*." + item)
		self.filechooserbutton3.add_filter(self.filter0)
		for item in self.formats:
                        self.filter1.add_pattern("*" + item)
                        self.filter1.add_pattern("*" + item.upper())
                for item in self.raw_formats:
                        self.filter1.add_pattern("*" + item)
                        self.filter1.add_pattern("*" + item.upper())
                self.filechooser.add_filter(self.filter1)
                self.filter2.add_pattern("*.icc")
		self.filter2.add_pattern("*.icm")
                self.filechooserbutton4.add_filter(self.filter2)
                self.filechooserbutton5.add_filter(self.filter2)

        def autoresize(self, obj, param):
                if param.name == 'position':
                        self.rect = self.viewport1.allocation
                        format = os.path.splitext(self.list[self.indice])[1]	
			pixbuf = None
                        if format.lower() in self.raw_formats:
				if self.workflow_started :
                                        preview = None
                        	else:			
                                	if self.raw_preview:
                                                preview = self.temp + self.fname
                                	else:
                                                preview = self.list[self.indice][:-len(format)]
				if preview and self.raw_preview:
					self.pblist[self.pbindex] = gtk.gdk.pixbuf_new_from_file_at_size(preview,\
                                                                                self.rect.width, self.rect.height)
				elif preview and not self.raw_preview:
					if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
						self.pblist[self.pbindex] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice]\
                                		[:-len(format)], self.rect.height, self.rect.width)
						self.pblist[self.pbindex] = self.pblist[self.pbindex].rotate_simple(self.rotated[self.indice])
					else:	
                                		self.pblist[self.pbindex] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice]\
                                		[:-len(format)], self.rect.width, self.rect.height)
				else:
					if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
						pixbuf, ratio = self.wand2pixbuf(self.wand)
						ratio2 = float(self.rect.width) / self.rect.height
						if ratio2 > ratio:
							self.pblist[self.pbindex] = self.scale_pixbuf(pixbuf, ratio)
						else:
							self.pblist[self.pbindex] = pixbuf.scale_simple(self.rect.width,\
							int(self.rect.width / ratio), gtk.gdk.INTERP_BILINEAR)
					else:
						self.pblist[self.pbindex] = self.scale_pixbuf(*self.wand2pixbuf(self.wand))
                        else:
                                if self.workflow_started:
					if not self.checkbutton17.get_active(): 
						return True
					else:
                                                if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
							pixbuf, ratio = self.wand2pixbuf(self.wand)
							ratio2 = float(self.rect.width) / self.rect.height
							if ratio2 > ratio:
								self.pblist[self.pbindex] = self.scale_pixbuf(pixbuf, ratio)
							else:
								self.pblist[self.pbindex] = pixbuf.scale_simple(self.rect.width,\
								int(self.rect.width / ratio), gtk.gdk.INTERP_BILINEAR)
						else:
							self.pblist[self.pbindex] = self.scale_pixbuf(*self.wand2pixbuf(self.wand))
				else:
					if self.rotated.has_key(self.indice) and self.checkbutton2.get_active() and \
										self.notebook2.get_current_page() == 0:
						self.pblist[self.pbindex] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice],\
                                                                        	self.rect.height, self.rect.width)
						self.pblist[self.pbindex] = self.pblist[self.pbindex].rotate_simple(self.rotated[self.indice])
					else:
                        			self.pblist[self.pbindex] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice],\
                        							self.rect.width, self.rect.height)
			self.pblist[self.pbindex] = self.check_icons(format,self.pblist[self.pbindex])
			if self.expander8.get_expanded():
                                self.draw_grid(False)
			else:
                                self.image1.set_from_pixbuf(self.pblist[self.pbindex])
                        self.window2.show_all()
                        while gtk.events_pending():
                                gtk.main_iteration(False)
			if pixbuf:
				del pixbuf
			
	def autoresize2(self, obj, param):
		if not self.n:
                        return True
		if self.radiobutton6.get_active():
                        return True
		if param.name == 'position':
                        self.rect2 = self.scrolledwindow2.allocation
			format = os.path.splitext(self.list[self.indice])[1]	
                        if format.lower() in self.raw_formats:
				if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
					self.b_pixlist[self.pixindex] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice]\
                                	[:-len(format)], self.rect2.height - self.swin2_label.allocation.height, self.rect2.width)
					self.b_pixlist[self.pixindex] = self.b_pixlist[self.pixindex].rotate_simple(self.rotated[self.indice])
				else:	
                                	self.b_pixlist[self.pixindex] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice]\
                                	[:-len(format)], self.rect2.width, self.rect2.height - self.swin2_label.allocation.height)
                        else:
				if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
					self.b_pixlist[self.pixindex] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice],\
                                	self.rect2.height - self.swin2_label.allocation.height, self.rect2.width)
					self.b_pixlist[self.pixindex] = self.b_pixlist[self.pixindex].rotate_simple(self.rotated[self.indice])
				else:
                                	self.b_pixlist[self.pixindex] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice],\
                                	self.rect2.width, self.rect2.height - self.swin2_label.allocation.height)
			self.b_pixlist[self.pixindex] = self.check_icons(format, self.b_pixlist[self.pixindex])
			self.swin2_image.set_from_pixbuf(self.b_pixlist[self.pixindex])
			self.scrolledwindow2.show_all()
                        while gtk.events_pending():
                                gtk.main_iteration(False)
			
	def on_key_press_event(self, obj, event):
		keyname = gtk.gdk.keyval_name(event.keyval)
		if obj == self.window3:
			if keyname == 'Up':
                                self.previous_fullphoto(self)
			elif keyname == 'Down':
                                self.next_fullphoto(self)
			elif keyname in ['Return', 'space']:
                                self.on_delete_window3(self.window3, event)
		elif obj == self.window4:
                        self.on_delete_event(self.window4, event)

	def scroll_bottom_panel(self, obj, event):
                adj = self.scrolledwindow6.get_hadjustment()
                if event.direction == gtk.gdk.SCROLL_DOWN:
			if adj.value < adj.upper - adj.page_size:
                                adj.set_value(adj.value + adj.step_increment)
                                self.scrolledwindow6.set_hadjustment(adj)
			elif adj.value >= adj.upper - adj.page_size:
				adj.set_value(adj.upper - adj.page_size)
                                self.scrolledwindow6.set_hadjustment(adj)
                elif event.direction == gtk.gdk.SCROLL_UP:
                        adj.set_value(adj.value - adj.step_increment)
                        self.scrolledwindow6.set_hadjustment(adj)
			
	def toolbuttons(self, obj, data1, data2):
			self.toolbutton31.set_sensitive(data1)
			self.toolbutton32.set_sensitive(data1)
			self.toolbutton33.set_sensitive(data1)
			self.toolbutton34.set_sensitive(data1)
			self.toolbutton18.set_sensitive(data2)
			self.toolbutton19.set_sensitive(data2)
			self.toolbutton20.set_sensitive(data2)
			self.toolbutton40.set_sensitive(data1)
			self.toolbutton41.set_sensitive(data1)
			self.toolbutton42.set_sensitive(data1)
			self.toolbutton43.set_sensitive(data1)

	def store_dcraw_settings(self, event):
                if self.radiobutton10.get_active():
                        self.settings['depth'] = 8
                else:
                        self.settings['depth'] = 16
                if self.checkbutton8.get_active():
                        self.settings['-f'] = True
                else:
                        self.settings['-f'] = False
                self.settings['output_colorspace'] = self.combobox4.get_active()
                if self.checkbutton9.get_active():
                        self.settings['camera_profile'] = True
                else:
                        self.settings['camera_profile'] = False
                self.settings['camera_ICC'] = self.filechooserbutton4.get_filename()
                if self.checkbutton10.get_active():
                        self.settings['output_profile'] = True
                else:
                        self.settings['output_profile'] = False
                self.settings['output_ICC'] = self.filechooserbutton5.get_filename()
                if self.checkbutton11.get_active():
                        self.settings['+M'] = True
                else:
                        self.settings['+M'] = False
                if self.checkbutton13.get_active():
                        self.settings['dark_frame'] = True
                else:
                        self.settings['dark_frame'] = False
                self.settings['dark_filename'] = self.filechooserbutton6.get_filename()
                if self.checkbutton14.get_active():
                        self.settings['-j'] = True
                else:
                        self.settings['-j'] = False
                if self.checkbutton16.get_active():
                        self.settings['-h'] = True
                else:
                        self.settings['-h'] = False    
		
	def load_batch_database(self):
		try:
			f = open('batch.db')
			self.batch_list = cPickle.load(f)
			f.close()
			self.batch_queue = self.batch_list[1]
			for item in self.batch_list[0]:
				self.batchmodel.append([item[0], gtk.gdk.pixbuf_new_from_file(self.batch_thumbs + \
							os.path.basename(item[2]) + '.jpg'), item[1], item[2], item[3]])
			self.treeview4.set_model(self.batchmodel)
		except:
			self.batch_list = [0,0]
                 
        def load_settings_database(self):
                try:
                        f = open('settings')
                        self.settings = cPickle.load(f)
                        f.close()
                        if self.settings.has_key('window1_size'):
                                window1_size = self.settings['window1_size']
				if window1_size[0] == gtk.gdk.screen_width() and window1_size[1] > gtk.gdk.screen_height() - 50:
                                        self.window1.maximize()
				else:
                                        self.window1.resize(window1_size[0], window1_size[1])
			else:
				self.window1.maximize()
			if self.settings.has_key('font'):
				self.font = self.settings['font']
				self.font_desc = pango.FontDescription(self.font)
			else:
                                self.font_desc = pango.FontDescription(self.font)
			if self.settings.has_key('gallery_red'):
                                red = self.settings['gallery_red']
			if self.settings.has_key('gallery_green'):
                                green = self.settings['gallery_green']
			if self.settings.has_key('gallery_blue'):
				blue = self.settings['gallery_blue']
				self.gallery_color = gtk.gdk.Color(red, green, blue)	
				self.colorbutton1.set_color(self.gallery_color)
			else:
                                self.gallery_color = self.colorbutton1.get_color()
			if self.settings.has_key('label_red'):
                                l_red = self.settings['label_red']
			if self.settings.has_key('label_green'):
                                l_green = self.settings['label_green']
			if self.settings.has_key('label_blue'):
				l_blue = self.settings['label_blue']
				self.label_color = gtk.gdk.Color(l_red, l_green, l_blue)	
				self.colorbutton2.set_color(self.label_color)
			else:
                                self.label_color = self.colorbutton2.get_color()
			if self.settings.has_key('treeview_red'):
                                treeview_red = self.settings['treeview_red']
			if self.settings.has_key('treeview_green'):
                                treeview_green = self.settings['treeview_green']
			if self.settings.has_key('treeview_blue'):
				treeview_blue = self.settings['treeview_blue']
				self.treeview_color = gtk.gdk.Color(treeview_red, treeview_green, treeview_blue)
				self.colorbutton3.set_color(self.treeview_color)
			else:
                                self.treeview_color = self.colorbutton3.get_color()
			if self.settings.has_key('toolbar_red'):
                                toolbar_red = self.settings['toolbar_red']
			if self.settings.has_key('toolbar_green'):
                                toolbar_green = self.settings['toolbar_green']
			if self.settings.has_key('toolbar_blue'):
				toolbar_blue = self.settings['toolbar_blue']
				self.toolbar_color = gtk.gdk.Color(toolbar_red, toolbar_green, toolbar_blue)
				self.colorbutton4.set_color(self.toolbar_color)
			else:
                                self.toolbar_color = self.colorbutton4.get_color()
			if self.settings.has_key('selection_red'): selection_red = self.settings['selection_red']
			if self.settings.has_key('selection_green'): selection_green = self.settings['selection_green']
			if self.settings.has_key('selection_blue'):
				selection_blue = self.settings['selection_blue']
				self.selection_color = gtk.gdk.Color(selection_red, selection_green, selection_blue)
				self.colorbutton5.set_color(self.selection_color)
			else:
                                self.selection_color = self.colorbutton5.get_color()
			if self.settings.has_key('image_background_red'):
                                image_background_red = self.settings['image_background_red']
                                image_background_green = self.settings['image_background_green']
                                image_background_blue = self.settings['image_background_blue']
                                self.image_background_color = gtk.gdk.Color(image_background_red, image_background_green, image_background_blue)
                                self.colorbutton8.set_color(self.image_background_color)
                        else:
                                self.image_background_color = self.colorbutton8.get_color()
                        if self.settings.has_key('adj_value'):
				self.adj.set_value(self.settings['adj_value'])
			else:
				self.adj.set_value(2)
				self.settings['adj_value'] = 2
                        if self.settings.has_key('jpg_quality'):
                                self.jpg_quality.set_value(self.settings['jpg_quality'])
                        self.pause = self.settings['adj_value']
			if self.settings.has_key('border_color'):
				self.border_color = self.settings['border_color']
				if self.border_color == 0xffffffff:
					self.comboboxentry5.child.set_text('White')
				elif self.border_color == 0x00000000:
					self.comboboxentry5.child.set_text('Black')
				else:
                                        self.comboboxentry5.child.set_text('Grey')
			if self.settings.has_key('frames'):
				self.frames = self.settings['frames']
				self.spinbutton2.set_value(self.frames)
                        if self.settings['radiobutton1']:
                                self.radiobutton1.set_active(True)
                                self.width = 150
                                self.height = 100
                        if self.settings['radiobutton2']:
                                self.radiobutton2.set_active(True)
                                self.width = 201
                                self.height = 134
                        if self.settings['radiobutton3']:
                                self.radiobutton3.set_active(True)
                                self.width = 260
                                self.height = 174
			if self.settings['radiobutton6']:
				self.radiobutton6.set_active(True)
				self.toolbuttons(self, False, True)
			elif self.settings['radiobutton7']:
				self.radiobutton7.set_active(True)
				self.toolbuttons(self, True, False)
                        if self.settings['checkbutton1']:
                                self.checkbutton1.set_active(True)
				self.toolbutton25.set_icon_widget(self.stock_properties_img)
				self.stock_properties_img.show()
				self.tooltip.set_tip(self.toolbutton25, 'Show Image Tools', None)
			else:
				self.toolbutton25.set_icon_widget(self.stock_close_img)
				self.stock_close_img.show()
				self.tooltip.set_tip(self.toolbutton25, 'Hide Image Tools', None)
			if self.settings['checkbutton2']:
                                self.checkbutton2.set_active(True)
                        if self.settings['checkbutton3']:
                                self.checkbutton3.set_active(True)
			if self.settings['checkbutton4']:
                                self.checkbutton4.set_active(True)
			if self.settings['checkbutton5']:
                                self.checkbutton5.set_active(True)
			if self.settings['checkbutton6']:
                                self.checkbutton6.set_active(True)
			else:
                                self.checkbutton6.set_active(False)
			if self.settings['checkbutton7']:
                                self.checkbutton7.set_active(True)
			else:
                                self.checkbutton7.set_active(False)
                        self.ark = self.settings['ark'] + '/'
                        self.filechooserbutton1.set_current_folder(self.ark[:-1])
                        self.entry4.set_text(self.ark[:-1])
			if self.settings.has_key('filechooserbutton7'):
				self.filechooserbutton7.set_current_folder(self.settings['filechooserbutton7'])
			else:   
				self.filechooserbutton7.set_current_folder(os.environ['HOME'])
				self.settings['filechooserbutton7'] = os.environ['HOME']
			if self.settings.has_key('combobox10'): 
				self.combobox10.set_active(self.settings['combobox10'])
			else:                           
				self.combobox10.set_active(0)
				self.settings['combobox10'] = 0
			if self.settings.has_key('hscale23'):   
				self.hscale23.get_adjustment().value = self.settings['hscale23']
			else: 
				self.hscale23.get_adjustment().value = 80
				self.settings['hscale23'] = 80
			if self.settings['sample']:
				self.sample = self.settings['sample']
                                self.filechooserbutton3.set_filename(self.sample)
			if self.settings['delay']:
				self.delay = self.settings['delay']
				self.spinbutton3.set_value(self.delay)
			self.combobox5.set_active(0)
			if self.settings.has_key('depth'):
                                if self.settings['depth'] == 8:
                                        self.radiobutton10.set_active(True)
                                else:
                                        self.radiobutton11.set_active(True)
                        if self.settings.has_key('-f') and self.settings['-f']:
                                self.checkbutton8.set_active(True)
                        self.combobox2.set_active(0)
                        self.combobox3.set_active(0)
                        if self.settings.has_key('output_colorspace'):
                                self.combobox4.set_active(self.settings['output_colorspace'])
                        if self.settings.has_key('camera_profile') and self.settings['camera_profile']:
                                self.checkbutton9.set_active(True)
                        if self.settings['camera_ICC']:
				self.filechooserbutton4.handler_block(self.id20)
                                self.filechooserbutton4.set_filename(self.settings['camera_ICC'])
				self.filechooserbutton4.handler_unblock(self.id20)
                        if self.settings.has_key('output_profile') and self.settings['output_profile']:
                                self.checkbutton10.set_active(True)
                        if self.settings['output_ICC']:
				self.filechooserbutton5.handler_block(self.id21)
                                self.filechooserbutton5.set_filename(self.settings['output_ICC'])
				self.filechooserbutton5.handler_unblock(self.id21)
                        if self.settings.has_key('+M') and self.settings['+M']:
                                self.checkbutton11.set_active(True)
                        if self.settings.has_key('dark_frame') and self.settings['dark_frame']:
                                self.checkbutton13.set_active(True)
                        if self.settings.has_key('dark_filename') and self.settings['dark_filename']:
                                self.filechooserbutton6.set_filename(self.settings['dark_filename'])
                        if self.settings.has_key('-j') and self.settings['-j']:
                                self.checkbutton14.set_active(True)
                        if self.settings.has_key('-h') and self.settings['-h']:
                                self.checkbutton16.set_active(True) 
			if self.settings.has_key('tags') and self.settings['tags']:
				self.populate_tag_managers()
                except:	
			self.settings = {}
			self.default_settings(self)
		
	def default_settings(self, event):
		self.window1.move(0, 0)
		self.checkbutton1.set_active(False)
		self.settings['checkbutton1'] = False
		self.toolbutton25.set_icon_widget(self.stock_close_img)
		self.stock_close_img.show()
		self.tooltip.set_tip(self.toolbutton25, 'Hide Image Tools', None)
		self.settings['checkbutton2'] = False
		self.settings['checkbutton3'] = True
		self.settings['checkbutton4'] = False
		self.settings['checkbutton5'] = True
		self.settings['checkbutton6'] = False
		self.settings['checkbutton7'] = True
		self.settings['checkbutton17'] = False
		self.settings['radiobutton1'] = True
		self.settings['radiobutton2'] = False
		self.settings['radiobutton3'] = False
		self.settings['radiobutton6'] = True      
		self.settings['ark'] = self.ark[:-1]
		self.radiobutton1.set_active(True)
		self.radiobutton6.set_active(True)
		self.radiobutton7.set_active(False)
		self.checkbutton2.set_active(False)
		self.checkbutton3.set_active(True)
		self.checkbutton4.set_active(False)
		self.checkbutton5.set_active(True)
		self.checkbutton6.set_active(False)
		self.checkbutton7.set_active(True)
		self.checkbutton17.set_active(False)
		self.default_colors(self)
		self.gallery_color = self.colorbutton1.get_color()
		self.label_color = self.colorbutton2.get_color()
		self.treeview_color = self.colorbutton3.get_color()
		self.toolbar_color = self.colorbutton4.get_color()
		self.selection_color = self.colorbutton5.get_color()
		self.image_background_color = self.colorbutton8.get_color()
		self.font_desc = pango.FontDescription(self.font)
		self.settings['border_color'] = 0xffffffff
		self.comboboxentry5.child.set_text('White')
		self.frames = 25
		self.delay = 0.00
		self.sample = None
		self.font = 'TSCu_Comic 12'
		self.settings['frames'] = 25
		self.settings['sample'] = self.sample
		self.settings['delay'] = 0.00
		self.spinbutton3.set_value(0.00)
		self.spinbutton2.set_value(self.frames)	
		self.fontbutton1.set_font_name(self.font)
		self.adj.set_value(2)
		self.filechooserbutton1.set_current_folder(os.environ['HOME'] + '/.GTKRawGallery')
		self.entry9.set_text('50')
		self.settings['window1_size'] = gtk.gdk.screen_width(), gtk.gdk.screen_height()
		self.filechooserbutton7.set_current_folder(os.environ['HOME'])
		self.settings['filechooserbutton7'] = os.environ['HOME']
		self.combobox10.set_active(0)
		self.settings['combobox10'] = 0
		self.hscale23.get_adjustment().value = 80
		self.settings['hscale23'] = 80
		self.combobox2.set_active(0)
		self.combobox3.set_active(0)
		self.combobox4.set_active(1)
		self.combobox5.set_active(0)
		self.checkbutton11.set_active(True)
		self.checkbutton16.set_active(True) 
		self.settings['tags'] = ['Family', 'Portraits', 'Panoramics', 'Macro', 'Sport', 'Nature']
		self.populate_tag_managers()
		
	def populate_tag_managers(self):
		for item in self.settings['tags']:
			self.tagmodel.append([False, item])
			self.tagmodel2.append([False, item])
			self.tagmodel3.append([item])
		self.treeview5.set_model(self.tagmodel)
		self.treeview6.set_model(self.tagmodel2)
		self.combobox14.set_model(self.tagmodel3)
		self.combobox15.set_model(self.tagmodel3)

	def load_album_database(self):
                try:
                        f = open(self.ark + 'albums.db')
                        self.albums = cPickle.load(f)
                        f.close()
			for key in self.albums.keys():
                                try:
                                        self.model.append([gtk.gdk.pixbuf_new_from_file(self.ark + key + '/_preview_.png'), key])
                                except:
                                        self.model.append([gtk.gdk.pixbuf_new_from_file('icons/no_preview.png'), key])
				self.boxmodel.append([key])
				self.boxmodel2.append([key])
                        self.comboboxentry1.set_model(self.boxmodel)
                        self.comboboxentry2.set_model(self.boxmodel2)
			if self.comboboxentry1.get_text_column() != 0:
                                self.comboboxentry1.set_text_column(0)
                        if self.comboboxentry2.get_text_column() != 0:
                                self.comboboxentry2.set_text_column(0)
			self.treeview1.set_model(self.model)
                except:
                        self.albums = {}

	def show_menu6(self, obj, event):
                if event.button == 3:
			x = int(event.x)
			y = int(event.y)
			path = self.treeview1.get_path_at_pos(x, y)
			if path:
				self.path = path[0]
                                self.menu6.popup(None, None, None, event.button, event.time)

        def info(self, event):
                self.dialog7.show()
                response = self.dialog7.run()
                if response == gtk.RESPONSE_CLOSE or response == gtk.RESPONSE_DELETE_EVENT:
                        self.dialog7.hide()
			
	def on_window7_state_event(self, obj, event):
		self.window7_was_iconified = event.new_window_state & gtk.gdk.WINDOW_STATE_ICONIFIED
                        
        def window_state_event(self, obj, event):
                if event.new_window_state & gtk.gdk.WINDOW_STATE_MAXIMIZED:
			if obj == self.window2:
                                if self.settings['checkbutton1']:
					self.frame1.hide_all()
					while gtk.events_pending():
                                                gtk.main_iteration(False)
					self.zoom_fit_photo(self, 0)		
                                else:
                                        self.frame1.show_all()
			elif obj == self.window1 and self.radiobutton7.get_active():
				self.vpaned2.set_position(self.settings['window1_size'][1] - self.height + 30)
					
        def get_options(self, event):                      # Saves settings
                self.dialog12.show()
                response = self.dialog12.run()
                if response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_DELETE_EVENT:
			self.dialog12.hide()
			while gtk.events_pending():
                                gtk.main_iteration(False)
			self.settings['adj_value'] = self.oldadj
			self.adj.set_value(self.settings['adj_value'])
                        self.pause = int(self.settings['adj_value'])
                        if self.settings['radiobutton1']:
                                self.radiobutton1.set_active(True)
                                self.width = 150
                                self.height = 100
                        if self.settings['radiobutton2']:
                                self.radiobutton2.set_active(True)
                                self.width = 201
                                self.height = 134
                        if self.settings['radiobutton3']:
                                self.radiobutton3.set_active(True)
                                self.width = 260
                                self.height = 174
			if self.settings['radiobutton6']:
                                self.radiobutton6.set_active(True)
			else:
			   	self.radiobutton7.set_active(True)
                        if self.settings['checkbutton1']:
                                self.checkbutton1.set_active(True)
			else:
                                self.checkbutton1.set_active(False)
			if self.settings['checkbutton2']:
                                self.checkbutton2.set_active(True)
			else:
                                self.checkbutton2.set_active(False)
                        if self.settings['checkbutton4']:
                                self.checkbutton4.set_active(True)
			else:
                                self.checkbutton4.set_active(False)
			if self.settings['checkbutton5']:
                                self.checkbutton5.set_active(True)
			else:
                                self.checkbutton5.set_active(False)
			if self.settings['checkbutton6']:
                                self.checkbutton6.set_active(True)
			else:
                                self.checkbutton6.set_active(False)
			if self.settings['checkbutton7']:
                                self.checkbutton7.set_active(True)
			else:
                                self.checkbutton7.set_active(False)
			if self.settings['checkbutton3']:
                                self.checkbutton3.set_active(True)
			else:
                                self.checkbutton3.set_active(False)
			if self.settings['checkbutton17']:
                                self.checkbutton17.set_active(True)
			else:
                                self.checkbutton17.set_active(False)
                        self.ark = self.settings['ark'] + '/'
                        self.filechooserbutton1.set_current_folder(self.ark[:-1])
                        self.entry4.set_text(self.ark[:-1])
			self.colorbutton1.set_color(self.gallery_color)
			self.colorbutton2.set_color(self.label_color)
			self.colorbutton3.set_color(self.treeview_color)
			self.colorbutton4.set_color(self.toolbar_color)
			self.colorbutton5.set_color(self.selection_color)
			self.colorbutton8.set_color(self.image_background_color)
			self.fontbutton1.set_font_name(self.font)
			self.border_color = self.settings['border_color']
			if self.border_color == 0xffffffff:
                                self.comboboxentry5.child.set_text('White')
			elif self.border_color == 0x00000000:
                                self.comboboxentry5.child.set_text('Black')
			else:
                                self.comboboxentry5.child.set_text('Grey')
			self.spinbutton2.set_value(self.settings['frames'])
			self.spinbutton3.set_value(self.settings['delay'])
			if self.settings['sample']:
                                self.filechooserbutton3.set_filename(self.settings['sample'])
			self.entry9.set_text(str(self.cache_size))
		elif response == -7:
			self.dialog20.show()
			response20 = self.dialog20.run()
			if response20 == gtk.RESPONSE_CANCEL or response20 == gtk.RESPONSE_DELETE_EVENT:
				self.dialog20.hide()
				self.get_options(self)
			elif response20 == gtk.RESPONSE_OK:
				self.dialog20.hide()
				self.default_settings(self)
				self.get_options(self)
                elif response == gtk.RESPONSE_OK:
			self.dialog12.hide()
			while gtk.events_pending():
                                gtk.main_iteration(False)
			thread.start_new_thread(self.cache_control,())
			self.delay = self.settings['delay'] = self.spinbutton3.get_value()
			self.sample = self.settings['sample'] = self.filechooserbutton3.get_filename()
			self.font = self.fontbutton1.get_font_name()
			self.font_desc = pango.FontDescription(self.font)
			self.settings['font'] = self.font
			self.treeview1.modify_font(self.font_desc)
			self.gallery_color = self.colorbutton1.get_color()
			self.label_color = self.colorbutton2.get_color()
			self.toolbar_color = self.colorbutton4.get_color()
			self.selection_color = self.colorbutton5.get_color()
			self.treeview_color = self.colorbutton3.get_color()
			self.image_background_color = self.colorbutton8.get_color()
			self.settings['treeview_red'] = self.treeview_color.red
			self.settings['treeview_green'] = self.treeview_color.green
			self.settings['treeview_blue'] = self.treeview_color.blue
			self.settings['label_red'] = self.label_color.red
			self.settings['label_green'] = self.label_color.green
			self.settings['label_blue'] = self.label_color.blue
			self.settings['gallery_red'] = self.gallery_color.red
			self.settings['gallery_green'] = self.gallery_color.green
			self.settings['gallery_blue'] = self.gallery_color.blue
			self.settings['toolbar_red'] = self.toolbar_color.red
			self.settings['toolbar_green'] = self.toolbar_color.green
			self.settings['toolbar_blue'] = self.toolbar_color.blue
			self.settings['selection_red'] = self.selection_color.red
			self.settings['selection_green'] = self.selection_color.green
			self.settings['selection_blue'] = self.selection_color.blue
			self.settings['image_background_red'] = self.image_background_color.red
			self.settings['image_background_green'] = self.image_background_color.green
			self.settings['image_background_blue'] = self.image_background_color.blue
			self.window1.modify_bg(gtk.STATE_NORMAL, self.toolbar_color)
			self.window2.modify_bg(gtk.STATE_NORMAL, self.toolbar_color)
			self.toolbar1.modify_bg(gtk.STATE_NORMAL, self.toolbar_color)
			self.toolbar2.modify_bg(gtk.STATE_NORMAL, self.toolbar_color)
			self.treeview1.modify_base(gtk.STATE_NORMAL, self.treeview_color)
			self.treeview2.modify_base(gtk.STATE_NORMAL, self.treeview_color)
			self.treeview3.modify_base(gtk.STATE_NORMAL, self.treeview_color)
			self.eventbox3.modify_bg(gtk.STATE_NORMAL, self.treeview_color)
			self.eventbox5.modify_bg(gtk.STATE_NORMAL, self.treeview_color)
			self.eventbox6.modify_bg(gtk.STATE_NORMAL, self.treeview_color)
			self.viewport1.modify_bg(gtk.STATE_NORMAL, self.image_background_color)
			self.viewport2.modify_bg(gtk.STATE_NORMAL, self.treeview_color)
			if self.radiobutton6.get_active():
                                self.eventbox1.modify_bg(gtk.STATE_NORMAL, self.gallery_color)
                                self.eb.modify_bg(gtk.STATE_NORMAL, self.gallery_color)
                                if self.scrolledwindow2.get_child():
                                        for i in xrange(len(self.label)):
                                                self.event[i].modify_bg(gtk.STATE_NORMAL, self.gallery_color)
                                                self.e[i].modify_bg(gtk.STATE_NORMAL, self.gallery_color)
                                                if type(self.label[i]) != int:
                                                        self.label[i].modify_fg(gtk.STATE_NORMAL, self.label_color)
                                                        self.label[i].modify_font(self.font_desc)
                        else:
				try:
                                	self.swin2_label.modify_fg(gtk.STATE_NORMAL, self.label_color)
                                	self.swin2_label.modify_font(self.font_desc)
					self.eventbox9.modify_bg(gtk.STATE_NORMAL, self.gallery_color)
					self.scrolledwindow2.get_child().modify_bg(gtk.STATE_NORMAL, self.image_background_color)
                                	for i in xrange(self.n):
                                        	self.b_event[i].modify_bg(gtk.STATE_NORMAL, self.gallery_color)
                                	self.b_event[self.indice].modify_bg(gtk.STATE_NORMAL, self.selection_color)
				except:
                                        pass
                        self.settings['adj_value'] = self.oldadj = self.adj.value
                        self.pause = self.adj.value
                        if self.checkbutton1.get_active():
                                self.settings['checkbutton1'] = True
                        else:
                                self.settings['checkbutton1'] = False
			if self.checkbutton2.get_active():
				if not self.settings['checkbutton2']: 
					thread.start_new_thread(self.delete_cached,())
                                self.settings['checkbutton2'] = True
                        else:
                                self.settings['checkbutton2'] = False
                        if self.checkbutton3.get_active():
                                self.settings['checkbutton3'] = True
                        else:
                                self.settings['checkbutton3'] = False
			if self.checkbutton4.get_active():
                                self.settings['checkbutton4'] = True
				border_color = self.comboboxentry5.get_active_text()
				if border_color == 'White':
                                        self.border_color = 0xffffffff
				elif border_color == 'Black':
                                        self.border_color = 0x00000000
				else:
                                        self.border_color = 0x858585ff
				self.settings['border_color'] = self.border_color
                        else:
                                self.settings['checkbutton4'] = False
			if self.checkbutton5.get_active():
                                self.settings['checkbutton5'] = True
				self.frames = int(self.spinbutton2.get_value())
				self.settings['frames'] = self.frames
                        else:
                                self.settings['checkbutton5'] = False
			if self.checkbutton6.get_active():
                                self.settings['checkbutton6'] = True
                        else:
                                self.settings['checkbutton6'] = False
			if self.checkbutton17.get_active():
                                self.settings['checkbutton17'] = True
                        else:
                                self.settings['checkbutton17'] = False
			if self.checkbutton7.get_active():
                                self.settings['checkbutton7'] = True
				try:
					self.cache_size = int(self.entry9.get_text())
				except:
                                        self.cache_size = 50
                        else:
                                self.settings['checkbutton7'] = False
                        if self.radiobutton1.get_active():
                                self.width = 150
                                self.height = 100
                                self.settings['radiobutton1'] = True
                        else:
                                self.settings['radiobutton1'] = False
                        if self.radiobutton2.get_active():
                                self.width = 201
                                self.height = 134
                                self.settings['radiobutton2'] = True
                        else:
                                self.settings['radiobutton2'] = False
                        if self.radiobutton3.get_active():
                                self.width = 260
                                self.height = 174
                                self.settings['radiobutton3'] = True
                        else:
                                self.settings['radiobutton3'] = False
			if self.radiobutton6.get_active():
				self.settings['radiobutton6'] = True
				self.settings['radiobutton7'] = False
			else:
				self.settings['radiobutton6'] = False
				self.settings['radiobutton7'] = True
			archives = self.filechooserbutton1.get_current_folder()
			if archives != self.ark[:-1]:
                                f = open(self.ark + 'albums.db', 'w')
                                cPickle.dump(self.albums, f)
                                f.close()
                                self.ark = archives + '/'
                                self.settings['ark'] = archives
				self.model.clear()
				self.load_album_database(self)
			
        def default_colors(self, event):
                self.colorbutton1.set_color(gtk.gdk.color_parse('#525252'))
                self.colorbutton2.set_color(gtk.gdk.color_parse('#FFFFFF'))
                self.colorbutton3.set_color(gtk.gdk.color_parse('#E2E2E2'))
                self.colorbutton4.set_color(gtk.gdk.color_parse('#969696'))
                self.colorbutton5.set_color(gtk.gdk.color_parse('#CD7300'))
		self.colorbutton8.set_color(gtk.gdk.color_parse('#000000'))
				
	def dcraw_options2(self, event):
		options=['dcraw -c -v']
		WB = self.combobox5.get_active_text()
		if WB == 'Camera WB':
                        options += ['-w']
		elif WB == 'Auto WB':
                        options += ['-a']
		elif WB == 'Manual WB':
			options += ['-r']
			options += [str(self.spinbutton4.get_value())]
			options += [str(self.spinbutton5.get_value())]
			options += [str(self.spinbutton6.get_value())]
			options += ['1.0']
		elif WB == 'Daylight':
                        options += ['-r']
                        options += ['2.2070', '1.0', '1.5566', '1.0']
		elif WB == 'Shade':
			options += ['-r']
                        options += ['2.5664', '1.0', '1.2949', '1.0']
		elif WB == 'Cloudy':
			options += ['-r']
                        options += ['2.3925', '1.0', '1.4121', '1.0']
		elif WB == 'Tungsten':
			options += ['-r']
                        options += ['1.6953', '1.1299', '2.7519', '1.0']
                elif WB=='Fluorescent':
			options+=['-r']
                        options+=['1.9336','1.0420','2.2646','1.0']
		elif WB == 'Flash':
			options += ['-r']
                        options += ['2.4385', '1.0', '1.3838', '1.0']
		if self.checkbutton11.get_active():
			options += ['+M']
		else:
                        options += ['-M']
		options += ['-C']
		options += [str(1.0 + self.spinbutton7.get_value() / 1000.0)]
		options += [str(1.0 + self.spinbutton8.get_value() / 1000.0)]
		options += ['-b']
		adj = self.hscale3.get_adjustment()
		options += [str(adj.value)]
		options += ['-n']
		options += [str(self.spinbutton1.get_value())]
		if self.checkbutton12.get_active():
			options += ['-k']
			options += [str(self.spinbutton9.get_value())]
		if self.checkbutton23.get_active():
			options += ['-S']
			options += [str(self.spinbutton35.get_value())]
		if self.checkbutton13.get_active() and self.filechooserbutton6.get_filename():
			options += ['-K']
			options += [self.filechooserbutton6.get_filename()]
		options += ['-H']
		options += [str(self.combobox3.get_active())]
		options += ['-o']			
		if self.checkbutton10.get_active() and self.filechooserbutton5.get_filename():
			output_profile = self.filechooserbutton5.get_filename()
			options += ['"%s"']
		else:
			output_profile = None
                        options += [str(self.combobox4.get_active())]
		options += ['-p']			
		if self.checkbutton9.get_active() and self.filechooserbutton4.get_filename():
			camera_profile = self.filechooserbutton4.get_filename()
			options += ['"%s"']
		else:
			camera_profile = None
                        options += ['embed']
		if self.checkbutton14.get_active():
			options += ['-j']
		if self.checkbutton8.get_active():
			options += ['-f']
		if self.checkbutton16.get_active():
			options += ['-h']
		if self.radiobutton11.get_active():
			options += ['-4']
		options += ['-T']
		options += ['"%s"', '>', '"%s"']
		return options, output_profile, camera_profile

	def set_default_dcraw_options(self, event):
                self.spinbutton1.handler_block(self.id49)
                self.spinbutton7.handler_block(self.id46)
                self.spinbutton8.handler_block(self.id47)
		self.spinbutton11.handler_block(self.id65)
                self.radiobutton11.handler_block(self.id52)
                self.hscale3.handler_block(self.id51)
		self.hscale15.handler_block(self.id66)
                self.checkbutton8.handler_block(self.id53)
                self.checkbutton9.handler_block(self.id54)
                self.checkbutton10.handler_block(self.id55)
                self.checkbutton11.handler_block(self.id56)
                self.checkbutton12.handler_block(self.id57)
                self.checkbutton13.handler_block(self.id58)
                self.checkbutton14.handler_block(self.id59)
		self.checkbutton16.handler_block(self.id67)
		self.checkbutton23.handler_block(self.id76)
                self.combobox2.handler_block(self.id60)
                self.combobox3.handler_block(self.id61)
                self.combobox4.handler_block(self.id62)
                self.combobox5.handler_block(self.id42)
                self.radiobutton10.set_active(True)
                self.combobox2.set_active(0)
                self.combobox3.set_active(0)
                self.combobox4.set_active(1)
                self.combobox5.set_active(0)
                self.spinbutton1.set_value(0)
                self.spinbutton7.set_value(0)
                self.spinbutton8.set_value(0)
		self.checkbutton8.set_active(False)
                self.checkbutton9.set_active(False)
                self.checkbutton10.set_active(False)
                self.checkbutton11.set_active(True)
                self.checkbutton12.set_active(False)
                self.checkbutton13.set_active(False)
                self.checkbutton14.set_active(False)
		self.checkbutton16.set_active(True)
		self.checkbutton23.set_active(False)
                adj = self.hscale3.get_adjustment()
                adj.set_value(1)
                self.hscale3.set_adjustment(adj)
                self.spinbutton1.handler_unblock(self.id49)
                self.spinbutton7.handler_unblock(self.id46)
                self.spinbutton8.handler_unblock(self.id47)
		self.spinbutton11.handler_unblock(self.id65)
                self.radiobutton11.handler_unblock(self.id52)
                self.hscale3.handler_unblock(self.id51)
		self.hscale15.handler_unblock(self.id66)
                self.checkbutton8.handler_unblock(self.id53)
                self.checkbutton9.handler_unblock(self.id54)
                self.checkbutton10.handler_unblock(self.id55)
                self.checkbutton11.handler_unblock(self.id56)
                self.checkbutton12.handler_unblock(self.id57)
                self.checkbutton13.handler_unblock(self.id58)
                self.checkbutton14.handler_unblock(self.id59)
		self.checkbutton16.handler_unblock(self.id67)
		self.checkbutton23.handler_unblock(self.id76)
                self.combobox2.handler_unblock(self.id60)
                self.combobox3.handler_unblock(self.id61)
                self.combobox4.handler_unblock(self.id62)
                self.combobox5.handler_unblock(self.id42)
       		gobject.idle_add(self.load_raw_preview, self.rect.width, self.rect.height)
                	
	def wb_changed(self, event):
		if  'Manual WB' not in self.combobox5.get_active_text():
			self.spinbutton4.set_sensitive(False)
			self.spinbutton5.set_sensitive(False)
			self.spinbutton6.set_sensitive(False)
		else:
			self.spinbutton4.set_sensitive(True)
			self.spinbutton5.set_sensitive(True)
			self.spinbutton6.set_sensitive(True)
		
        def show_convert(self, event):
		self.window6.move(0, 0)
		self.progressbar4.hide()
                self.window6.set_title('Convert Selection  (%d files)' % len(self.selected)) 
                self.window6.show()

        def multiple_conversion(self, event):
                dest = self.entry5.get_text()
                extension = self.combobox7.get_active()
                if extension == 0:
                        self.dialog16.show()
                        response16 = self.dialog16.run()
                        if response16 == gtk.RESPONSE_CANCEL or response16 == gtk.RESPONSE_DELETE_EVENT:
                                self.dialog16.hide()
                                self.show_convert(self)
				return True
                        elif response16 == gtk.RESPONSE_OK:
                                self.dialog16.hide()
                                while gtk.events_pending():
                                        gtk.main_iteration(False)
                                self.settings['jpg_quality'] = self.jpg_quality.value
				self.progressbar4.show()
                                thread.start_new_thread(self.convert_as_jpg, (self.selected, self.jpg_quality.value, dest))
                elif extension == 1:
			self.progressbar4.show()
                        thread.start_new_thread(self.convert_as_png, (self.selected, dest))     
                elif extension == 2:
			self.progressbar4.show()
                        thread.start_new_thread(self.convert_as_tiff, (self.selected, 8, dest))
                elif extension == 3:
			self.progressbar4.show()
                        thread.start_new_thread(self.convert_as_tiff,(self.selected, 16, dest)) 
		elif extension == 4:
			self.progressbar4.show()
                        thread.start_new_thread(self.convert_as_tiff, (self.selected, int(QUANTUM[1:]), dest))    
                elif extension == 5:
			self.progressbar4.show()
                        thread.start_new_thread(self.convert_as_bmp, (self.selected, dest))      

        def save_as_dialog(self, event):
		expanded = False
                for item in self.expander_list:
                        if item.get_expanded():
                                expanded = True
                                break
                if expanded:
                        self.on_expander_activate(item, False) 
                if self.radiobutton6.get_active() and not self.window2.get_property('visible'):
                        if self.obj in self.event:
                                self.indice = self.event.index(self.obj)
                        elif  self.obj in self.e:
                                self.indice = self.e.index(self.obj)
                format = os.path.splitext(self.list[self.indice])[1]
                if self.version + 'Albums/' not in self.window1.get_title() :
                        if format.lower() in self.raw_formats:
                                filename = self.rawpath[self.list[self.indice]]
                        else:
                                filename = self.list[self.indice]
                elif self.version+'Albums/' in self.window1.get_title() :
                        if format.lower() in self.raw_formats:
				filename = self.list[self.indice].replace('/thumb', '').replace('.thumb.jpg', '')
                        else:
                                filename = self.list[self.indice]
		self.entry7.set_text(os.path.basename(filename)[:-len(format)])
		self.filechooser2.move(0, 0)
                self.filechooser2.show()
		if self.window2.get_property('visible'):
                        self.filechooser2.set_transient_for(self.window2)
		else:
                        self.filechooser2.set_transient_for(self.window1)
                response = self.filechooser2.run()
                if response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_DELETE_EVENT:
                        self.filechooser2.hide()
                elif response == gtk.RESPONSE_OK:
                        self.filechooser2.hide()
                        while gtk.events_pending():
                                gtk.main_iteration(False)
                        fname = self.entry7.get_text()
                        dest = self.filechooser2.get_current_folder()
                        extension = self.combobox9.get_active()
                        if extension == 0:
                                self.dialog16.show()
                                response16 = self.dialog16.run()
                                if response16 == gtk.RESPONSE_CANCEL or response16 == gtk.RESPONSE_DELETE_EVENT:
                                        self.dialog16.hide()
                                        self.save_as_dialog(self)
                                elif response16 == gtk.RESPONSE_OK:
                                        self.dialog16.hide()
                                        while gtk.events_pending():
                                                gtk.main_iteration(False)
                                        self.settings['jpg_quality'] = self.jpg_quality.value
                                        self.save_as_jpg(fname, filename, self.jpg_quality.value, dest)
                        elif extension == 1:
                                self.save_as_png(fname, filename, dest)        
                        elif extension == 2:
                                self.save_as_tiff(fname, filename, 8, dest)
                        elif extension == 3:
                                self.save_as_tiff(fname, filename, 16, dest)
                        elif extension == 4:
                                self.save_as_tiff(fname, filename, int(QUANTUM[1:]), dest)      
                        elif extension == 5:
                                self.save_as_bmp(fname, filename, dest)                 
                self.unselect(self)

        def conversion_error(self, item):
                self.label31.set_text('Cannot convert %s' % os.path.split(item)[1])
                self.dialog15.show()
                gtk.gdk.beep()
                response = self.dialog15.run()
                if response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_DELETE_EVENT:
                        self.dialog15.hide()

        def overwrite_dialog(self, dest, filename):
                filelist = os.listdir(dest)
                if filename in filelist:
                        self.label29.set_text('A file named:\n"%s" already exists.\nDo you want to overwrite it?' % filename)
                        self.dialog18.show()
			gtk.gdk.beep()
                        response = self.dialog18.run()
                        if response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_DELETE_EVENT:
                                self.dialog18.hide()
				while gtk.events_pending():
                                        gtk.main_iteration(False)
                                self.overwrite_thumb = False
                                return False
                        elif response == gtk.RESPONSE_OK:
                                self.dialog18.hide()
				while gtk.events_pending():
                                        gtk.main_iteration(False)
				self.overwrite_thumb = True
                                return True
		else:
                        return True

	def make_dcraw_command(self):
                options, output_profile, camera_profile = self.dcraw_options2(self)
                interpolation = self.combobox2.get_active_text()
		if '-h' in options:
                	if interpolation == 'AUTO':
                                del options[options.index('-h')]
                	elif interpolation == 'BILINEAR':
                                options[options.index('-h')] = '-q 0'
                	elif interpolation == 'VNG':
                                options[options.index('-h')] = '-q 1'
                	elif interpolation == 'PPG':
                                options[options.index('-h')] = '-q 2'
                	elif interpolation == 'AHG':
                                options[options.index('-h')] = '-q 3'
                return string.join(options), output_profile, camera_profile

        def overwrite_thumbnail(self, outfile):
		preview = str(hash(outfile)) + '.jpeg' 
                if self.overwrite_thumb or preview in self.cache_list:
                        pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(outfile, 260, 174)
                        pixbuf.save(self.cache + preview, "jpeg")
                        self.overwrite_thumb = False

        def pulse_progressbar2(self):
                while not self.stop_progressbar2.isSet():
                        self.progressbar2.pulse()
			while gtk.events_pending():
                                gtk.main_iteration(False)
                        time.sleep(1)
                self.stop_progressbar2.clear()
		
	def process(self, history, command, tupla, outfile, data, depth=None, quality=None, batch=None):
		if batch or self.window6.get_property('visible') and history:
                        index = len(history)
		else:
                        index = self.wand_index
		if data:
                        os.system(command % tupla)
		i_magick = MagickImage(tupla[-1])
		if history:
                        for item in history[:index]:
                                if len(item) == 3 :
                                        if item[0][0] == '_get_size' :
                                                try:
                                                        size = getattr(i_magick, item[0][0])()
                                                        args = (long(item[1][1][0][0] * size[0]), long(item[1][1][0][1] * size[1])),\
                                                        (long(item[1][1][1][0] * size[0]), long(item[1][1][1][1] * size[1]))
                                                        getattr(i_magick, item[1][0])(*args)
                                                        args = (long(item[2][1][0][0] * size[0]), long(item[2][1][0][1] * size[1])),(0,0)	
                                                        getattr(i_magick, item[2][0])(*args)
                                                except:
                                                        print 'Error on crop function.'
					elif item[0] == 'recolor':
                                        	getattr(i_magick, item[0])(3, item[1])
						if item[2]:
							i_magick._set_colorspace(api.GRAYColorspace)
                                        else:
                                                getattr(i_magick, item[0][0])(*item[0][1])
                                                getattr(i_magick, item[1][0])(*item[1][1])
                                                getattr(i_magick, item[2][0])(*item[2][1])
				elif item[0] == 'border':
					getattr(i_magick, item[0])(Color(item[1][0]), *item[1][1:])
				else: 
					getattr(i_magick, item[0])(*item[1])
		format_ = os.path.splitext(outfile)[1][1:].upper()
		i_magick.format = format_
                if depth:
                        i_magick.set_depth(long(depth))
                if quality:
                        i_magick._set_compression_quality(quality)
                if batch or self.window6.get_property('visible'):
                        outfile = self.make_outname(outfile)
                i_magick.save(outfile)
		self.add_missed_tags(tupla[-2], outfile, format_)
		if not batch:
                        self.stop_progressbar2.set()
		del i_magick
                gc.collect()

        def make_outname(self, outfile): 
		n = 0          
                while os.path.isfile(outfile):
                        basename = os.path.basename(outfile)
                        root, format = os.path.splitext(basename)
                        if '_(' not in root and ')_' not in root:
                                outfile = os.path.dirname(outfile)+ '/' + root + '_(1)_' + format
				n = 1
                        else:
				outfile = outfile.replace('_(' + str(n) + ')_', '_(' + str(n + 1) + ')_')
                                n += 1
                return outfile
			
	def add_missed_tags(self, filename, outfile, format):
		if format == 'PNG':
			os.system('exiftool -P -overwrite_original -TagsFromFile "%s" -ExposureTime -FNumber -ISO \
		 	-ExposureProgram -ExposureCompensation -Flash -FocalLength -Lens >xmp "%s"'% (filename, outfile))
		else:	
			os.system('exiftool -P -overwrite_original -TagsFromFile "%s" -ExposureTime -FNumber -ISO \
		 	-ExposureProgram -ExposureCompensation -Flash -FocalLength -Lens "%s"'% (filename, outfile))
		
        def save_as_jpg(self, fname, filename, quality, dest):
                if not self.overwrite_dialog(dest, fname + '.jpg'):
                        return True
                self.window1.window.set_cursor(self.watch)
		self.progressbar2.set_text('Saving...')
		self.window5.show()
		while gtk.events_pending():
                        gtk.main_iteration(False)
                format = os.path.splitext(filename)[1]
                if format.lower() in self.raw_formats:
                        try:
                                tempfile = os.getcwd() + '/.thumbnails/_' + fname + '.tiff'
                                outfile = dest + '/' + fname + '.jpg'
                                command, output_profile, camera_profile = self.make_dcraw_command()
				tupla = (filename, tempfile)
				if camera_profile:
					tupla = (camera_profile,) + tupla
				if output_profile:
					tupla = (output_profile,) + tupla
				thread.start_new_thread(self.process,(self.history, command, tupla, outfile, True, None, quality))
				self.pulse_progressbar2()
				self.overwrite_thumbnail(outfile)
                                os.remove(tempfile)
                        except IOError:
                                self.conversion_error(filename)
                else:
                        try:
                                outfile = dest + '/' + fname+ '.jpg'
				tupla=(0, filename)
				thread.start_new_thread(self.process,(self.history, None, tupla, outfile, False, None, quality))
				self.pulse_progressbar2()
				self.overwrite_thumbnail(outfile)            
			except IOError:
                                self.conversion_error(filename)
                                if os.path.isfile(outfile):
                                        os.remove(outfile)
                self.window1.window.set_cursor(None)
                self.window5.hide()
                self.progressbar2.set_fraction(0)

        def save_as_png(self, fname, filename, dest):
                if not self.overwrite_dialog(dest, fname+ '.png'):
                        return True
                self.window1.window.set_cursor(self.watch)
		self.progressbar2.set_text('Saving...')
		self.window5.show()
		while gtk.events_pending():
                        gtk.main_iteration(False)
                format = os.path.splitext(filename)[1]
                if format.lower() in self.raw_formats:
                        try:
                                tempfile = os.getcwd() + '/.thumbnails/_' + fname + '.tiff'
                                outfile = dest + '/' + fname + '.png'
				command, output_profile, camera_profile = self.make_dcraw_command()
				tupla = (filename, tempfile)
				if camera_profile:
					tupla = (camera_profile,) + tupla
				if output_profile:
					tupla = (output_profile,) + tupla
				thread.start_new_thread(self.process,(self.history, command, tupla, outfile, True, None, None))
				self.pulse_progressbar2()
                                self.overwrite_thumbnail(outfile)
				os.remove(tempfile)
                        except IOError:
                                self.conversion_error(filename)
                else:
                        try:
                                outfile = dest + '/' + fname + '.png'
				tupla = (0, filename)
				thread.start_new_thread(self.process,(self.history, None, tupla, outfile, False, None, None))
				self.pulse_progressbar2()
                                self.overwrite_thumbnail(outfile)
                        except IOError:
                                self.conversion_error(filename)
                                if os.path.isfile(outfile):
                                        os.remove(outfile)
                self.window1.window.set_cursor(None)
                self.window5.hide()
                self.progressbar2.set_fraction(0)
		
	def on_filechooserbutton4_current_folder_changed(self,obj):
		if self.checkbutton9.get_active() and self.window2.get_property("visible"):
			gobject.idle_add(self.load_raw_preview, self.rect.width, self.rect.height)	
		
	def on_filechooserbutton5_current_folder_changed(self,obj):
		if self.checkbutton10.get_active() and self.window2.get_property("visible"):
			gobject.idle_add(self.load_raw_preview, self.rect.width, self.rect.height)	
		
	def first_to_load_raw_preview(self, *obj):
		if self.window2.get_property('visible') and self.notebook2.get_current_page() == 2:
			if self.workflow_started:
				if self.show_dialog21():
                                        return True		
			if obj[0]==self.combobox5 and not self.combobox5.get_active() == 2:
				gobject.idle_add(self.load_raw_preview, self.rect.width, self.rect.height)
			elif obj[0] in [self.spinbutton1, self.spinbutton4, self.spinbutton5, self.spinbutton6, self.spinbutton7,self.spinbutton8,self.spinbutton11]:
				thread.start_new_thread(self.on_multiplier_changed, ())
			elif obj[0]==self.spinbutton9 and self.checkbutton12.get_active():
				thread.start_new_thread(self.on_multiplier_changed, ())
			elif obj[0]==self.spinbutton35 and self.checkbutton23.get_active():
				thread.start_new_thread(self.on_multiplier_changed, ())
			elif obj[0] in [self.combobox3, self.combobox4, self.checkbutton8, self.checkbutton11, self.checkbutton14, self.radiobutton11,\
			self.checkbutton9, self.checkbutton10, self.checkbutton12, self.checkbutton13, self.checkbutton16, self.checkbutton23, self.hscale3, self.hscale15]:
				gobject.idle_add(self.load_raw_preview, self.rect.width, self.rect.height)

	def on_multiplier_changed(self):
                self.pila.append(0)
                time.sleep(0.3)
                if len(self.pila) > 1:
			self.pila.pop()
                else:
			gobject.idle_add(self.load_raw_preview, self.rect.width, self.rect.height)
			self.pila = []
								
	def load_raw_preview(self, width, height):
		format = os.path.splitext(self.list[self.indice])[1]
		if format.lower() in self.raw_formats:
                        self.window2.window.set_cursor(self.watch)
                        self.make_surface(True)
                        self.draw_gradient(self.r, self.g, self.b)
                	if self.version + 'Albums/' not in self.window1.get_title() :
                        	filename = self.rawpath[self.list[self.indice]]
                	elif self.version + 'Albums/' in self.window1.get_title() :
				filename = self.list[self.indice].replace('/thumb', '').replace('.thumb.jpg', '')
			fname = os.path.basename(filename)[:-len(format)]
                        outfile = self.temp + self.fname
			options, output_profile, camera_profile = self.dcraw_options2(self)
			command = string.join(options,' ')
			tupla = (filename, outfile)
			if camera_profile:
				tupla = (camera_profile,) + tupla
			if output_profile:
				tupla = (output_profile,) + tupla
			st_input, st_output = os.popen4(command % tupla)
			output = st_output.read()
			st_output.close()
			st_input.close()
			try:
				outlist = output.split(', and\nmultipliers ')
				levels = outlist[0].split('\n')[-1].split(', ')
				black_point = levels[0].split(' ')[-1]
				saturation = levels[1].split(' ')[-1]
				multipliers = outlist[1].split('\n')[0].split(' ')
				self.spinbutton4.handler_block(self.id43)
				self.spinbutton5.handler_block(self.id44)
				self.spinbutton6.handler_block(self.id45)
				self.spinbutton9.handler_block(self.id48)
				self.spinbutton35.handler_block(self.id79)
				self.spinbutton4.set_value(float(multipliers[0]))   
				self.spinbutton5.set_value(float(multipliers[1]))   
				self.spinbutton6.set_value(float(multipliers[2]))
				self.spinbutton9.set_value(int(black_point)) 
				self.spinbutton35.set_value(int(saturation)) 
				self.spinbutton4.handler_unblock(self.id43)
				self.spinbutton5.handler_unblock(self.id44)
				self.spinbutton6.handler_unblock(self.id45)
				self.spinbutton9.handler_unblock(self.id48)
				self.spinbutton35.handler_unblock(self.id79)
			except:
                                pass
			self.pblist[self.pbindex] = gtk.gdk.pixbuf_new_from_file_at_size(outfile, width, height)
			if self.expander17.get_expanded():
				width = self.pblist[self.pbindex].get_width()
				height = self.pblist[self.pbindex].get_height()
				self.drawable.draw_pixbuf(self.gc, self.pblist[self.pbindex], 0, 0, int((self.rect.width - width)/2),\
				int((self.rect.height - height) / 2))
				self.drawing_area.queue_draw()
				self.x, self.y = self.x1, self.y1
				self.set_zoom_sensitivity(False)
			elif self.expander8.get_expanded():
				self.draw_grid(False)   
			else:
                		self.image1.set_from_pixbuf(self.pblist[self.pbindex])
				self.image1.show()
                        self.window2.window.set_cursor(None)
			self.calculate_percentage()
			self.add_dimensions(format, self._label)
			self.raw_preview = True
                self.get_channel()
		
        def save_as_tiff(self, fname, filename, depth, dest):
                if not self.overwrite_dialog(dest, fname + '.tiff'):
                        return True
                self.window1.window.set_cursor(self.watch)
		self.progressbar2.set_text('Saving...')
		self.window5.show()
		while gtk.events_pending():
                        gtk.main_iteration(False)
                format = os.path.splitext(filename)[1]
                if format.lower() in self.raw_formats:
                        try:
                                tempfile = os.getcwd() + '/.thumbnails/_' + fname + '.tiff'
                                outfile = dest + '/' + fname + '.tiff'
                                command, output_profile, camera_profile = self.make_dcraw_command()
				tupla = (filename, tempfile)
				if camera_profile:
					tupla = (camera_profile,) + tupla
				if output_profile:
					tupla = (output_profile,) + tupla
                                thread.start_new_thread(self.process,(self.history, command, tupla, outfile, True, depth, None))
				self.pulse_progressbar2()
                                self.overwrite_thumbnail(outfile)
                                os.remove(tempfile)
                        except IOError:
                                self.conversion_error(filename)
                else:
                        try:
                        	outfile = dest + '/' + fname + '.tiff'
				tupla=(0, filename)
				thread.start_new_thread(self.process,(self.history, None, tupla, outfile, False, depth, None))
				self.pulse_progressbar2()
                                self.overwrite_thumbnail(outfile)
			except IOError:
                                self.conversion_error(filename)
                                if os.path.isfile(outfile):
                                        os.remove(outfile)
                self.window1.window.set_cursor(None)
                self.window5.hide()
                self.progressbar2.set_fraction(0)
                
        def save_as_bmp(self, fname, filename, dest):
                if not self.overwrite_dialog(dest, fname + '.bmp'):
                        return True
                self.window1.window.set_cursor(self.watch)
	 	self.progressbar2.set_text('Saving...')
		self.window5.show()
		while gtk.events_pending():
                        gtk.main_iteration(False)
                format = os.path.splitext(filename)[1]
                if format.lower() in self.raw_formats:
                        try:
                                tempfile = os.getcwd() + '/.thumbnails/_' + fname + '.tiff'
                                outfile = dest + '/' + fname + '.bmp'
				command, output_profile, camera_profile = self.make_dcraw_command()
				tupla = (filename, tempfile)
				if camera_profile:
					tupla = (camera_profile,) + tupla
				if output_profile:
					tupla = (output_profile,) + tupla
				thread.start_new_thread(self.process,(self.history, command, tupla, outfile, True, None, None))
				self.pulse_progressbar2()
				self.overwrite_thumbnail(outfile)
				os.remove(tempfile)
                        except IOError:
                                self.conversion_error(filename)
                else:
                        try:
                                outfile = dest + '/' + fname + '.bmp'
				tupla=(0, filename)
				thread.start_new_thread(self.process,(self.history, None, tupla, outfile, False, None, None))
				self.pulse_progressbar2()
				self.overwrite_thumbnail(outfile)
                        except IOError:
                                self.conversion_error(filename)
                                if os.path.isfile(outfile):
                                        os.remove(outfile)
                self.window1.window.set_cursor(None)
                self.window5.hide()
                self.progressbar2.set_fraction(0)
               
        def convert_as_jpg(self, selected, quality, dest):
		gtk.gdk.threads_enter()
                gobject.idle_add(self.win6_okbutton.set_sensitive, False)
                gobject.idle_add(self.checkbutton20.set_sensitive, False)
                gobject.idle_add(self.win6_cancelbutton.set_label, 'Stop')
                gobject.idle_add(self.win6_cancelbutton.set_property, 'image', self.stock_stop_img)
                n = 0
                fraction = 0.99 / len(selected)
		command, output_profile, camera_profile = self.make_dcraw_command()
		if self.checkbutton20.get_active() and self.workflow_copy:
                        workflow = self.workflow_copy
                else:
                        workflow = None
                for item in selected:
                        if self.stop_thread.isSet():
                                break
                        n += 1
                        gobject.idle_add(self.window6.set_title, ('Converting %s of %s files...' % (n, len(selected))))
                        format = os.path.splitext(item)[1]
                        if format.lower() in self.raw_formats:
                                if self.version + 'Albums/' not in self.window1.get_title() :
                                	filename = self.rawpath[item]
                                else:
                                        filename = item.replace('/thumb', '').replace('.thumb.jpg', '')
                                try:
                                	fname = os.path.split(filename)[1][:-len(format)]
                                	tempfile = os.getcwd() + '/.thumbnails/_' + fname + '.tiff'
                                	outfile = dest + '/' + fname + '.jpg'
                                	if os.path.isfile(outfile):
                                                self.overwrite_thumb = True       
					tupla = (filename, tempfile)
					if camera_profile:
						tupla = (camera_profile,) + tupla
					if output_profile:
						tupla = (output_profile,) + tupla
                                	self.process(workflow, command, tupla, outfile, True, None, quality)
					self.overwrite_thumbnail(outfile) 
                                	os.remove(tempfile)
                                except IOError:
                                       self.conversion_error(item)
                        else:
                                try:
                                        fname = os.path.split(item)[1][:-len(format)]
                                        outfile = dest + '/' + fname + '.jpg'
                                        if os.path.isfile(outfile):
                                                self.overwrite_thumb = True
					tupla=(0, item)
                                        self.process(workflow, None, tupla, outfile, None, None, quality)
					self.overwrite_thumbnail(outfile) 
                                except IOError:
                                        self.conversion_error(item)
                        gobject.idle_add(self.progressbar4.set_fraction,(self.progressbar4.get_fraction() + fraction))
		self.window6.hide()
		self.unselect(self)
                gobject.idle_add(self.progressbar4.set_fraction, 0)
                gobject.idle_add(self.win6_okbutton.set_sensitive, True)
                gobject.idle_add(self.checkbutton20.set_sensitive, True)
                gobject.idle_add(self.win6_cancelbutton.set_label, 'Cancel')
                gobject.idle_add(self.win6_cancelbutton.set_property, 'image', self.stock_cancel_img)
		self.stop_thread.clear()
		gtk.gdk.threads_leave()
		
        def convert_as_png(self, selected, dest):
		gtk.gdk.threads_enter()
                gobject.idle_add(self.win6_okbutton.set_sensitive, False)
                gobject.idle_add(self.checkbutton20.set_sensitive, False)
                gobject.idle_add(self.win6_cancelbutton.set_label, 'Stop')
                gobject.idle_add(self.win6_cancelbutton.set_property, 'image', self.stock_stop_img)
                n = 0
                fraction = 0.99 / len(selected)
		command, output_profile, camera_profile = self.make_dcraw_command()
		if self.checkbutton20.get_active() and self.workflow_copy:
                        workflow = self.workflow_copy
                else:
                        workflow = None
                for item in selected:
                        if self.stop_thread.isSet():
                                break
                        n += 1
                        gobject.idle_add(self.window6.set_title, ('Converting %s of %s files...' % (n, len(selected))))
                        format = os.path.splitext(item)[1]
                        if format.lower() in self.raw_formats:
                                if self.version+'Albums/' not in self.window1.get_title() :
                                        filename = self.rawpath[item]
                                else:
                                        filename = item.replace('/thumb', '').replace('.thumb.jpg', '')
                                try:
                                        fname = os.path.split(filename)[1][:-len(format)]
                                        tempfile = os.getcwd() + '/.thumbnails/_' + fname + '.tiff'
                                        outfile = dest + '/' + fname + '.png'
                                        if os.path.isfile(outfile):
                                                self.overwrite_thumb = True
                                        tupla=(filename, tempfile)
					if camera_profile:
						tupla = (camera_profile,) + tupla
					if output_profile:
						tupla = (output_profile,) + tupla
                                        self.process(workflow, command, tupla, outfile, True, None, None)
					self.overwrite_thumbnail(outfile) 
                                        os.remove(tempfile)
                                except IOError:
                                        self.conversion_error(item)
                        else:
                                try:
                                        fname = os.path.split(item)[1][:-len(format)]
                                        outfile = dest + '/' + fname + '.png'
                                        if os.path.isfile(outfile):
                                                self.overwrite_thumb = True
                                        tupla=(0, item)
                                        self.process(workflow, None, tupla, outfile, None, None, None)
					self.overwrite_thumbnail(outfile) 
                                except IOError:
                                        self.conversion_error(item)
                        gobject.idle_add(self.progressbar4.set_fraction, (self.progressbar4.get_fraction() + fraction))
                self.window6.hide()
		self.unselect(self)
                gobject.idle_add(self.progressbar4.set_fraction, 0)
                gobject.idle_add(self.win6_okbutton.set_sensitive, True)
                gobject.idle_add(self.checkbutton20.set_sensitive, True)
                gobject.idle_add(self.win6_cancelbutton.set_label, 'Cancel')
                gobject.idle_add(self.win6_cancelbutton.set_property, 'image', self.stock_cancel_img)
		self.stop_thread.clear()
		gtk.gdk.threads_leave()
		
        def convert_as_tiff(self, selected, depth, dest):
		gtk.gdk.threads_enter()
                gobject.idle_add(self.win6_okbutton.set_sensitive, False)
                gobject.idle_add(self.checkbutton20.set_sensitive, False)
                gobject.idle_add(self.win6_cancelbutton.set_label, 'Stop')
                gobject.idle_add(self.win6_cancelbutton.set_property, 'image', self.stock_stop_img)
                n = 0
                fraction = 0.99 / len(selected)
		command, output_profile, camera_profile = self.make_dcraw_command()
		if self.checkbutton20.get_active() and self.workflow_copy:
                        workflow = self.workflow_copy
                else:
                        workflow = None
                for item in selected:
                        if self.stop_thread.isSet():
                                break
                        n += 1
                        gobject.idle_add(self.window6.set_title,('Converting %s of %s files...' % (n, len(selected))))
                        format = os.path.splitext(item)[1]
                        if format.lower() in self.raw_formats:
                                if self.version + 'Albums/' not in self.window1.get_title() :
                                        filename = self.rawpath[item]
                                else:
                                        filename = item.replace('/thumb', '').replace('.thumb.jpg', '')
                                try:
                                        fname = os.path.split(filename)[1][:-len(format)]
                                        tempfile = os.getcwd() + '/.thumbnails/_' + fname + '.tiff'
                                        outfile = dest + '/'+fname + '.tiff'
                                        if os.path.isfile(outfile):
                                                self.overwrite_thumb = True
                                        tupla=(filename, tempfile)
					if camera_profile:
						tupla = (camera_profile,) + tupla
					if output_profile:
						tupla = (output_profile,) + tupla
                                        self.process(workflow, command, tupla, outfile, True, depth, None)
					self.overwrite_thumbnail(outfile) 
                                        os.remove(tempfile)
				except IOError:
                                        self.conversion_error(item)
                        else:
                                try:
                                        fname = os.path.split(item)[1][:-len(format)]
                                        outfile = dest + '/' + fname + '.tiff'
                                        if os.path.isfile(outfile):
                                                self.overwrite_thumb = True
                                        tupla=(0, item)
                                        self.process(workflow, None, tupla, outfile, None, depth, None)
					self.overwrite_thumbnail(outfile) 
                                except IOError:
                                        self.conversion_error(item)
                        gobject.idle_add(self.progressbar4.set_fraction,(self.progressbar4.get_fraction() + fraction))
                self.window6.hide()
		self.unselect(self)
                gobject.idle_add(self.progressbar4.set_fraction, 0)
                gobject.idle_add(self.win6_okbutton.set_sensitive, True)
                gobject.idle_add(self.checkbutton20.set_sensitive, True)
                gobject.idle_add(self.win6_cancelbutton.set_label, 'Cancel')
                gobject.idle_add(self.win6_cancelbutton.set_property, 'image', self.stock_cancel_img)
		self.stop_thread.clear()
		gtk.gdk.threads_leave()
		
        def convert_as_bmp(self, selected, dest):
		gtk.gdk.threads_enter()
                gobject.idle_add(self.win6_okbutton.set_sensitive, False)
                gobject.idle_add(self.checkbutton20.set_sensitive, False)
                gobject.idle_add(self.win6_cancelbutton.set_label, 'Stop')
                gobject.idle_add(self.win6_cancelbutton.set_property, 'image', self.stock_stop_img)
                n = 0
                fraction = 0.99 / len(selected)
		command, output_profile, camera_profile = self.make_dcraw_command()
		if self.checkbutton20.get_active() and self.workflow_copy:
                        workflow = self.workflow_copy
                else:
                        workflow = None
                for item in selected:
                        if self.stop_thread.isSet():
                                break
                        n += 1
                        gobject.idle_add(self.window6.set_title, ('Converting %s of %s files...' % (n, len(selected))))
                        format = os.path.splitext(item)[1]
                        if format.lower() in self.raw_formats:
                                if self.version + 'Albums/' not in self.window1.get_title() :
                                        filename = self.rawpath[item]
                                else:
                                        filename = item.replace('/thumb', '').replace('.thumb.jpg', '')
                                try:
                                        fname = os.path.split(filename)[1][:-len(format)]
                                        tempfile = os.getcwd() + '/.thumbnails/_' + fname + '.tiff'
					outfile = dest + '/' + fname + '.bmp'
					if os.path.isfile(outfile):
                                                self.overwrite_thumb = True
                                        tupla=(filename, tempfile)
					if camera_profile:
						tupla = (camera_profile,) + tupla
					if output_profile:
						tupla = (output_profile,) + tupla
                                        self.process(workflow, command, tupla, outfile, True, None, None)
					self.overwrite_thumbnail(outfile) 
                                        os.remove(tempfile)
                                except IOError:
                                        self.conversion_error(item)
                        else:
                                try:
                                        fname = os.path.split(item)[1][:-len(format)]
                                        outfile = dest + '/' + fname + '.bmp'
                                        if os.path.isfile(outfile):
                                                self.overwrite_thumb = True
                                        tupla = (0, item)
                                        self.process(workflow, None, tupla, outfile, False, None, None)
					self.overwrite_thumbnail(outfile) 
                                except IOError:
                                        self.conversion_error(item)
                        gobject.idle_add(self.progressbar4.set_fraction, (self.progressbar4.get_fraction() + fraction))
                self.window6.hide()
		self.unselect(self)
                gobject.idle_add(self.progressbar4.set_fraction, 0)
                gobject.idle_add(self.win6_okbutton.set_sensitive, True)
                gobject.idle_add(self.checkbutton20.set_sensitive, True)
                gobject.idle_add(self.win6_cancelbutton.set_label, 'Cancel')
                gobject.idle_add(self.win6_cancelbutton.set_property, 'image', self.stock_cancel_img)
		self.stop_thread.clear()
		gtk.gdk.threads_leave()
		   
        def statusbar_push(self, statusbar, context_id, text):
                statusbar.push(context_id, text)

        def statusbar_pop(self, statusbar, context_id):
                statusbar.pop(context_id)

        def set_statusbar2(self, image_size, filename):
                self.statusbar_pop(self.statusbar2, self.context_id2)
		text=' %s                          %.3f kb' % (image_size, os.path.getsize(filename) / 1000.0)
		self.statusbar_push(self.statusbar2, self.context_id2, text)

	def calculate_percentage(self):                 # Calculates zoom percentage
                try:
                        if self.window2.get_property('visible'):
				h = self.rect.height
                        	w = self.rect.width
                        	i = (h ** 2 + w ** 2) ** 0.5
				format = os.path.splitext(self.list[self.indice])[1]
                        	if format.lower() in self.raw_formats:
					if self.version + 'Albums/' not in self.window1.get_title() :
						filename = self.rawpath[self.list[self.indice]]
					else:
                                                filename = self.list[self.indice].replace('/thumb', '').replace('.thumb.jpg', '')
                        	else:
                                        filename = self.list[self.indice]
                        	status,output = commands.getstatusoutput('exiftool -s -ExifImageWidth -ExifImageLength -ImageWidth\
				 -ImageHeight "%s" ' % filename)
                        	if output:
                                	exif_list = output.split('\n')
                                	self.grep_image_size(exif_list)
                                	full_size = self.image_size.split('x')
                                	full_i = (int(full_size[0]) ** 2 + int(full_size[1]) ** 2) ** 0.5
                                	text = str(int((i / full_i) * 100)) + '%'
                                	self.statusbar_pop(self.statusbar1, self.context_id1)
                                	self.statusbar_push(self.statusbar1, self.context_id1, text)
                        else:
				h = self.rect2.height
                        	w = self.rect2.width
                        	i=(h ** 2 + w ** 2) ** 0.5
				format = os.path.splitext(self.list[self.indice])[1]
                        	if format.lower() in self.raw_formats:
					if self.version + 'Albums/' not in self.window1.get_title() :
						filename = self.rawpath[self.list[self.indice]]
					else:
                                                filename = self.list[self.indice].replace('/thumb', '').replace('.thumb.jpg', '')
                        	else:
                                        filename = self.list[self.indice]
                        	status,output = commands.getstatusoutput('exiftool -s -ExifImageWidth -ExifImageLength -ImageWidth\
			 	-ImageHeight "%s" ' % filename)
                        	if output:
                                	exif_list = output.split('\n')
                                	self.grep_image_size(exif_list)
                                	full_size = self.image_size.split('x')
                                	full_i=(int(full_size[0]) ** 2 + int(full_size[1]) ** 2) ** 0.5
                                	text = str(int((i / full_i) * 100)) + '%'
                                	self.statusbar_pop(self.statusbar4, self.context_id4)
                                	self.statusbar_push(self.statusbar4, self.context_id4, text)
                except:
                        pass
		
        def get_folder(self, treeview, path, view_column):   # Make a gallery double clicking a  
		self.vpaned2.handler_block(self.id27)        # folder in the directory tree      
                iter0 = self.treestore.get_iter(path)      
                n = 1
                percorso = self.treestore[path][1]
                while n < len(path):
                        iterparent = self.treestore.iter_parent(iter0)
                        pathparent = self.treestore.get_path(iterparent)
                        percorso = self.treestore[pathparent][1] + '/' + percorso
                        n += 1
			del iter0
			iter0 = iterparent.copy()
			del iterparent
                percorso = percorso[1:]
                viewport = self.scrolledwindow2.get_child()
		if viewport:
                        viewport.destroy()
		self.cartella = percorso
		self.window1.set_title(self.version + self.cartella)
		self.n = self.count_images(self)
		if self.n:
                        if self.radiobutton7.get_active():
                                self.make_bottom_panel(self, self.n)
			else:
                                self.make_table(self)
                                self.attach_images(self)
                                self.make_thumbnails(self.width, self.height, self.n)
			self.statusbar_pop(self.statusbar3, self.context_id3)
			self.statusbar_push(self.statusbar3, self.context_id3,\
                        'There are %s images     Total size %f MB' % (self.n, self.total_size / 1000000.0))
		else:
			self.statusbar_pop(self.statusbar3, self.context_id3)
                        self.statusbar_push(self.statusbar3, self.context_id3, 'There are %s images' % self.n)
			if self.radiobutton7.get_active():
                                self.hbox1.destroy()
                self.delete_selection1.set_sensitive(False)
                self.add_selection1.set_sensitive(True)
		self.selected=[]
		self.settings['last_folder_path'] = self.cartella[:]
		self.settings['switch'] = 'cartella'
       		self.vpaned2.handler_unblock(self.id27)
       		
	def expand_rows(self, treeview, iter_, path):       # Expands row appending children dynamically
                iter0 = iter_.copy()
                n = 1
                percorso = self.treestore[path][1]
                while n < len(path):
                        iterparent = self.treestore.iter_parent(iter0)
                        pathparent = self.treestore.get_path(iterparent)
                        percorso = self.treestore[pathparent][1] + '/' + percorso
                        n += 1
			del iter0
			iter0 = iterparent.copy()
			del iterparent
                percorso = percorso[1:]
                n_children = self.treestore.iter_n_children(iter_)
                x = 0
                while x < n_children:
                        iterchildren = self.treestore.iter_nth_child(iter_, x)
                        pathchildren = self.treestore.get_path(iterchildren)
                        childname = percorso + '/' + self.treestore[pathchildren][1]
                        filelist = glob.glob(childname + '/*')
                        for item in sorted(filelist):
                                if os.path.isdir(item):
                                        self.treestore.append(iterchildren, [self.folderpb, os.path.basename(item)] )
                        x += 1
                self.treeview2.set_model(self.treestore)
		
	def collapse_rows(self, treeview, iter_, path):
		n_children = self.treestore.iter_n_children(iter_)
                x = 0
                while x < n_children:
                        iterchildren = self.treestore.iter_nth_child(iter_, x)
                        pathchildren = self.treestore.get_path(iterchildren)
                        n_nipoti = self.treestore.iter_n_children(iterchildren)
                        lista = list(pathchildren)
                        n = 0
                        lista.append(n)
                        while n < n_nipoti:
                                lista[len(lista) - 1] = n_nipoti - 1
                                del self.treestore[tuple(lista)]
				n_nipoti -= 1
                        x += 1
                self.treeview2.set_model(self.treestore)
		
	def show_filechooserdialog1(self, event):
		self.vpaned2.handler_block(self.id27)
		self.filechooser.show()
		response = self.filechooser.run()
		if response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_DELETE_EVENT:
			self.filechooser.hide()
		elif response == gtk.RESPONSE_OK:
			viewport = self.scrolledwindow2.get_child()
			if viewport:
                                viewport.destroy()
			self.cartella = self.filechooser.get_current_folder()
			self.window1.set_title(self.version + self.cartella)
			self.filechooser.hide()
			while gtk.events_pending():
                                gtk.main_iteration(False)
			self.n = self.count_images(self)
			if self.n:
                                if self.radiobutton7.get_active():
                                        self.make_bottom_panel(self, self.n)
				else:
                                        self.make_table(self)
                                        self.attach_images(self)
                                        self.make_thumbnails(self.width, self.height, self.n)
				self.statusbar_pop(self.statusbar3, self.context_id3)
                                self.statusbar_push(self.statusbar3, self.context_id3,\
                                'There are %s images     Total size %f MB' % (self.n, self.total_size / 1000000.0))
			else:
                                self.statusbar_pop(self.statusbar3, self.context_id3)
                                self.statusbar_push(self.statusbar3, self.context_id3, 'There are %s images' % self.n)
				if self.radiobutton7.get_active():
                                        self.hbox1.destroy()
		self.delete_selection1.set_sensitive(False)
		self.add_selection1.set_sensitive(True)
		self.selected = []
		self.settings['last_folder_path'] = self.cartella[:]
		self.settings['switch'] = 'cartella'
		self.vpaned2.handler_unblock(self.id27)
		
	def open_last_folder(self, cartella):            # Opens last visited folder at start
		self.expand_to_path(cartella)
		self.vpaned2.handler_block(self.id27)
                self.cartella = cartella
                self.window1.set_title(self.version + self.cartella)
		self.n = self.count_images(self)
		if self.n:
                        if self.radiobutton7.get_active():
                                self.make_bottom_panel(self, self.n)
			else:
                                self.make_table(self)
                                self.attach_images(self)
                                self.make_thumbnails(self.width, self.height, self.n)
			self.statusbar_pop(self.statusbar3, self.context_id3)
                        self.statusbar_push(self.statusbar3, self.context_id3,\
                        'There are %s images     Total size %f MB '% (self.n, self.total_size / 1000000.0))
		else:
                        self.statusbar_pop(self.statusbar3, self.context_id3)
                        self.statusbar_push(self.statusbar3, self.context_id3, 'There are %s images' % self.n)
		self.delete_selection1.set_sensitive(False)
		self.add_selection1.set_sensitive(True)
		self.selected = []
		self.settings['last_folder_path'] = self.cartella[:]
		self.settings['switch'] = 'cartella'
		self.vpaned2.handler_unblock(self.id27)
		
	def expand_to_path(self, folder):                # Autoexpands the directory tree
		lista = folder.split('/')
		iter0 = self.treestore.get_iter_root()
		iter0 = self.treestore.iter_nth_child(iter0, 0)
		for item in lista[1:]:
			value = ''
                	while value != item:
                		value = self.treestore.get_value(iter0, 1)
                        	if value == item:
                                        break
                        	iter0 = self.treestore.iter_next(iter0)
			path0 = self.treestore.get_path(iter0)
			self.treeview2.expand_to_path(path0)
			iter0 = self.treestore.iter_nth_child(iter0, 0)
		column = self.treeview2.get_column(len(lista))
		self.treeview2.scroll_to_cell(path0, column, True, 0.5, 0.0)
		
	def album_control(self, event):                 # Controls for new files on album directory
                files = os.listdir(self.ark+self.album)
                filelist = []
                for item in files:
			if item == '_preview_.png':
                                continue
                        format = os.path.splitext(item)[1]
                        if format.lower() in self.raw_formats:
                                filelist += [self.ark + self.album + '/thumb/' + item[:-len(format)] + '.thumb.jpg' + format]
                        elif format.lower() in self.formats:
                                filelist += [self.ark + self.album + '/' + item]
                        else:
                                continue
                if len(filelist) != len(self.albums[self.album]):
                        self.label8.set_text('Attention! The %s archives has been modified!\nDo you want to update the album?'%self.album)
                        self.dialog14.show()
                        gtk.gdk.beep()
                        response = self.dialog14.run()
                        if response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_DELETE_EVENT:
                                self.dialog14.hide()
                        elif response == gtk.RESPONSE_OK:
                                self.dialog14.hide()
                                self.albums[self.album] = []
                                self.albums[self.album] = filelist

        def open_last_album(self, album):                # Opens last visited album at start
                try:
                        self.expand_to_path(self.settings['last_folder_path'])
		except:
                        pass
                self.album = album
                self.album_control(self)
		self.make_album_gallery(self)
		self.delete_selection1.set_sensitive(True)
                self.add_selection1.set_sensitive(True)
		self.selected = []
		self.settings['last_album_path'] = self.album[:]
		self.settings['switch'] = 'album'                        
                                
	def show_album(self, treeview, path, column):      # Makes gallery double clicking the album name.
                iter_ = self.model.get_iter(path)
		self.album = self.model.get_value(iter_,1)
		self.album_control(self)
		self.make_album_gallery(self)
		self.delete_selection1.set_sensitive(True)
                self.add_selection1.set_sensitive(True)
		self.selected = []
		self.settings['last_album_path'] = self.album[:]
		self.settings['switch'] = 'album'
		
	def make_album_gallery(self, event):
		self.vpaned2.handler_block(self.id27)
		self.window1.set_title(self.version + 'Albums/' + self.album)
                self.n = len(self.albums[self.album])
		files = self.albums[self.album]
		self.list = []
		self.total_size = 0
		total_size = self.total_size
		get_size = os.path.getsize
		get_format = os.path.splitext
		formats_ = self.formats
		raw_formats = self.raw_formats
		get_iptc_keywords = self.get_iptc_keywords
		if not self.checkbutton28.get_active():
			for infile in files:
                        	format = get_format(infile)[1]
				if format.lower() in self.formats:
					self.list += [infile]
					self.total_size += os.path.getsize(infile)
				else:
					self.list += [infile]
					f = infile.replace('thumb/', '').replace('.thumb.jpg', '')
					self.total_size += os.path.getsize(f)
		else:
			tag = self.combobox14.get_active_text()
                        tagged_list = []
			self.label163.set_text('')
			len_files = len(files)
			if len_files < 2:
				len_files = 1.0
			fraction = 0.99 / len_files
                        self.window9.show()
			while gtk.events_pending():
                        	gtk.main_iteration(False)
                        for item in files:
                                format = get_format(item)[1]
                                if format.lower() in formats_ + raw_formats:
					file = self.get_real_path(item)
                                        info_list = get_iptc_keywords(file, format)
                                        if tag in info_list:
                                        	tagged_list += [item]
                                        	total_size += get_size(file)
						self.label163.set_text('%s images found' % len(tagged_list))
				self.progressbar5.set_fraction(self.progressbar5.get_fraction() + fraction)
				while gtk.events_pending():
                        		gtk.main_iteration(False)
				if self.stop_progressbar5.isSet():
                                        break
			self.window9.hide()
			self.progressbar5.set_fraction(0)
                        self.total_size = total_size
                        self.list = tagged_list[:]
			self.stop_progressbar5.clear()	
		self.n = len(self.list)
		viewport = self.scrolledwindow2.get_child()
                if viewport:
                        viewport.destroy()
                if self.n > 0:
                        if self.radiobutton7.get_active():
                                self.make_bottom_panel(self, self.n)
			else:
                                self.make_table(self)
                                self.attach_images(self)
                                self.make_thumbnails(self.width, self.height, self.n)
                        self.statusbar_pop(self.statusbar3, self.context_id3)
			self.statusbar_push(self.statusbar3, self.context_id3,\
                        'There are %s images     Total size %f MB' % (self.n, self.total_size / 1000000.0))
                else:
			if self.radiobutton7.get_active():
                                self.hbox1.destroy()
			self.statusbar_pop(self.statusbar3, self.context_id3)
                        self.statusbar_push(self.statusbar3, self.context_id3, 'There are 0 images')
                self.vpaned2.handler_unblock(self.id27)
		
	def Open(self, event):
		self.treeiter = self.model.get_iter(self.path)
                self.album = self.model.get_value(self.treeiter,1)
                self.album_control(self)
                self.make_album_gallery(self)
                self.delete_selection1.set_sensitive(True)
                self.add_selection1.set_sensitive(True)
                self.settings['last_album_path'] = self.album[:]
		self.settings['switch'] = 'album'

        def open_album(self, event):
                self.dialog3.set_title('Open Album')
                self.label4.set_text('Choose the album to open')
                self.dialog3.show()
		response = self.dialog3.run()
		if response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_DELETE_EVENT:
                        self.dialog3.hide()
		elif response == gtk.RESPONSE_OK:
                        self.album = self.comboboxentry1.get_active_text()
                        if not self.album:
                                self.dialog3.hide()
                        else:
                                self.dialog3.hide()
                                self.album_control(self)
                                self.make_album_gallery(self)
                self.delete_selection1.set_sensitive(True)
                self.add_selection1.set_sensitive(True)
		self.selected = []
		self.settings['last_album_path'] = self.album[:]
		self.settings['switch'] = 'album'
                
	def add_album(self, event, data):			# Makes a new album 
		self.entry1.grab_focus()                            
                self.dialog1.show()
		response = self.dialog1.run()
		if response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_DELETE_EVENT:
			self.dialog1.hide()
			self.entry1.set_text('')
                        if data == 'button':
				self.add_selection(self)
				return False
		elif response == gtk.RESPONSE_OK:
                        self.added_album = self.entry1.get_text()
			if self.added_album.isspace() or not self.added_album:
			 	self.dialog1.hide()
                        	if data == 'button':
					self.add_selection(self)
					return False
                        elif self.albums.has_key(self.added_album):
                                gtk.gdk.beep()
                                self.dialog2.show()
                                response = self.dialog2.run()
                                if response == gtk.RESPONSE_CLOSE or response == gtk.RESPONSE_DELETE_EVENT:
                                        self.dialog2.hide()
                                        self.add_album(self, event)
                        else:
                                os.mkdir(self.ark + self.added_album)
                                os.mkdir(self.ark + self.added_album + '/thumb')
                                self.albums[self.added_album] = []
                                self.model.append([gtk.gdk.pixbuf_new_from_file('icons/no_preview.png'), self.added_album])
                                self.treeview1.set_model(self.model)
                                self.boxmodel.append([self.added_album])
                                self.comboboxentry1.set_model(self.boxmodel)
                                self.boxmodel2.append([self.added_album])
                                self.comboboxentry2.set_model(self.boxmodel2)
                                if self.comboboxentry1.get_text_column() != 0:
                                        self.comboboxentry1.set_text_column(0)
                                if self.comboboxentry2.get_text_column() != 0:
                                        self.comboboxentry2.set_text_column(0)
                                self.dialog1.hide()
				self.entry1.set_text('')
			return True
		
		
	def Delete(self, event):                                 #Deletes the album       
		self.treeiter = self.model.get_iter(self.path)
                album = self.model.get_value(self.treeiter, 1)
                self.dialog10.set_title('Delete Album')
                self.label9.set_text('Are you shure to delete\n %s ?' % album)
                self.dialog10.show()
                response = self.dialog10.run()
		if response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_DELETE_EVENT:
                        self.dialog10.hide()
		elif response == gtk.RESPONSE_OK:
                        if album in self.window1.get_title():
                                        viewport = self.scrolledwindow2.get_child()
					if viewport:
						viewport.destroy()
						self.statusbar_pop(self.statusbar3, self.context_id3)
                                                self.statusbar_push(self.statusbar3, self.context_id3, 'There are 0 images')
					if self.radiobutton7.get_active():
						self.hbox1.destroy()
						del self.b_event
						gc.collect()       
                        iter0 = self.model.get_iter_first()
                        value = ''
                        while value != album:
                                value = self.model.get_value(iter0, 1)
                                if value == album:
                                        break
                                iter0 = self.model.iter_next(iter0)
                        self.model.remove(iter0)
                        self.treeview1.set_model(self.model)
                        iter1 = self.boxmodel.get_iter_root()
                        value = ''
                        while value != album:
                                value = self.boxmodel.get_value(iter1, 0)
                                if value == album:
                                        break
                                iter1 = self.boxmodel.iter_next(iter1)
                        self.boxmodel.remove(iter1)
                        self.comboboxentry1.set_model(self.boxmodel)
                        self.boxentry.set_text('')
                        iter1 = self.boxmodel2.get_iter_root()
                        value = ''
                        while value != album:
                                value = self.boxmodel2.get_value(iter1, 0)
                                if value == album:
                                        break
                                iter1 = self.boxmodel2.iter_next(iter1)
                        self.boxmodel2.remove(iter1)
                        self.comboboxentry2.set_model(self.boxmodel2)
                        self.dialog10.hide()
                        del self.albums[album]
                        shutil.rmtree(self.ark + album, ignore_errors = True)
			self.n = 0
			self.list = []
                                        	
        def delete_album(self, event):                                   
                self.dialog3.set_title('Delete Album')
                self.label4.set_text('Choose the album to delete!')
                self.dialog3.show()
		response = self.dialog3.run()
		if response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_DELETE_EVENT:
                        self.dialog3.hide()
		elif response == gtk.RESPONSE_OK:
                        album = self.comboboxentry1.get_active_text()
                        if not album:
                                self.dialog3.hide()
                        else:
                                if album in self.window1.get_title():
                                        viewport = self.scrolledwindow2.get_child()
					if viewport:
						viewport.destroy()
						self.statusbar_pop(self.statusbar3, self.context_id3)
                                                self.statusbar_push(self.statusbar3, self.context_id3, 'There are 0 images')
					if self.radiobutton7.get_active:
						self.hbox1.destroy()
						del self.b_event
						gc.collect()                 
                                iter0 = self.model.get_iter_first()
                                value = ''
                                while value != album:
                                        value = self.model.get_value(iter0, 1)
                                        if value == album:
                                                break
                                        iter0 = self.model.iter_next(iter0)
                                self.model.remove(iter0)
                                self.treeview1.set_model(self.model)
                                iter1 = self.boxmodel.get_iter_root()
                                value = ''
                                while value != album:
                                        value = self.boxmodel.get_value(iter1, 0)
                                        if value == album:
                                                break
                                        iter1 = self.boxmodel.iter_next(iter1)
                                self.boxmodel.remove(iter1)
                                self.comboboxentry1.set_model(self.boxmodel)
                                self.boxentry.set_text('')
                                iter1 = self.boxmodel2.get_iter_root()
                                value = ''
                                while value != album:
                                        value = self.boxmodel2.get_value(iter1, 0)
                                        if value == album:
                                                break
                                        iter1 = self.boxmodel2.iter_next(iter1)
                                self.boxmodel2.remove(iter1)
                                self.comboboxentry2.set_model(self.boxmodel2)
                                self.dialog3.hide()
                                del self.albums[album]
                                shutil.rmtree(self.ark+album, ignore_errors = True)
				self.n = 0
				self.list = []
        
        def rename_album(self, event):                                        
		self.treeiter = self.model.get_iter(self.path)
                album = self.model.get_value(self.treeiter, 1)
                self.label10.set_text('Insert a new name for\n %s' % album)
		self.entry2.grab_focus()
                self.dialog11.show()
                response = self.dialog11.run()
		if response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_DELETE_EVENT:
                        self.dialog11.hide()
		elif response == gtk.RESPONSE_OK:
                        new_name = self.entry2.get_text()
			if new_name.isspace() or not new_name:
                                self.dialog11.hide()
                        elif self.albums.has_key(new_name):
                                gtk.gdk.beep()
                                self.dialog2.show()
                                response = self.dialog2.run()
                                if response == gtk.RESPONSE_CLOSE or response == gtk.RESPONSE_DELETE_EVENT:
                                        self.dialog2.hide()
                                        self.rename_album(self)
                        else:
                        	self.dialog11.hide()
                        	self.entry2.set_text('')
                        	temp = self.albums[album]
				os.rename(self.ark + album, self.ark + new_name)
				del self.albums[album]
				n = 0
				while n < len(temp):
					item = temp[0]
					del temp[0]
					temp.append(item.replace(self.ark + album, self.ark + new_name))
					n += 1
				self.albums[new_name] = temp
                        	self.model.remove(self.treeiter)
                        	iter1 = self.boxmodel.get_iter_root()
                        	value = ''
                        	while value != album:
                                	value = self.boxmodel.get_value(iter1, 0)
                                	if value == album:
                                                break
                                	iter1 = self.boxmodel.iter_next(iter1)
                        	self.boxmodel.remove(iter1)
                        	self.boxentry.set_text('')
                        	iter1 = self.boxmodel2.get_iter_root()
                        	value = ''
                       		while value != album:
                                	value = self.boxmodel2.get_value(iter1, 0)
                                	if value == album:
                                                break
                                	iter1 = self.boxmodel2.iter_next(iter1)
                        	self.boxmodel2.remove(iter1)
                        	try:
                                        self.model.append([gtk.gdk.pixbuf_new_from_file(self.ark + new_name + '/_preview_.png'),new_name])
                                except:
                                        self.model.append([gtk.gdk.pixbuf_new_from_file('icons/no_preview.png'), new_name])
				self.boxmodel.append([new_name])
				self.boxmodel2.append([new_name])
                        	self.comboboxentry1.set_model(self.boxmodel)
                        	self.comboboxentry2.set_model(self.boxmodel2)
				self.treeview1.set_model(self.model)
				self.window1.set_title(self.version + 'Albums/' + new_name)

	def set_panel(self, event, data):         # Hides and shows the left panel
		self.vpaned2.handler_block(self.id27)
		if self.scrolledwindow6:
                        self.scrolledwindow6.destroy()
		if data == 'hide':
                	self.hpaned1.set_position(0)
			self.close_panel = False
		elif data == 'show':
			self.hpaned1.set_position(int(gtk.gdk.screen_width() * 0.15))
		if self.radiobutton7.get_active():
                	viewport = self.scrolledwindow2.get_child()
			if viewport:
				viewport.destroy()
				if self.n:
					self.make_table(self)
					self.attach_images(self)
					self.make_thumbnails(self.width, self.height, self.n)
		self.vpaned2.handler_unblock(self.id27)
		self.radiobutton6.set_active(True)
		self.settings['radiobutton6'] = True
		self.settings['radiobutton7'] = False
		
	def hide_pane(self, event):
		if self.radiobutton6.get_active():
			self.close_panel = True
			self.vpaned2.handler_block(self.id27)	
			self.hpaned1.set_position(0)
			self.vpaned2.handler_unblock(self.id27)
			self.make_bottom_panel(self, self.n)
		else:	
			self.vpaned2.handler_block(self.id27)	
			self.hpaned1.set_position(0)
			self.vpaned2.handler_unblock(self.id27)
		
				                                   
	def enlarge_gallery(self, event):
                if self.radiobutton7.get_active():
			self.zoom_out_photo(self, 1)
			return True
		if self.width == 260:
                        return True
		viewport = self.scrolledwindow2.get_child()
		if viewport:
			viewport.destroy()
			if self.n:
				if self.width == 150:
					self.width = 201
					self.height = 134
				elif self.width == 201:
					self.width = 260
					self.height = 174 
				self.make_table(self)
				self.attach_images(self)
				self.make_thumbnails(self.width, self.height, self.n)
              	
	def reduce_gallery(self, event):
                if self.radiobutton7.get_active():
			self.zoom_in_photo(self,1)
			return True
		if self.width == 150:
                        return True
		viewport = self.scrolledwindow2.get_child()
		if viewport:
			viewport.destroy()
			if self.n:
				if self.width == 260:
					self.width = 201
					self.height = 134
				elif self.width == 201:
					self.width = 150
					self.height = 100 
				self.make_table(self)
				self.attach_images(self)
				self.make_thumbnails(self.width, self.height, self.n)
              		
	def select_all(self, event):
                viewport = self.scrolledwindow2.get_child()
		if viewport:
			for indice in xrange(self.n):
                                label = self.e[indice].get_child()
                                filename = label.get_text()
                                format = os.path.splitext(filename)[1]
                        	if self.version + 'Albums/' not in self.window1.get_title():
                                        if format.lower() not in self.raw_formats:
                                                filename = self.cartella + '/' + filename
                                                if filename not in self.selected:
                                                        self.e[indice].modify_bg(gtk.STATE_NORMAL, self.selection_color)
                                                        self.selected += [filename]
                                        else:
                                                filename = self.temp + filename[:-len(format)] + '.thumb.jpg' + format
                                                if filename not in self.selected:
                                                        self.e[indice].modify_bg(gtk.STATE_NORMAL, self.selection_color)
                                                        self.selected += [filename]

                        	else:
                               		for item in self.albums[self.album]:    
                                        	if format.lower() in self.raw_formats:
                                                        if filename[:-len(format)] in item:
                                                                filename = item[:]
                                                                break
                                                elif filename in item:
                                                        filename = item[:]
                                                        break
                                                else:
                                                        continue
                                	if filename not in self.selected:
                                        	self.e[indice].modify_bg(gtk.STATE_NORMAL, self.selection_color)
                                        	self.selected += [filename]
                                                
        def unselect(self,event):
                if self.selected:
                        for indice in xrange(self.n):
                                self.e[indice].modify_bg(gtk.STATE_NORMAL, self.colorbutton1.get_color())
                        self.selected = []

        def inverted_selection(self, event):    
                if not self.selected: 
			self.select_all(self)
                else:
                        selected = self.selected[:]
                        self.select_all(self)
                        for item in selected:
                                format = os.path.splitext(item)[1]
                                if format.lower() in self.raw_formats:
                                        filename = os.path.split(item)[1].replace('.thumb.jpg', '')
                                else:  
					filename = os.path.split(item)[1]
                                for indice in xrange(self.n):
                                        label = self.e[indice].get_child()
                                        fname = label.get_text()
                                        if fname == filename:
                                                self.e[indice].modify_bg(gtk.STATE_NORMAL, self.colorbutton1.get_color())
                                                del self.selected[self.selected.index(item)]
                                                break
                                        else:   
						continue
                                                                	
	def fullscreen_mode(self, *obj):
		if not self.n: 
			return True
		if not self.window2.get_property('visible'):
			if self.radiobutton6.get_active(): 
				self.indice = 0
			indice = self.indice
			self.old_indice = indice
		self.fullpbindex = 1
		self.window3.set_size_request(gtk.gdk.screen_width(), gtk.gdk.screen_height())
		self.window3.fullscreen()
		width, height = self.window3.get_size()
		format = os.path.splitext(self.list[self.indice])[1]
		if format.lower() in self.raw_formats:
			if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
				self.fullpblist[1] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice][:-len(format)], height, width)
				self.fullpblist[1] = self.fullpblist[1].rotate_simple(self.rotated[self.indice])	
			else:
				self.fullpblist[1] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice][:-len(format)], width, height)
		else:
			if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
				self.fullpblist[1] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice], height, width)
				self.fullpblist[1] = self.fullpblist[1].rotate_simple(self.rotated[self.indice])	
			else:
				self.fullpblist[1] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice], width, height)
		self.image2.set_from_pixbuf(self.fullpblist[1])
		self.window3.show_all()
		while gtk.events_pending():
                        gtk.main_iteration(False)
		gc.collect()
		thread.start_new_thread(self.load_cache, (width, height, 'fullscreen'))

	def player(self, *data):           # starts the player
		options = ['-q'] + [self.sample] * 30 + ["-t", "ossdsp", "-w", "-s", "/dev/dsp"]
                self.pid = os.fork()
                if self.pid == 0:
			try:
                		os.execvp("sox", options)
			except:  
				print 'Error trying to execute sox'
                elif self.pid > 0: 
			pass
                else: 
			print 'fork error'

	def slideshow(self, *data):
		if self.list:
			if len(data) == 3:
				if self.radiobutton6.get_active():
                                        self.indice = 0
				self.loop = data[1]
				indice = self.indice
				self.old_indice = indice
				if self.checkbutton6.get_active() and self.sample:
					self.player(self, *data)
			if len(data) == 2:
				self.loop = data[1]
				indice = self.indice
				self.win2_indice = indice
				if self.checkbutton6.get_active() and self.sample:
					self.player(self, *data)
			if self.loop:
				self.window4.set_size_request(gtk.gdk.screen_width(), gtk.gdk.screen_height())
				self.window4.fullscreen()
				width, height = self.window4.get_size()
				if not self.pixbuf1 or not self.checkbutton5.get_active():
					format = os.path.splitext(self.list[self.indice])[1]
					if format.lower() in self.raw_formats:
						if not self.rotated.has_key(self.indice):
                                			self.pixbuf1 = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice]\
							[:-len(format)], width, height)
						else:
							self.pixbuf1 = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice]\
							[:-len(format)], height, width)
							self.pixbuf1 = self.pixbuf1.rotate_simple(self.rotated[self.indice])
                        		else:
						if not self.rotated.has_key(self.indice):   
							self.pixbuf1 = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice],\
							width, height)
						else:   
							self.pixbuf1 = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice],\
							height, width)
							self.pixbuf1 = self.pixbuf1.rotate_simple(self.rotated[self.indice])
					width1 = self.pixbuf1.get_width()
                			height1 = self.pixbuf1.get_height()
                			nero = self.background.copy()
					if self.pixbuf1.get_has_alpha():
						nero = nero.add_alpha(False, chr(255), chr(255), chr(255))
                			self.pixbuf1.copy_area(0, 0, width1, height1, nero, (width - width1) / 2,(height - height1)/2)
                			self.pixbuf1 = nero.copy()
                			del nero
					gc.collect()
				self.image4.set_from_pixbuf(self.pixbuf1)
				self.window4.show_all()
				while gtk.events_pending():
                                        gtk.main_iteration(False)
				t1 = time.time()
				if self.indice == len(self.list) - 1:
                                        self.indice = -1
				format = os.path.splitext(self.list[self.indice + 1])[1]
				if format.lower() in self.raw_formats:
					if not self.rotated.has_key(self.indice + 1):
                                		pixbuf2 = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice + 1][:-len(format)],\
                                		width, height)
					else:
						pixbuf2 = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice + 1][:-len(format)],\
                                		height, width)
						pixbuf2 = pixbuf2.rotate_simple(self.rotated[self.indice+1])
                        	else:   
					if not self.rotated.has_key(self.indice + 1):
						pixbuf2 = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice + 1], width, height)
					else:
						pixbuf2 = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice + 1], height, width)
						pixbuf2 = pixbuf2.rotate_simple(self.rotated[self.indice + 1])
				while gtk.events_pending():
                                        gtk.main_iteration(False)
                                t2 = time.time()
                                delay = t2 - t1
                                pause = self.pause
                                if delay > pause: delay = pause
				for i in xrange(100):
					time.sleep((pause - delay) / 100.0)
					while gtk.events_pending():
                                                gtk.main_iteration(False)
					if self.loop == 0:
						self.pixbuf1 = 0
						del pixbuf2
						gc.collect()
						return True 
				if self.checkbutton5.get_active():
                                        self.pixbuf1 = self.fading_transition(self.pixbuf1, pixbuf2, width, height,\
					self.pixbuf1.get_width(), self.pixbuf1.get_height())
                                        if not self.pixbuf1:
                                                return True
				self.image4.set_from_pixbuf(pixbuf2)
				self.window4.show_all()
				while gtk.events_pending():
                                        gtk.main_iteration(False)
				del pixbuf2
				gc.collect()
				self.indice += 1
				if self.indice >= len(self.list) - 1:
                                        self.indice = -1
				gobject.timeout_add(1, self.slideshow)
			else:
				self.pixbuf1 = 0
				gc.collect()

	def fading_transition(self, pixbuf1, pixbuf2, width, height, width1, height1):
                width2 = pixbuf2.get_width()
		height2 = pixbuf2.get_height()
                nero = self.background.copy()
		if pixbuf2.get_has_alpha():
			nero = nero.add_alpha(False, chr(255), chr(255), chr(255))
		pixbuf2.copy_area(0, 0, width2, height2, nero, (width - width2) / 2, (height - height2) / 2)
		pixbuf2 = nero.copy()
		del nero
		gc.collect()
		n = 255 / self.frames
		alpha = 255 - n
		for i in xrange(self.frames):
			if self.loop == 0:
				pixbuf1 = 0
				gc.collect()
				return pixbuf1
			transition = pixbuf2.copy()
			pixbuf1.composite(transition, 0, 0, width1, height1, 0, 0, 1.0, 1.0, gtk.gdk.INTERP_BILINEAR, alpha)
			self.image4.set_from_pixbuf(transition)
			self.window4.show_all()
			while gtk.events_pending():
                                gtk.main_iteration(False)
			alpha -= n
			pixbuf1 = transition.copy()
			time.sleep(self.delay)
		del transition
		gc.collect()
		return pixbuf2

        def set_image1(self, format):
		if self.workflow_started:
				if self.show_dialog21():
                                        return True	
		if format.lower() in self.raw_formats:
                        self._label = os.path.split(self.list[self.indice])[1].replace('.thumb.jpg', '')
                        self.window2.set_title(self.window1.get_title() + '/' + self._label)
                        if self.notebook2.get_current_page() == 0:
				if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
					self.pblist[1] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice][:-len(format)],\
                                	self.rect.height, self.rect.width)
					self.pblist[1] = self.pblist[1].rotate_simple(self.rotated[self.indice])
				else:
					self.pblist[1] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice][:-len(format)],\
                                	self.rect.width, self.rect.height)	
                                
                        else:
				gobject.idle_add(self.load_raw_preview, self.rect.width, self.rect.height)
				self.set_sensitivity(format)
				if self.notebook2.get_current_page() == 1:
                        		self.show_tags(format)
                                return True
		else:
                        self._label = os.path.split(self.list[self.indice])[1]
                        self.window2.set_title(self.window1.get_title() + '/' + self._label)
			if self.rotated.has_key(self.indice) and self.checkbutton2.get_active() and self.notebook2.get_current_page()==0:
				self.pblist[1] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice],\
                                self.rect.height, self.rect.width)
				self.pblist[1] = self.pblist[1].rotate_simple(self.rotated[self.indice])
			else:	
                        	self.pblist[1] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice],\
                        	self.rect.width, self.rect.height)
		self.pblist[1] = self.check_icons(format, self.pblist[1])
                if self.expander17.get_expanded():
			width = self.pblist[self.pbindex].get_width()
			height = self.pblist[self.pbindex].get_height()
			self.drawable.draw_pixbuf(self.gc, self.pblist[self.pbindex], 0, 0, int((self.rect.width - width) / 2),\
			int((self.rect.height - height) / 2))
			self.drawing_area.queue_draw()
			self.set_zoom_sensitivity(False)
		elif self.expander8.get_expanded():
			self.draw_grid(False)
		else:
                	self.image1.set_from_pixbuf(self.pblist[self.pbindex])
			self.image1.show()
			self.set_sensitivity(format)
		while gtk.events_pending():
                        gtk.main_iteration(False)
		if self.notebook2.get_current_page() == 3:
                        self.get_channel()
                elif self.notebook2.get_current_page() == 1:
                        self.show_tags(format)
		self.calculate_percentage()
		self.raw_preview = False
		
	def set_image2(self, format):
		if format.lower() in self.raw_formats:
                        self._label = os.path.split(self.list[self.indice])[1].replace('.thumb.jpg', '')
			if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
				self.b_pixlist[1] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice][:-len(format)],\
                        	self.rect2.height - self.swin2_label.allocation.height, self.rect2.width)
				self.b_pixlist[1] = self.b_pixlist[1].rotate_simple(self.rotated[self.indice])
			else:
                        	self.b_pixlist[1] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice][:-len(format)],\
                        	self.rect2.width, self.rect2.height - self.swin2_label.allocation.height)
		else:
                        self._label = os.path.split(self.list[self.indice])[1]
			if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
				self.b_pixlist[1] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice],\
                        	self.rect2.height - self.swin2_label.allocation.height, self.rect2.width)
				self.b_pixlist[1] = self.b_pixlist[1].rotate_simple(self.rotated[self.indice])
			else:
                        	self.b_pixlist[1] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice],\
                        	self.rect2.width, self.rect2.height - self.swin2_label.allocation.height)
		self.b_pixlist[1] = self.check_icons(format, self.b_pixlist[1])
                self.swin2_image.set_from_pixbuf(self.b_pixlist[1])
		self.scroll_to_selection(self)
		while gtk.events_pending():
                        gtk.main_iteration(False)
		self.calculate_percentage()
               
	def set_pixbuf(self, format, pbindex):
		if self.workflow_started:
				if self.show_dialog21():
                                        return True	
                if format.lower() in self.raw_formats:
                        self._label = os.path.split(self.list[self.indice])[1].replace('.thumb.jpg', '')
                        self.window2.set_title(self.window1.get_title()+ '/' + self._label)
                        if self.notebook2.get_current_page() != 0:
			 	gobject.idle_add(self.load_raw_preview, self.rect.width, self.rect.height)
				self.set_sensitivity(format)
				if self.notebook2.get_current_page() == 1:
                        		self.show_tags(format)
                                return True
		else:
                        self._label = os.path.split(self.list[self.indice])[1]
                        self.window2.set_title(self.window1.get_title() + '/' + self._label)
			if self.rotated.has_key(self.indice) and self.notebook2.get_current_page()!=0:
				self.pblist[pbindex] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice],\
                                self.rect.width, self.rect.height)
		self.pblist[pbindex] = self.check_icons(format, self.pblist[pbindex])
		if self.expander17.get_expanded():
			width = self.pblist[self.pbindex].get_width()
			height = self.pblist[self.pbindex].get_height()
			self.drawable.draw_pixbuf(self.gc, self.pblist[self.pbindex], 0, 0, int((self.rect.width - width) / 2),\
			int((self.rect.height - height) / 2))
			self.drawing_area.queue_draw()
			self.set_zoom_sensitivity(False)
		elif self.expander8.get_expanded():
			self.draw_grid(False)
		else:
                	self.image1.set_from_pixbuf(self.pblist[self.pbindex])
			self.image1.show()
			self.set_sensitivity(format)
		while gtk.events_pending(): 
			gtk.main_iteration(False)	
		self.calculate_percentage()
		if self.notebook2.get_current_page() == 3: 
			self.get_channel()
		elif self.notebook2.get_current_page() == 1:
                        self.show_tags(format)
		self.raw_preview = False
		if self.pblist[pbindex].get_width() != self.rect.width: 
			self.zoom_fit_photo(self, 0)
		
	def set_b_pixbuf(self, format, pixindex):
		self.b_pixlist[pixindex] = self.check_icons(format,self.b_pixlist[pixindex])
		self.swin2_image.set_from_pixbuf(self.b_pixlist[pixindex])
		self.swin2_label.set_text(self.label[self.indice].get_text())
		self.scroll_to_selection(self)
		while gtk.events_pending():
                        gtk.main_iteration(False)
		if self.b_pixlist[pixindex].get_width() != self.rect2.width:
                        self.zoom_fit_photo(self, 1)
		self.calculate_percentage()
                        
	def cache_pixbuf(self, pbindex, indice):          # Preloads pixbuf on detailed window
		if indice in xrange(self.n):
			if pbindex > 2:
                                pbindex = 0
			if pbindex < 0:
                                pbindex = 2
			format = os.path.splitext(self.list[indice])[1]
			if format.lower() in self.raw_formats:
				if self.rotated.has_key(indice) and self.checkbutton2.get_active():
					self.pblist[pbindex] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[indice][:-len(format)],\
                                	self.rect.height, self.rect.width)
					self.pblist[pbindex] = self.pblist[pbindex].rotate_simple(self.rotated[indice])
				else:
					self.pblist[pbindex] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[indice][:-len(format)],\
                                	self.rect.width, self.rect.height)		
			else:
				if self.rotated.has_key(indice) and self.checkbutton2.get_active():
					self.pblist[pbindex] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[indice],\
					self.rect.height, self.rect.width)
					self.pblist[pbindex] = self.pblist[pbindex].rotate_simple(self.rotated[indice])
				else:	
					self.pblist[pbindex] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[indice],\
					self.rect.width, self.rect.height)
		self.lock.release()

	def cache_b_pixbuf(self, pixindex, indice):	# Preloads pixbuf on detailed window
		if indice in xrange(self.n):
			if pixindex > 2:
                                pixindex = 0
			if pixindex < 0:
                                pixindex = 2
			format = os.path.splitext(self.list[indice])[1]
			if format.lower() in self.raw_formats:
				if self.rotated.has_key(indice) and self.checkbutton2.get_active():	
                			self.b_pixlist[pixindex] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[indice]\
                                	[:-len(format)], self.rect2.height - self.swin2_label.allocation.height, self.rect2.width)
					self.b_pixlist[pixindex] = self.b_pixlist[pixindex].rotate_simple(self.rotated[indice])
				else:
					self.b_pixlist[pixindex] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[indice]\
                                	[:-len(format)], self.rect2.width, self.rect2.height - self.swin2_label.allocation.height)
			else:
				if self.rotated.has_key(indice) and self.checkbutton2.get_active():
					self.b_pixlist[pixindex]=gtk.gdk.pixbuf_new_from_file_at_size(self.list[indice],\
					self.rect2.height - self.swin2_label.allocation.height, self.rect2.width)
					self.b_pixlist[pixindex] = self.b_pixlist[pixindex].rotate_simple(self.rotated[indice])	
				else:
					self.b_pixlist[pixindex] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[indice],\
					self.rect2.width, self.rect2.height - self.swin2_label.allocation.height)
		self.lock2.release()
		
	def cache_fullpixbuf(self, fullpbindex, indice):          # Preloads pixbuf on fullscreen mode
		if indice in xrange(self.n):
			if fullpbindex > 2:
                                fullpbindex = 0
			elif fullpbindex < 0:
                                fullpbindex = 2
			format = os.path.splitext(self.list[indice])[1]
			if format.lower() in self.raw_formats:
				if self.rotated.has_key(indice) and self.checkbutton2.get_active():
					self.fullpblist[fullpbindex] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[indice]\
					[:-len(format)], gtk.gdk.screen_height(),gtk.gdk.screen_width())
					self.fullpblist[fullpbindex] = self.fullpblist[fullpbindex].rotate_simple(self.rotated[indice])
				else:	
                			self.fullpblist[fullpbindex] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[indice]\
					[:-len(format)], gtk.gdk.screen_width(), gtk.gdk.screen_height())
			else:
				if self.rotated.has_key(indice) and self.checkbutton2.get_active():
					self.fullpblist[fullpbindex] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[indice],\
					gtk.gdk.screen_height(), gtk.gdk.screen_width())
					self.fullpblist[fullpbindex] = self.fullpblist[fullpbindex].rotate_simple(self.rotated[indice])
				else:
					self.fullpblist[fullpbindex] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[indice],\
					gtk.gdk.screen_width(), gtk.gdk.screen_height())
		self.lock.release()
		
       	def add_dimensions(self, format, label):        # Adds image dimensions on the statusbar
		if format.lower() in self.raw_formats and self.ark not in self.list[self.indice]:
			self.display_exif(self.rawpath[self.list[self.indice]], label)
			if self.image_size:
                                self.set_statusbar2(self.image_size, self.rawpath[self.list[self.indice]])
                        else:
                                self.set_statusbar2('', self.list[self.indice][:-len(format)])
		elif format.lower() in self.raw_formats and self.ark in self.list[self.indice]:
                        filename = self.list[self.indice].replace('/thumb', '').replace('.thumb.jpg', '')
                        self.display_exif(filename, label)
                        if self.image_size:
                                self.set_statusbar2(self.image_size, filename)
                        else:
                                self.set_statusbar2('', filename)
		else:
                        try:
                                self.display_exif(self.list[self.indice], label)
                                if self.image_size:
                                        self.set_statusbar2(self.image_size, self.list[self.indice])
                                else:
                                        self.set_statusbar2('', self.list[self.indice])
                        except:
                                self.exifmodel.clear()
				
	def first_photo(self, event):
		if not self.lock.locked():
			self.lock.acquire()
                	self.pbindex = 1
                	self.indice = 0
			format = os.path.splitext(self.list[self.indice])[1]
                	self.set_image1(format)
                	while gtk.events_pending():
                                gtk.main_iteration(False)
       			if format.lower() in self.raw_formats and self.notebook2.get_current_page() != 0:
				pass
			else:
       				self.add_dimensions(format, self._label)
       			self.count = 0
       			while gtk.events_pending():
                                gtk.main_iteration(False)
       			thread.start_new_thread(self.cache_pixbuf, (self.pbindex + 1, self.indice + 1))
		
	def first_b_photo(self, event):
		if not self.lock2.locked() and self.n > 0:
			self.lock2.acquire()
                	self.pixindex = 1
                	self.indice = 0
			for i in xrange(self.n):
                        	self.b_event[i].modify_bg(gtk.STATE_NORMAL, self.gallery_color)
			self.b_event[self.indice].modify_bg(gtk.STATE_NORMAL, self.selection_color)
			while gtk.events_pending():
                                gtk.main_iteration(False)
			format = os.path.splitext(self.list[self.indice])[1]
                	self.set_image2(format)
                	while gtk.events_pending():
                                gtk.main_iteration(False)
       			self.count = 0
       			thread.start_new_thread(self.cache_b_pixbuf, (self.pixindex + 1, self.indice + 1))
		
	def last_photo(self, event):
		if not self.lock.locked():
			self.lock.acquire()
                	self.pbindex = 1
                	self.indice = len(self.list) - 1
			format = os.path.splitext(self.list[self.indice])[1]
                	self.set_image1(format)
                	while gtk.events_pending(): 
				gtk.main_iteration(False)
       			if format.lower() in self.raw_formats and self.notebook2.get_current_page() != 0:
				pass
			else:
       				self.add_dimensions(format, self._label)
       			self.count = 0
       			thread.start_new_thread(self.cache_pixbuf,(self.pbindex - 1, self.indice - 1))
		
	def last_b_photo(self, event):
		if not self.lock2.locked() and self.n > 0:
			self.lock2.acquire()
                	self.pixindex = 1
                	self.indice = len(self.list) - 1
			for i in xrange(self.n):
                        	self.b_event[i].modify_bg(gtk.STATE_NORMAL, self.gallery_color)
			self.b_event[self.indice].modify_bg(gtk.STATE_NORMAL, self.selection_color)
			while gtk.events_pending():
                                gtk.main_iteration(False)
			format = os.path.splitext(self.list[self.indice])[1]
                	self.set_image2(format)
                	while gtk.events_pending():
                                gtk.main_iteration(False)
       			self.count = 0
       			thread.start_new_thread(self.cache_b_pixbuf,(self.pixindex - 1, self.indice - 1))
	
	def previous_photo(self, event):
		if not self.lock.locked():
			self.count = 0
			if self.indice > 0:
				self.lock.acquire()
				self.indice -= 1
				self.previous_index = self.pbindex
				if self.pbindex > 0:
                                        self.pbindex -= 1
                        	else:
                                        self.pbindex = 2
				format = os.path.splitext(self.list[self.indice])[1]
				self.set_pixbuf(format, self.pbindex)
				while gtk.events_pending(): 
					gtk.main_iteration(False)
				if format.lower() in self.raw_formats and self.notebook2.get_current_page() != 0:
					pass
				else:
       					self.add_dimensions(format, self._label)
       				thread.start_new_thread(self.cache_pixbuf, (self.pbindex - 1, self.indice - 1))

	def previous_b_photo(self, event):
		if not self.lock2.locked():
			self.count = 0
			if self.indice > 0:
				self.lock2.acquire()
				self.indice -= 1
				for i in xrange(self.n):
                                	self.b_event[i].modify_bg(gtk.STATE_NORMAL, self.gallery_color)
				self.b_event[self.indice].modify_bg(gtk.STATE_NORMAL, self.selection_color)
				while gtk.events_pending():
                                        gtk.main_iteration(False)
				if self.pixindex > 0:
                                        self.pixindex -= 1
                        	else:
                                        self.pixindex = 2
				format = os.path.splitext(self.list[self.indice])[1]
				self.set_b_pixbuf(format, self.pixindex)
       				thread.start_new_thread(self.cache_b_pixbuf, (self.pixindex - 1, self.indice - 1))

	def next_photo(self, event):
		if not self.lock.locked():
			self.count = 0
			if self.indice < len(self.list) - 1:
				self.lock.acquire()
				self.indice += 1
				self.previous_index = self.pbindex
				if self.pbindex < 2:
                                        self.pbindex += 1
                        	else:
                                        self.pbindex = 0
				format = os.path.splitext(self.list[self.indice])[1]
				self.set_pixbuf(format, self.pbindex)
				while gtk.events_pending(): 
					gtk.main_iteration(False)
       				if format.lower() in self.raw_formats and self.notebook2.get_current_page() != 0:
					pass
				else:
       					self.add_dimensions(format, self._label)
       				thread.start_new_thread(self.cache_pixbuf, (self.pbindex + 1, self.indice + 1))

	def next_b_photo(self, event):
		if not self.lock2.locked():
			self.count = 0
			if self.indice < len(self.list) - 1:
				self.lock2.acquire()
				self.indice += 1
				for i in xrange(self.n):
                                        self.b_event[i].modify_bg(gtk.STATE_NORMAL, self.gallery_color)
				self.b_event[self.indice].modify_bg(gtk.STATE_NORMAL, self.selection_color)
				while gtk.events_pending():
                                        gtk.main_iteration(False)
				if self.pixindex < 2:
                                        self.pixindex += 1
                        	else:
                                        self.pixindex = 0
				format = os.path.splitext(self.list[self.indice])[1]
				self.set_b_pixbuf(format, self.pixindex)
       				thread.start_new_thread(self.cache_b_pixbuf, (self.pixindex + 1, self.indice + 1))

	def previous_fullphoto(self, event):
		if not self.lock.locked():
                	if self.indice > 0:
				self.lock.acquire()
				self.indice -= 1
				if self.fullpbindex > 0:
                                        self.fullpbindex -= 1
                        	else:
                                        self.fullpbindex = 2
				self.image2.set_from_pixbuf(self.fullpblist[self.fullpbindex])
       				thread.start_new_thread(self.cache_fullpixbuf,(self.fullpbindex - 1, self.indice - 1))	

	def next_fullphoto(self, event):
		if not self.lock.locked():
			if self.indice < len(self.list) - 1:
				self.lock.acquire()
				self.indice += 1
				if self.fullpbindex < 2:
                                        self.fullpbindex += 1
                        	else:
                                        self.fullpbindex = 0
				self.image2.set_from_pixbuf(self.fullpblist[self.fullpbindex])
       				thread.start_new_thread(self.cache_fullpixbuf,(self.fullpbindex + 1, self.indice + 1))	
		
	def zoom_in_photo(self, event, data):
		while gtk.events_pending():
                        gtk.main_iteration(False)
		if not self.n:
                        return True
		self.toolbutton6.handler_block(self.id35)
                self.toolbutton7.handler_block(self.id36)
		self.toolbutton8.handler_block(self.id37)
		self.toolbutton9.handler_block(self.id38)
                self.toolbutton16.handler_block(self.id1)
                self.toolbutton17.handler_block(self.id2)
		self.count = 0
		format = os.path.splitext(self.list[self.indice])[1]
		if not data:
                        self.rect.width -= (self.rect.width / 100) * 25
			self.rect.height -= (self.rect.height / 100) * 25
			if self.rect.height < 100:
				self.rect.width = 150
				self.rect.height = 100
                        rect_width = self.rect.width
                        rect_height = self.rect.height
                else:
                        self.rect2.width -= (self.rect2.width / 100) * 25
			self.rect2.height -= (self.rect2.height / 100) * 25
			if self.rect2.height < 100:
				self.rect2.width = 150
				self.rect2.height = 100
                        rect_width = self.rect2.width
                        rect_height = self.rect2.height
		if format.lower() in self.raw_formats:
                        if self.workflow_started :
                                if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
					pixbuf, ratio = self.wand2pixbuf(self.wand)
					ratio2 = float(self.rect.width) / self.rect.height
					if ratio2 > ratio:
						pixbuf = self.scale_pixbuf(pixbuf, ratio)
					else:
						pixbuf = pixbuf.scale_simple(self.rect.width,\
								int(self.rect.width / ratio), gtk.gdk.INTERP_BILINEAR)
                                else:
                                        pixbuf = self.scale_pixbuf(*self.wand2pixbuf(self.wand))
                        else:
                                if self.raw_preview:
					pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.temp + self.fname, rect_width, rect_height)
                                else:
					if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
						pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice][:-len(format)],\
													rect_height, rect_width)
						pixbuf = pixbuf.rotate_simple(self.rotated[self.indice])
					else:
						pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice][:-len(format)],\
													rect_width, rect_height)
		else:
			if self.workflow_started :
                                if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
					pixbuf, ratio = self.wand2pixbuf(self.wand)
					ratio2 = float(self.rect.width) / self.rect.height
					if ratio2 > ratio:
						pixbuf = self.scale_pixbuf(pixbuf, ratio)
					else:
						pixbuf = pixbuf.scale_simple(self.rect.width, int(self.rect.width / ratio),\
													 gtk.gdk.INTERP_BILINEAR)
				else:
					pixbuf = self.scale_pixbuf(*self.wand2pixbuf(self.wand))
                        else:
				if self.rotated.has_key(self.indice) and self.checkbutton2.get_active() and self.notebook2.get_current_page() == 0:
					pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice], rect_height, rect_width)
					pixbuf = pixbuf.rotate_simple(self.rotated[self.indice])
				else:
					pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice], rect_width, rect_height)
		self.pblist[self.pbindex] = self.check_icons(format, pixbuf) 
		if not data:
                        if self.expander8.get_expanded():
                                self.draw_grid(False)
                        else:
                                self.image1.set_from_pixbuf(self.pblist[self.pbindex])
                else:
                        self.swin2_image.set_from_pixbuf(self.pblist[self.pbindex])
		while gtk.events_pending():
                        gtk.main_iteration(False)
		del pixbuf
		gc.collect()
		self.calculate_percentage()
		self.toolbutton6.handler_unblock(self.id35)
                self.toolbutton7.handler_unblock(self.id36)
		self.toolbutton8.handler_unblock(self.id37)
		self.toolbutton9.handler_unblock(self.id38)
		self.toolbutton16.handler_unblock(self.id1)
                self.toolbutton17.handler_unblock(self.id2)
		
	def zoom_out_photo(self, event, data):
		while gtk.events_pending():
                        gtk.main_iteration(False)
		if not self.n:
                        return True
		self.toolbutton6.handler_block(self.id35)
                self.toolbutton7.handler_block(self.id36)
		self.toolbutton8.handler_block(self.id37)
		self.toolbutton9.handler_block(self.id38)
                self.toolbutton16.handler_block(self.id1)
                self.toolbutton17.handler_block(self.id2)
		self.count = 0
		format = os.path.splitext(self.list[self.indice])[1]
		if not data:
                        self.rect.width += (self.rect.width / 100) * 25
			self.rect.height += (self.rect.height / 100) * 25
			if self.rect.height < 100:
				self.rect.width = 150
				self.rect.height = 100
                        rect_width = self.rect.width
                        rect_height = self.rect.height
                else:
                        self.rect2.width += (self.rect2.width / 100) * 25
			self.rect2.height += (self.rect2.height / 100) * 25
                        if self.rect2.height < 100:
				self.rect2.width = 150
				self.rect2.height = 100
                        rect_width = self.rect2.width
                        rect_height = self.rect2.height
		if format.lower() in self.raw_formats:
                        if self.workflow_started :
                                if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
					pixbuf, ratio = self.wand2pixbuf(self.wand)
					ratio2 = float(self.rect.width) / self.rect.height
					if ratio2 > ratio:
						pixbuf = self.scale_pixbuf(pixbuf, ratio)
					else:
						pixbuf = pixbuf.scale_simple(self.rect.width, int(self.rect.width / ratio),\
													 gtk.gdk.INTERP_BILINEAR)
				else:
					pixbuf = self.scale_pixbuf(*self.wand2pixbuf(self.wand))
                        else:
                                if self.raw_preview:
					pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.temp + self.fname, rect_width, rect_height)
                                else:
                                        if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
						pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice][:-len(format)],\
													rect_height, rect_width)
						pixbuf = pixbuf.rotate_simple(self.rotated[self.indice])
					else:
						pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice][:-len(format)],\
													rect_width, rect_height)
		else:
			if self.workflow_started :
                                if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
					pixbuf, ratio = self.wand2pixbuf(self.wand)
					ratio2 = float(self.rect.width) / self.rect.height
					if ratio2 > ratio:
						pixbuf = self.scale_pixbuf(pixbuf, ratio)
					else:
						pixbuf = pixbuf.scale_simple(self.rect.width, int(self.rect.width / ratio),\
													 gtk.gdk.INTERP_BILINEAR)
				else:
					pixbuf = self.scale_pixbuf(*self.wand2pixbuf(self.wand))
                        else:
				if self.rotated.has_key(self.indice) and self.checkbutton2.get_active() and self.notebook2.get_current_page() == 0:
					pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice], rect_height, rect_width)
					pixbuf = pixbuf.rotate_simple(self.rotated[self.indice])
				else:
					pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice], rect_width, rect_height)
		self.pblist[self.pbindex] = self.check_icons(format, pixbuf) 
		if not data:
                        if self.expander8.get_expanded():
                                self.draw_grid(False)
                        else:
                                self.image1.set_from_pixbuf(self.pblist[self.pbindex])
                else:
                        self.swin2_image.set_from_pixbuf(self.pblist[self.pbindex])
		while gtk.events_pending():
                        gtk.main_iteration(False)
		del pixbuf
		gc.collect()
		self.calculate_percentage()
		self.toolbutton6.handler_unblock(self.id35)
                self.toolbutton7.handler_unblock(self.id36)
		self.toolbutton8.handler_unblock(self.id37)
		self.toolbutton9.handler_unblock(self.id38)
		self.toolbutton16.handler_unblock(self.id1)
                self.toolbutton17.handler_unblock(self.id2)

	def zoom_fit_photo(self, obj, data):
		while gtk.events_pending():
                        gtk.main_iteration(False)
		self.toolbutton6.handler_block(self.id35)
                self.toolbutton7.handler_block(self.id36)
		self.toolbutton8.handler_block(self.id37)
		self.toolbutton9.handler_block(self.id38)
                self.toolbutton16.handler_block(self.id1)
                self.toolbutton17.handler_block(self.id2)
		self.count = 0
		format = os.path.splitext(self.list[self.indice])[1]
		if not data:
                        self.rect = self.viewport1.allocation
                        rect = self.rect
                else:
                        self.rect2 = self.scrolledwindow2.allocation
                        rect = self.rect2
		if format.lower() in self.raw_formats:
			if not data:
				if self.workflow_started :
                                        if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
						pixbuf, ratio = self.wand2pixbuf(self.wand)
						ratio2 = float(self.rect.width) / self.rect.height
						if ratio2 > ratio:
							pixbuf = self.scale_pixbuf(pixbuf, ratio)
						else:
							pixbuf = pixbuf.scale_simple(self.rect.width, int(self.rect.width / ratio),\
													 gtk.gdk.INTERP_BILINEAR)
                                        else:
                                                pixbuf = self.scale_pixbuf(*self.wand2pixbuf(self.wand))
                                else:
                                        if self.raw_preview:
						pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.temp + self.fname, rect.width, rect.height)
                                        else:
                                                if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
							pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice][:-len(format)],\
													rect.height, rect.width)
							pixbuf = pixbuf.rotate_simple(self.rotated[self.indice])
						else:
							pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice][:-len(format)],\
													rect.width, rect.height)
			else:
				if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
					pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice][:-len(format)],\
					rect.height - self.swin2_label.allocation.height, rect.width)
					pixbuf = pixbuf.rotate_simple(self.rotated[self.indice])
				else:
					pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice][:-len(format)],\
					rect.width, rect.height - self.swin2_label.allocation.height)
		else:
			if not data:
				if self.workflow_started :
                                        if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
						pixbuf, ratio = self.wand2pixbuf(self.wand)
						ratio2 = float(self.rect.width) / self.rect.height
						if ratio2 > ratio:
							pixbuf = self.scale_pixbuf(pixbuf, ratio)
						else:
							pixbuf = pixbuf.scale_simple(self.rect.width, int(self.rect.width / ratio),\
												 gtk.gdk.INTERP_BILINEAR)
					else:
						pixbuf = self.scale_pixbuf(*self.wand2pixbuf(self.wand))
                       		else:
					if self.rotated.has_key(self.indice) and self.checkbutton2.get_active() and \
										self.notebook2.get_current_page() == 0:
						pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice], rect.height, rect.width)
						pixbuf = pixbuf.rotate_simple(self.rotated[self.indice])
					else:
						pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice], rect.width, rect.height)
			else:
				if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
					pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice],\
					rect.height - self.swin2_label.allocation.height, rect.width)
					pixbuf = pixbuf.rotate_simple(self.rotated[self.indice])
				else:
					pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice],\
					rect.width, rect.height - self.swin2_label.allocation.height)
		self.pblist[self.pbindex] = self.check_icons(format,pixbuf)   
		if not data:
                        if self.expander8.get_expanded():
                                self.draw_grid(False)
			elif self.expander17.get_expanded():
				width = self.pblist[self.pbindex].get_width()
				height = self.pblist[self.pbindex].get_height()
				self.drawable.draw_pixbuf(self.gc, self.pblist[self.pbindex], 0, 0,\
                                                  int((self.rect.width - width)/2), int((self.rect.height - height) / 2))
				self.drawing_area.queue_draw()
				self.x, self.y = self.x1, self.y1
                        else:
                                self.image1.set_from_pixbuf(self.pblist[self.pbindex])
                else:
                        self.swin2_image.set_from_pixbuf(self.pblist[self.pbindex])
		del pixbuf
		gc.collect()
		self.calculate_percentage()
		self.toolbutton6.handler_unblock(self.id35)
                self.toolbutton7.handler_unblock(self.id36)
		self.toolbutton8.handler_unblock(self.id37)
		self.toolbutton9.handler_unblock(self.id38)
		self.toolbutton16.handler_unblock(self.id1)
                self.toolbutton17.handler_unblock(self.id2)
		
	def zoom_1_photo(self, event, data):
		while gtk.events_pending():
                        gtk.main_iteration(False)
		self.toolbutton6.handler_block(self.id35)
                self.toolbutton7.handler_block(self.id36)
		self.toolbutton8.handler_block(self.id37)
		self.toolbutton9.handler_block(self.id38)
                self.toolbutton16.handler_block(self.id1)
                self.toolbutton17.handler_block(self.id2)
		self.count = 0
                format = os.path.splitext(self.list[self.indice])[1]
		if format.lower() in self.raw_formats:
			if self.workflow_started :
                                pixbuf = self.wand2pixbuf(self.wand)[0]
                        else:
                                if self.raw_preview:
					pixbuf = gtk.gdk.pixbuf_new_from_file(self.temp + self.fname)
                                else:
                                        if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
						pixbuf = gtk.gdk.pixbuf_new_from_file(self.list[self.indice][:-len(format)])
						pixbuf = pixbuf.rotate_simple(self.rotated[self.indice])
					else:
						pixbuf = gtk.gdk.pixbuf_new_from_file(self.list[self.indice][:-len(format)])
		else:   
			if self.workflow_started :
				pixbuf = self.wand2pixbuf(self.wand)[0]
                        else:   
				if self.rotated.has_key(self.indice) and self.checkbutton2.get_active() and self.notebook2.get_current_page() == 0:
					pixbuf = gtk.gdk.pixbuf_new_from_file(self.list[self.indice])
					pixbuf = pixbuf.rotate_simple(self.rotated[self.indice])
				else:
					pixbuf = gtk.gdk.pixbuf_new_from_file(self.list[self.indice])
		self.pblist[self.pbindex] = self.check_icons(format, pixbuf) 	
		if not data:
                        if self.expander8.get_expanded(): 
				self.draw_grid(False)
                        else: 
				self.image1.set_from_pixbuf(self.pblist[self.pbindex])
                        self.rect.width = self.pblist[self.pbindex].get_width()
                        self.rect.height = self.pblist[self.pbindex].get_height()
                else:
                        self.swin2_image.set_from_pixbuf(self.pblist[self.pbindex])
                        self.rect2.width = self.pblist[self.pbindex].get_width()
                        self.rect2.height = self.pblist[self.pbindex].get_height()
		del pixbuf
		gc.collect()
		self.calculate_percentage()
		self.toolbutton6.handler_unblock(self.id35)
                self.toolbutton7.handler_unblock(self.id36)
		self.toolbutton8.handler_unblock(self.id37)
		self.toolbutton9.handler_unblock(self.id38)
		self.toolbutton16.handler_unblock(self.id1)
                self.toolbutton17.handler_unblock(self.id2)
		
	def sx_rotation(self, event, data):
		while gtk.events_pending():
                        gtk.main_iteration(False)
                if self.count < 3:
                        self.count += 1
                else:
                        self.count = 0
                if not data:
                        rect_width = self.rect.width
                        rect_height = self.rect.height
                else:
                        rect_width = self.rect2.width
                        rect_height = self.rect2.height
                format = os.path.splitext(self.list[self.indice])[1]
		if format.lower() in self.raw_formats:
			if self.workflow_started :
                                if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
					pixbuf, ratio = self.wand2pixbuf(self.wand)
					ratio2 = float(self.rect.width) / self.rect.height
					if ratio2 > ratio:
						pixbuf = self.scale_pixbuf(pixbuf, ratio)
					else:
						pixbuf = pixbuf.scale_simple(self.rect.width, int(self.rect.width / ratio),\
													 gtk.gdk.INTERP_BILINEAR)
				else:
					pixbuf = self.scale_pixbuf(*self.wand2pixbuf(self.wand))
                        else:
                                if self.raw_preview:
                                        pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.temp + self.fname, rect_width, rect_height)
                                else:
                                        if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
                                                pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice][:-len(format)],rect_height,rect_width)
                                                pixbuf = pixbuf.rotate_simple(self.rotated[self.indice])
                                        else:
                                                pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice][:-len(format)],rect_width,rect_height)

			
			pixbuf = pixbuf.rotate_simple(self.gradi[self.count])
			pixbuf.save('.thumbnails/' + os.path.split(self.list[self.indice][:-len(format)])[1], "jpeg")
			pixbuf = gtk.gdk.pixbuf_new_from_file_at_size('.thumbnails/' +\
                        os.path.split(self.list[self.indice][:-len(format)])[1], rect_width, rect_height)               
                else:
			if self.workflow_started :
                                if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
					pixbuf, ratio = self.wand2pixbuf(self.wand)
					ratio2 = float(self.rect.width) / self.rect.height
					if ratio2 > ratio:
						pixbuf = self.scale_pixbuf(pixbuf, ratio)
					else:
						pixbuf = pixbuf.scale_simple(self.rect.width, int(self.rect.width / ratio),\
												 gtk.gdk.INTERP_BILINEAR)
				else:
					pixbuf = self.scale_pixbuf(*self.wand2pixbuf(self.wand)) 
                        else:
                                if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
                                        pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice], rect_height, rect_width)
                                        pixbuf = pixbuf.rotate_simple(self.rotated[self.indice])
                                else:
                                        pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice], rect_width, rect_height)
			pixbuf = pixbuf.rotate_simple(self.gradi[self.count])
			if format.lower() in ['.png','.ico','.svg'] and pixbuf.get_has_alpha():
                                pixbuf.save('.thumbnails/'+os.path.split(self.list[self.indice])[1][:-len(format)] + '.png', "png")
                                pixbuf = gtk.gdk.pixbuf_new_from_file_at_size('.thumbnails/' +\
                                os.path.split(self.list[self.indice])[1][:-len(format)] + '.png', rect_width, rect_height)
                        else:
                                pixbuf.save('.thumbnails/' + os.path.split(self.list[self.indice])[1][:-len(format)]+ '.jpg', "jpeg")
                                pixbuf = gtk.gdk.pixbuf_new_from_file_at_size('.thumbnails/' +\
                                os.path.split(self.list[self.indice])[1][:-len(format)] + '.jpg', rect_width, rect_height)
		pixbuf = self.check_icons(format, pixbuf) 
                if not data:
                        self.image1.set_from_pixbuf(pixbuf)
                else:
                        self.swin2_image.set_from_pixbuf(pixbuf)
		del pixbuf
		gc.collect()
          
        def scroll_fullphoto(self, obj, event):
                if event.direction == gtk.gdk.SCROLL_UP:
                	self.previous_fullphoto(self)
                elif event.direction == gtk.gdk.SCROLL_DOWN:
                        self.next_fullphoto(self)
		
	def dx_rotation(self, event, data):
		while gtk.events_pending():
                        gtk.main_iteration(False)
                if self.count > 0:
                        self.count -= 1
                else:
                        self.count = 3
                if not data:
                        rect_width = self.rect.width
                        rect_height = self.rect.height
                else:
                        rect_width = self.rect2.width
                        rect_height = self.rect2.height
		format = os.path.splitext(self.list[self.indice])[1]
		if format.lower() in self.raw_formats:
			if self.workflow_started :
                                if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
					pixbuf, ratio = self.wand2pixbuf(self.wand)
					ratio2 = float(self.rect.width) / self.rect.height
					if ratio2 > ratio:
						pixbuf = self.scale_pixbuf(pixbuf, ratio)
					else:
						pixbuf = pixbuf.scale_simple(self.rect.width, int(self.rect.width / ratio),\
													 gtk.gdk.INTERP_BILINEAR)
				else:
					pixbuf = self.scale_pixbuf(*self.wand2pixbuf(self.wand))
                        else:
                                if self.raw_preview:
                                        pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.temp + self.fname, rect_width, rect_height)
                                else:
                                        if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
                                                pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice][:-len(format)], rect_height,rect_width)
                                                pixbuf = pixbuf.rotate_simple(self.rotated[self.indice])
                                        else:
                                                pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice][:-len(format)], rect_width,rect_height)
			pixbuf = pixbuf.rotate_simple(self.gradi[self.count])
			pixbuf.save('.thumbnails/' + os.path.split(self.list[self.indice][:-len(format)])[1], "jpeg")
			pixbuf = gtk.gdk.pixbuf_new_from_file_at_size('.thumbnails/' +\
                        os.path.split(self.list[self.indice][:-len(format)])[1], rect_width, rect_height)           
                else:
			if self.workflow_started :
                                if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
					pixbuf, ratio = self.wand2pixbuf(self.wand)
					ratio2 = float(self.rect.width) / self.rect.height
					if ratio2 > ratio:
						pixbuf = self.scale_pixbuf(pixbuf, ratio)
					else:
						pixbuf = pixbuf.scale_simple(self.rect.width, int(self.rect.width / ratio),\
													 gtk.gdk.INTERP_BILINEAR)
				else:
					pixbuf = self.scale_pixbuf(*self.wand2pixbuf(self.wand))
                        else:
                                if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
                                        pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice], rect_height, rect_width)
                                        pixbuf = pixbuf.rotate_simple(self.rotated[self.indice])
                                else:
                                        pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice], rect_width, rect_height)
			pixbuf = pixbuf.rotate_simple(self.gradi[self.count])
			if format.lower() in ['.png', '.ico', '.svg'] and pixbuf.get_has_alpha():
                                pixbuf.save('.thumbnails/' + os.path.split(self.list[self.indice])[1][:-len(format)] + '.png', "png")
                                pixbuf = gtk.gdk.pixbuf_new_from_file_at_size('.thumbnails/' +\
                                os.path.split(self.list[self.indice])[1][:-len(format)] + '.png', rect_width, rect_height)
                        else:
                                pixbuf.save('.thumbnails/'+os.path.split(self.list[self.indice])[1][:-len(format)] + '.jpg', "jpeg")
                                pixbuf = gtk.gdk.pixbuf_new_from_file_at_size('.thumbnails/' +\
                                os.path.split(self.list[self.indice])[1][:-len(format)] + '.jpg', rect_width, rect_height)
		pixbuf = self.check_icons(format,pixbuf) 
                if not data:
                        self.image1.set_from_pixbuf(pixbuf)
                else:
                        self.swin2_image.set_from_pixbuf(pixbuf)
		del pixbuf
		gc.collect()

	def open_with_gimp(self, obj):               # Opens image with Gimp
                if self.radiobutton6.get_active() and not self.window2.get_property('visible'):
                        if self.obj in self.event:
                                self.indice = self.event.index(self.obj)
                        elif  self.obj in self.e:
                                self.indice = self.e.index(self.obj)
                format = os.path.splitext(self.list[self.indice])[1]
                if self.version + 'Albums/' not in self.window1.get_title() :
                        if format.lower() in self.raw_formats:
                                filename = self.rawpath[self.list[self.indice]]
                        else:
                                filename = self.list[self.indice]
                elif self.version + 'Albums/' in self.window1.get_title() :
                        if format.lower() in self.raw_formats:
				filename = self.list[self.indice].replace('/thumb', '').replace('.thumb.jpg', '')
                        else:
                                filename = self.list[self.indice]
		thread.start_new_thread(self.start_gimp, (filename,))
		
	def start_gimp(self, filename):
                status = os.system('gimp "%s" '% filename)
                print status
       
        def open_with_other(self, obj):                 # Opens image with other software
		self.entry3.grab_focus()              
                self.dialog13.show()
                response = self.dialog13.run()
                if response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_DELETE_EVENT:
                        self.dialog13.hide()
                elif response == gtk.RESPONSE_OK:
			self.dialog13.hide()
			while gtk.events_pending():
                                gtk.main_iteration(False)
			if self.radiobutton6.get_active() and not self.window2.get_property('visible'):
                                if self.obj in self.event:
                                        self.indice = self.event.index(self.obj)
                                elif  self.obj in self.e:
                                        self.indice = self.e.index(self.obj)
                        format = os.path.splitext(self.list[self.indice])[1]
                        if self.version + 'Albums/' not in self.window1.get_title() :
                                if format in self.raw_formats:
                                        filename = self.rawpath[self.list[self.indice]]
                                else:
                                        filename = self.list[self.indice]
                        elif self.version + 'Albums/' in self.window1.get_title() :
                                if format.lower() in self.raw_formats:
                                        filename = self.list[self.indice].replace('/thumb', '').replace('.thumb.jpg', '')
                                else:
                                        filename = self.list[self.indice]
                        command = self.entry3.get_text()
			thread.start_new_thread(self.start_other, (command, filename))
			
	def start_other(self, command, filename):
                        status = os.system(' "%s" "%s" ' % (command, filename))
                        print status

        def load_cache(self, width, height, data):         # Preloads previous and next image
		self.lock.acquire()
                if self.indice > 0:
			format = os.path.splitext(self.list[self.indice - 1])[1]
			if format.lower() in self.raw_formats:
				if data == 'fullscreen':
					if self.rotated.has_key(self.indice - 1) and self.checkbutton2.get_active():
						self.fullpblist[0]=gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice - 1]\
						[:-len(format)], height, width)
						self.fullpblist[0] = self.fullpblist[0].rotate_simple(self.rotated[self.indice - 1])
					else:
						self.fullpblist[0] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice - 1]\
						[:-len(format)], width, height)	
				else:
					if self.rotated.has_key(self.indice - 1) and self.checkbutton2.get_active():
						self.pblist[0] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice - 1]\
						[:-len(format)], height, width)
						self.pblist[0] = self.pblist[0].rotate_simple(self.rotated[self.indice - 1])
					else:	
                				self.pblist[0] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice - 1]\
						[:-len(format)], width, height)
			else:
				if data == 'fullscreen':
					if self.rotated.has_key(self.indice - 1) and self.checkbutton2.get_active():
						self.fullpblist[0] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice - 1]\
						,height, width)
						self.fullpblist[0] = self.fullpblist[0].rotate_simple(self.rotated[self.indice - 1])	
					else:
						self.fullpblist[0] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice - 1]\
						,width, height)
				else:
					if self.rotated.has_key(self.indice - 1) and self.checkbutton2.get_active():
						self.pblist[0] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice - 1],\
						height, width)
						self.pblist[0] = self.pblist[0].rotate_simple(self.rotated[self.indice - 1])
					else:
						self.pblist[0]=gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice - 1],\
						width,height)
                if self.indice < self.n - 1:
			format = os.path.splitext(self.list[self.indice + 1])[1]
			if format.lower() in self.raw_formats:
				if data == 'fullscreen':
					if self.rotated.has_key(self.indice + 1) and self.checkbutton2.get_active():
						self.fullpblist[2] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice + 1]\
						[:-len(format)], height, width)
						self.fullpblist[2] = self.fullpblist[2].rotate_simple(self.rotated[self.indice + 1])
					else:
						self.fullpblist[2] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice + 1]\
						[:-len(format)], width, height)
				else:
					if self.rotated.has_key(self.indice + 1) and self.checkbutton2.get_active():
						self.pblist[2] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice + 1]\
						[:-len(format)], height, width)
						self.pblist[2] = self.pblist[2].rotate_simple(self.rotated[self.indice + 1])
					else:		
                				self.pblist[2] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice + 1]\
						[:-len(format)], width, height)
						
			else:
				if data == 'fullscreen':
					if self.rotated.has_key(self.indice + 1) and self.checkbutton2.get_active():
						self.fullpblist[2] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice + 1],\
						height, width)
						self.fullpblist[2] = self.fullpblist[2].rotate_simple(self.rotated[self.indice + 1])
					else:
						self.fullpblist[2] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice + 1],\
						width, height)
				else:
					if self.rotated.has_key(self.indice + 1) and self.checkbutton2.get_active():
						self.pblist[2] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice + 1],\
						height, width)
						self.pblist[2] = self.pblist[2].rotate_simple(self.rotated[self.indice + 1])
					else:	
						self.pblist[2] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice + 1],\
						width, height)
		self.lock.release()

	def load_b_cache(self, width, height):
                self.lock2.acquire()
                if self.indice > 0:
			format = os.path.splitext(self.list[self.indice - 1])[1]
			if format.lower() in self.raw_formats:
				if self.rotated.has_key(self.indice - 1) and self.checkbutton2.get_active():
					self.b_pixlist[0] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice - 1]\
					[:-len(format)], height - self.swin2_label.allocation.height, width)
					self.b_pixlist[0] = self.b_pixlist[0].rotate_simple(self.rotated[self.indice - 1])
				else:
					self.b_pixlist[0] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice - 1]\
					[:-len(format)], width, height - self.swin2_label.allocation.height)	
			else:
				if self.rotated.has_key(self.indice - 1) and self.checkbutton2.get_active():
					self.b_pixlist[0] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice - 1],\
                                	height - self.swin2_label.allocation.height, width)
					self.b_pixlist[0] = self.b_pixlist[0].rotate_simple(self.rotated[self.indice - 1])
				else:
					self.b_pixlist[0] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice - 1],\
                                	width, height - self.swin2_label.allocation.height)
                if self.indice < self.n - 1:
			format = os.path.splitext(self.list[self.indice + 1])[1]
			if format.lower() in self.raw_formats:
				if self.rotated.has_key(self.indice + 1) and self.checkbutton2.get_active():
					self.b_pixlist[2] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice + 1]\
					[:-len(format)], height - self.swin2_label.allocation.height,width)
					self.b_pixlist[2] = self.b_pixlist[2].rotate_simple(self.rotated[self.indice + 1])	
				else:
					self.b_pixlist[2] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice + 1]\
					[:-len(format)], width, height - self.swin2_label.allocation.height)	
			else:
				if self.rotated.has_key(self.indice + 1) and self.checkbutton2.get_active():
					self.b_pixlist[2]=gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice + 1],\
					height - self.swin2_label.allocation.height, width)
					self.b_pixlist[2] = self.b_pixlist[2].rotate_simple(self.rotated[self.indice + 1])	
				else:
					self.b_pixlist[2] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice + 1],\
					width, height - self.swin2_label.allocation.height)
		self.lock2.release()
   
	def display_photo(self, obj):             # Opens image on details window
		self.hpaned2.handler_block(self.id22)
                self.pbindex = 1
		if self.obj in self.event:
			self.indice = self.event.index(self.obj)
		elif  self.obj in self.e:
                        self.indice = self.e.index(self.obj)
		self.window2.maximize()
		self.window2.show()
		while gtk.events_pending():
                        gtk.main_iteration(False)
		self.rect = self.viewport1.allocation
		format = os.path.splitext(self.list[self.indice])[1]	
		self.set_image1(format)
       		self.add_dimensions(format,self._label)
		self.hpaned2.handler_unblock(self.id22)
		thread.start_new_thread(self.load_cache, (self.rect.width, self.rect.height, ''))

	def eventbox1_handler(self, obj, event):
                if self.radiobutton7.get_active():
                        if event.button == 3 and self.n :
				if self.version + 'Albums/' not in self.window1.get_title():
					self.imagemenuitem9.set_sensitive(False)
					self.menuitem18.set_sensitive(True)
					self.menuitem19.set_sensitive(True)
					self.imagemenuitem20.set_sensitive(False)
					self.menuitem20.set_sensitive(True)
					self.menuitem21.set_sensitive(True)
				else:
                                        self.imagemenuitem9.set_sensitive(True)
                                        self.imagemenuitem20.set_sensitive(True)
                                        self.menuitem19.set_sensitive(False)
                                        self.menuitem20.set_sensitive(False)
                                self.menu8.popup(None, None, None, event.button, event.time)
                        if event.type == 5:
                                self.open_on_window2(self)
			if event.type == gtk.gdk.BUTTON_PRESS:
                                self.scrolledwindow2.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.FLEUR))
			
	def on_scrolledwindow_release_event(self,obj,event):
                self.hadj, self.vadj = obj.get_parent().get_hadjustment(), obj.get_parent().get_vadjustment()
		self.w = self.hadj.upper - self.hadj.page_size
		self.h = self.vadj.upper - self.vadj.page_size
		self.hadj_lower = self.hadj.lower
		self.vadj_lower = self.vadj.lower
		if event.type == gtk.gdk.BUTTON_PRESS:
                        if event.button == 1:
                                self.x, self.y = event.x, event.y
                                obj.get_parent().window.set_cursor(gtk.gdk.Cursor(gtk.gdk.FLEUR))              
                        elif event.button == 3 and self.workflow_started:
                                self.display_unchanged_image()
		if event.type == gtk.gdk.BUTTON_RELEASE:
                        if event.button == 1:
                                obj.get_parent().window.set_cursor(None)
                        elif event.button == 3 and self.workflow_started:
                                self.image1.set_from_pixbuf(self.pblist[self.pbindex])

	def hand_image(self, obj, event):
		hadj_value = self.hadj.value + self.x - event.x
		vadj_value = self.vadj.value + self.y - event.y
		if hadj_value <= 0:
                        pass
		elif self.hadj_lower < hadj_value < self.w:
			self.hadj.value = hadj_value
			self.x = event.x
		elif hadj_value >= self.w:
			self.hadj.value = self.w
		if vadj_value <= 0:
                        pass
		elif self.vadj_lower < vadj_value < self.h:
			self.vadj.value = vadj_value
			self.y = event.y
		elif vadj_value >= self.h:
			self.vadj.value = self.h

	def display_unchanged_image(self):
	   	if self.image_was_changed:
			unchanged_pixbuf = self.scale_pixbuf(*self.wand2pixbuf(MagickImage(self.wand_list[self.wand_index].get_image())))
                	self.image1.set_from_pixbuf(unchanged_pixbuf)
                                	
	def scroll_eventbox1(self, obj, event):
		if self.radiobutton7.get_active():
                	if event.direction == gtk.gdk.SCROLL_DOWN:
                                self.next_b_photo(self)
                	elif event.direction == gtk.gdk.SCROLL_UP:
                                self.previous_b_photo(self)
			
	def scroll_to_selection(self, event):
		adj = self.scrolledwindow6.get_hadjustment()
        	x, y = self.b_event[self.indice].window.get_position()
                if x > adj.value + adj.page_size:
                	adj.value = min(x, adj.upper - adj.page_size)
		elif x < adj.value:
			adj.value = max(adj.lower, x + self.b_event[self.indice].allocation.width - adj.page_size)

	def scroll_scrolledwindow3(self, obj, event):
		if event.direction == gtk.gdk.SCROLL_DOWN:
                        self.next_photo(self)
                elif event.direction == gtk.gdk.SCROLL_UP:
                        self.previous_photo(self)

        def open_on_window2(self, obj):
		self.hpaned2.handler_block(self.id22)
		indice = self.indice
                self.old_indice = indice
                self.pbindex = 1
                self.window2.maximize()
		self.window2.show()
		self.rect = self.viewport1.allocation
		format = os.path.splitext(self.list[self.indice])[1]	
		self.set_image1(format)
		self.window2.show()
		while gtk.events_pending():
                        gtk.main_iteration(False)
       		self.add_dimensions(format, self._label)
		thread.start_new_thread(self.load_cache, (self.rect.width, self.rect.height, ''))
		self.hpaned2.handler_unblock(self.id22)
			
	def full_exif(self, event):              # Populates exif panel with full exif list
		if self.checkbutton1.get_active():
			return True
		self.exifmodel.clear()
		format = os.path.splitext(self.list[self.indice])[1]
		if format.lower() in self.raw_formats and self.ark not in self.list[self.indice]:
			image = self.rawpath[self.list[self.indice]]
		elif format.lower() in self.raw_formats and self.ark in self.list[self.indice]:
                        image = self.list[self.indice].replace('/thumb', '').replace('.thumb.jpg', '')
		elif format.lower() in self.formats:
			image = self.list[self.indice]
		status,output = commands.getstatusoutput('exiftool -e -S "%s" ' % image)
		if output:
			exif_list = output.split('\n')
			for item in exif_list:
				tag = item.split(': ')
				self.exifmodel.append([tag[0], tag[1]])

        def display_exif(self, image, label):
		if self.toolbutton24.get_active():
			self.full_exif(self)
			return True
		if self.checkbutton1.get_active():
			return True
		else:
                	self.exifmodel.clear()  
                	self.exifmodel.append(['Filename  ', label])
                	cmd = 'exiftool -e -S -CreateDate -ISO -ExposureTime -FNumber -FocalLength -ExposureProgram -ExposureCompensation \
                        -ImageDescription -CameraModelName -Software -ExifImageWidth -ExifImageLength -BitsPerSample \
                        -Compression -Flash -FlashExposureCompensation -Lens -WhiteBalance -WhiteBalanceTemperature \
                        -FocusMode -FocusDistance -FocusProcess "%s"'
                	status, output = commands.getstatusoutput(cmd % image)
                	if output:
                        	exif_list = output.split('\n')
                        	for item in exif_list:
					tag = item.split(': ')
					self.exifmodel.append([tag[0], tag[1]])
				
	def grep_image_size(self, lista):       
                width = height = 0
		self.image_size = self.image_size2=''
		for item in lista:
			if 'ExifImageWidth' in item:
				width = item.split(': ')[1]
			elif 'ExifImageLength' in item:
				height = item.split(': ')[1]
			if width and height:
                                if self.rotated.has_key(self.indice) and os.path.splitext(self.list[self.indice])[1] in self.raw_formats:
                                        self.image_size = height + 'x' + width
                                else:
                                        self.image_size = width + 'x' + height
				break
		width1 = height1 = 0
		for item in lista:
			if 'ImageWidth' in item[:10]:
				width1 = item.split(': ')[1]
			elif 'ImageHeight' in item[:11]:
				height1 = item.split(': ')[1]
			if width1 and height1:
                                if self.rotated.has_key(self.indice) and os.path.splitext(self.list[self.indice])[1] in self.raw_formats:
                                        self.image_size2 = height1 + 'x' + width1
                                else:
                                        self.image_size2 = width1 + 'x' + height1
				break
		if not self.image_size:
                        self.image_size = self.image_size2[:]
		
        def hide_exif(self, obj):
		if not self.checkbutton1.get_active():
			self.frame1.hide_all()
			self.checkbutton1.set_active(True)
			self.settings['checkbutton1'] = True
			self.toolbutton25.set_icon_widget(self.stock_properties_img)
			self.stock_properties_img.show()
			self.tooltip.set_tip(self.toolbutton25, 'Show Image Tools', None)
			self.exifmodel.clear()
			while gtk.events_pending():
                                gtk.main_iteration(False)
			self.zoom_fit_photo(self, 0)
		else:
			self.checkbutton1.set_active(False)
			self.settings['checkbutton1'] = False
			if self.toolbutton24.get_active():
                                self.full_exif(self)
			else:
                                self.add_dimensions(os.path.splitext(self.list[self.indice])[1], self._label)
			self.frame1.show_all()
			self.toolbutton25.set_icon_widget(self.stock_close_img)
			self.stock_close_img.show()
			self.tooltip.set_tip(self.toolbutton25, 'Hide Image Tools', None)
			while gtk.events_pending():
                                gtk.main_iteration(False)
			self.zoom_fit_photo(self, 0)
			self.on_notebook2_switched(self)

        def select_b_photo(self, obj, event):      # Displays the selected image on the single image layout
                self.pixindex = 1
                self.vpaned2.handler_block(self.id27)
                self.indice = self.b_event.index(obj)
                for i in xrange(self.n):
                        self.b_event[i].modify_bg(gtk.STATE_NORMAL, self.gallery_color)
                self.b_event[self.indice].modify_bg(gtk.STATE_NORMAL, self.selection_color)
		while gtk.events_pending():
                        gtk.main_iteration(False)
                if event.button == 1 or event.button == 3 :
                        self.rect2 = self.scrolledwindow2.allocation
                        format = os.path.splitext(self.list[self.indice])[1]
                        if format.lower() in self.raw_formats:
				if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
					self.b_pixlist[self.pixindex] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice]\
                                	[:-len(format)], self.rect2.height - self.swin2_label.allocation.height, self.rect2.width)
					self.b_pixlist[self.pixindex] = self.b_pixlist[self.pixindex].rotate_simple(self.rotated[self.indice])
				else:
                                	self.b_pixlist[self.pixindex] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice]\
                                	[:-len(format)], self.rect2.width, self.rect2.height - self.swin2_label.allocation.height)
                        else:
				if self.rotated.has_key(self.indice) and self.checkbutton2.get_active():
					self.b_pixlist[self.pixindex] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice],\
                                	self.rect2.height - self.swin2_label.allocation.height, self.rect2.width)
				else:
                                	self.b_pixlist[self.pixindex] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice],\
                                	self.rect2.width, self.rect2.height - self.swin2_label.allocation.height)
			self.b_pixlist[self.pixindex] = self.check_icons(format,self.b_pixlist[self.pixindex])
                        self.swin2_image.set_from_pixbuf(self.b_pixlist[self.pixindex])
                        self.swin2_label.set_text(self.label[self.indice].get_text())
                        self.scrolledwindow2.show_all()
                        while gtk.events_pending():
                                gtk.main_iteration(False)
                        self.calculate_percentage()
                self.vpaned2.handler_unblock(self.id27)
                thread.start_new_thread(self.load_b_cache, (self.rect2.width, self.rect2.height))
		
	def check_icons(self, format, pixbuf):
		if format.lower() in ['.png', '.svg', '.ico'] and pixbuf.get_has_alpha():
			w = pixbuf.get_width()
			h = pixbuf.get_height()
			grey = self.grey.copy()
			grey = grey.scale_simple(w, h, gtk.gdk.INTERP_BILINEAR)
			pixbuf.composite(grey, 0, 0, w, h, 0, 0, 1.0, 1.0, gtk.gdk.INTERP_BILINEAR, 255)
			return grey
		else:
                        return pixbuf
		
	def select_photo(self, obj, event):        # Selects clicked thumbnails on layout1 - 2
		if obj in self.event:
			indice = self.event.index(obj)
		elif obj in self.e:
			indice = self.e.index(obj)
                if event.button == 3:
			self.obj = obj
                        label = self.e[indice].get_child()
			filename = label.get_text()
			format = os.path.splitext(filename)[1]
			if self.version + 'Albums/' not in self.window1.get_title():
                                if format.lower() in self.raw_formats:
					 filename = self.temp+filename[:-len(format)] + '.thumb.jpg'+format
                                else:
                                        filename = self.cartella + '/' + filename
                                if filename not in self.selected:
                                        self.e[indice].modify_bg(gtk.STATE_NORMAL, self.selection_color)
                                        self.selected.append(filename)
                        else:
                                for item in self.albums[self.album]:      
                                        if format.lower() in self.raw_formats:
                                                if filename[:-len(format)] in item:
                                                        filename = item[:]
                                                        break
                                        elif filename in item:
                                                filename = item[:]
                                                break
                                        else:
                                                continue
                                if filename not in self.selected:   
                                        self.e[indice].modify_bg(gtk.STATE_NORMAL, self.selection_color)
                                        self.selected.append(filename)
                        if self.selected:
				if self.version + 'Albums/' not in self.window1.get_title():
					self.imagemenuitem19.set_sensitive(False)
					self.delete1.set_sensitive(False)
					self.menuitem15.set_sensitive(True)
					self.menuitem16.set_sensitive(True)
				else:
                                        self.imagemenuitem19.set_sensitive(True)
					self.delete1.set_sensitive(True)
                                        self.menuitem15.set_sensitive(False)
					self.menuitem16.set_sensitive(False)
                        	self.menu5.popup(None, None, None, event.button, event.time)            
		elif event.type == 5 :
			self.obj = obj
			self.display_photo(self)
		elif event.button == 1:
			label = self.e[indice].get_child()
			filename = label.get_text()
			format = os.path.splitext(filename)[1]
			if self.version + 'Albums/' not in self.window1.get_title():
                                if format.lower() in self.raw_formats:
					filename = self.temp + filename[:-len(format)] + '.thumb.jpg' + format
                                else:
                                        filename = self.cartella + '/' + filename
                                if filename not in self.selected:
                                        self.e[indice].modify_bg(gtk.STATE_NORMAL,self.selection_color)
                                        self.selected.append(filename)
                                else:
                                        del self.selected[self.selected.index(filename)]
                                        self.e[indice].modify_bg(gtk.STATE_NORMAL, self.colorbutton1.get_color())
                        else:
                                for item in self.albums[self.album]:     
                                        if format.lower() in self.raw_formats:
                                                if filename[:-len(format)] in item:
                                                        filename = item[:]
                                                        break
                                        elif filename in item:
                                                filename = item[:]
                                                break
                                        else:
                                                continue
                                if filename not in self.selected:
                                        self.e[indice].modify_bg(gtk.STATE_NORMAL, self.selection_color)
                                        self.selected.append(filename)
                                else:
                                        del self.selected[self.selected.index(filename)]
                                        self.e[indice].modify_bg(gtk.STATE_NORMAL, self.colorbutton1.get_color())
		
        def selection_control(self, event):              #Checks for unknown files on selected images
                if self.radiobutton7.get_active():
                        self.selected = []
                        self.selected.append(self.list[self.indice])
                if self.version + 'Albums/' not in self.window1.get_title() :
                        files = os.listdir(self.cartella)
                        for item in self.selected:
                                format = os.path.splitext(item)[1]
                                if format.lower() in self.raw_formats:
					fname = os.path.split(item)[1].replace('.thumb.jpg', '')
                                else:
                                        fname = os.path.split(item)[1]
                                if fname in files: continue
                                else:
                                        self.label7.set_text('Attention! Unknown file: %s\n The gallery will be updated!' % fname)
                                        self.dialog6.show()
					gtk.gdk.beep()
                                        response = self.dialog6.run()
                                        if response == gtk.RESPONSE_OK:
                                                self.dialog6.hide()
                                                self.scrolledwindow2.get_child().destroy()
                                                if self.radiobutton7.get_active():
                                                        self.hbox1.destroy()
                                                self.n = self.count_images(self)
                                                if self.n:
                                                        self.make_table(self)
                                                        self.attach_images(self)
                                                        self.statusbar_pop(self.statusbar3, self.context_id3)
                                                        self.statusbar_push(self.statusbar3, self.context_id3,\
							'There are %s images     Total size %f MB'%(self.n, self.total_size / 1000000.0))
                                                        if self.radiobutton7.get_active():
                                                                self.make_bottom_panel(self, self.n)
                                                        else:
                                                                self.make_thumbnails(self.width, self.height, self.n)

                                                else:
                                                        self.statusbar_pop(self.statusbar3, self.context_id3)
                                                        self.statusbar_push(self.statusbar3, self.context_id3,\
							'There are %s images' % self.n)
                                                self.selected = []
                                                return False
                elif self.version + 'Albums/' in self.window1.get_title() :
                        files = os.listdir(self.ark + self.album)
                        for item in self.selected:
                                format = os.path.splitext(item)[1]
                                if format.lower() in self.raw_formats:
					fname = os.path.split(item)[1].replace('.thumb.jpg', '')
                                else:
                                        fname = os.path.split(item)[1]
                                if fname in files:
                                        continue
                                else:
                                        self.label7.set_text('Attention! Unknown file: %s\n The gallery will be updated!' % fname)
                                        self.dialog6.show()
					gtk.gdk.beep()
                                        response = self.dialog6.run()
                                        if response == gtk.RESPONSE_OK:
                                                self.dialog6.hide()
                                                del self.albums[self.album]
                                                lista = []
                                                for item in files:
                                                        format = os.path.splitext(item)[1]
                                                        if format.lower() in self.raw_formats:
                                                                fname = self.ark+self.album + '/thumb/' + item[:-len(format)] +\
								'.thumb.jpg' + format
                                                                lista += [fname]
                                                        elif format.lower() in self.formats:
                                                                fname = self.ark+self.album + '/' + item
                                                                lista += [fname]
                                                self.albums[self.album] = lista
                                                self.make_album_gallery(self)
                                                self.selected = []
                                                return False
                return True

        def pre_add_selection(self, event):
                if self.selected:
                        self.add_selection(self)
                else:
                        self.dialog9.show()
                        gtk.gdk.beep()
                        response = self.dialog9.run()
                        if response == gtk.RESPONSE_CLOSE or response == gtk.RESPONSE_DELETE_EVENT:
                                self.dialog9.hide()
                                        	
        def add_selection(self, event):                 # Adds selected images to album
	 	self.progressbar2.set_text('Saving to album...')
                if self.selection_control(self):
                        images = 0
                        selected = self.selected
                        self.dialog4.show()
                        response = self.dialog4.run()
                        if response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_DELETE_EVENT:
                                self.dialog4.hide()
				self.boxentry2.set_text('')
				return True
                        elif response == gtk.RESPONSE_APPLY:      
                                if not self.add_album(self, 'button'):
                                        return True
                                self.window1.window.set_cursor(self.watch)
                                if self.version + 'Albums/' not in self.window1.get_title() :
					self.dialog4.hide()
                                        if self.radiobutton6.get_active():
                                                for indice in xrange(self.n):
                                                        self.e[indice].modify_bg(gtk.STATE_NORMAL,self.gallery_color)
                                        fraction = 0.99 / len(selected)
                                        self.window5.show()
					while gtk.events_pending():
                                                gtk.main_iteration(False)
                                        for item in self.selected:
                                                self.progressbar2.set_fraction(self.progressbar2.get_fraction() + fraction)
                                                format = os.path.splitext(item)[1]
                                                if format.lower() in self.raw_formats:
                                                        source = self.rawpath[item]
                                                        dest = self.ark + self.added_album
                                                        fname = item.replace(self.temp, dest + '/thumb/')
                                                        raw = True
                                                else:
                                                        source = item
                                                        dest = self.ark + self.added_album
                                                        fname = dest + '/' + os.path.split(item)[1]
                                                        raw = False
                                                if fname in self.albums[self.added_album]:
                                                        continue
                                                else:
                                                        shutil.copy2(source, dest)
                                                        if raw:
                                                                shutil.copy(item[:-len(format)], dest + '/thumb')
                                                self.albums[self.added_album] += [fname]
                                                while gtk.events_pending():
                                                        gtk.main_iteration(False)
                                        self.window5.hide()
                                        self.selected = []
                                        self.progressbar2.set_fraction(0)
                                        album = self.added_album[:]
                                elif self.version + 'Albums/' in self.window1.get_title() : 
                                        self.dialog4.hide()
                                        if self.radiobutton6.get_active():
                                                for indice in xrange(self.n):
                                                        self.e[indice].modify_bg(gtk.STATE_NORMAL, self.gallery_color)
                                        fraction = 0.99 / len(selected)
                                        self.window5.show()
                                        for item in self.selected:
                                                self.progressbar2.set_fraction(self.progressbar2.get_fraction() + fraction)
                                                format = os.path.splitext(item)[1]
                                                if format.lower() in self.raw_formats:
                                                        source = item.replace('/thumb', '').replace('.thumb.jpg', '')
                                                        dest = self.ark + self.added_album
                                                        fname = dest + '/thumb/' + os.path.split(item)[1]
                                                        raw = True
                                                else:
                                                        source = item
                                                        dest = self.ark + self.added_album
                                                        fname = dest + '/' + os.path.split(item)[1]
                                                        raw = False
                                                if fname in self.albums[self.added_album]:
                                                        continue
                                                else:
                                                        shutil.copy2(source, dest)
                                                        if raw:
                                                                shutil.move(item[:-len(format)], dest + '/thumb')
                                                self.albums[self.added_album] += [fname]
                                                while gtk.events_pending():
                                                        gtk.main_iteration(False)
                                        self.window5.hide()
                                        self.selected = []
                                        self.progressbar2.set_fraction(0)
                                        album = self.added_album[:]
                                else:
                                        self.dialog4.hide()
                                self.boxentry2.set_text('')
				self.dialog4.hide()
                        elif response == gtk.RESPONSE_OK:
                                album = self.comboboxentry2.get_active_text()
				if album not in self.albums:
					self.dialog4.hide()
					return True
				else:
                                        self.album = album[:]	
                                if self.version + 'Albums/' + self.album in self.window1.get_title():
                                        self.dialog4.hide()
					return True
				self.window1.window.set_cursor(self.watch)
                                if self.album and self.version + 'Albums/' not in self.window1.get_title() :
                                        self.dialog4.hide()
					images = len(self.albums[self.album])
                                        if self.radiobutton6.get_active():
                                                for indice in xrange(self.n):
                                                        self.e[indice].modify_bg(gtk.STATE_NORMAL, self.gallery_color)
                                        fraction = 0.99 / len(selected)
                                        self.window5.show()
                                        for item in self.selected:
                                                self.progressbar2.set_fraction(self.progressbar2.get_fraction() + fraction)
                                                format = os.path.splitext(item)[1]
                                                if format.lower() in self.raw_formats:
                                                        source = self.rawpath[item]
                                                        dest = self.ark + self.album
                                                        fname = item.replace(self.temp, dest + '/thumb/')
                                                        raw = True
                                                else:
                                                        source = item
                                                        dest = self.ark + self.album
                                                        fname = dest + '/' + os.path.split(item)[1]
                                                        raw = False
                                                if fname in self.albums[self.album]:
                                                        continue
                                                else:
                                                        shutil.copy2(source, dest)
                                                        if raw:
                                                                shutil.copy(item[:-len(format)], dest + '/thumb')
                                                self.albums[self.album] += [fname]
                                                while gtk.events_pending():
                                                        gtk.main_iteration(False)
                                        self.window5.hide()
                                        self.selected = []
                                        self.progressbar2.set_fraction(0)
                                elif self.album and self.version + 'Albums/' in self.window1.get_title() :
                                        self.dialog4.hide()
					images = len(self.albums[self.album])
                                        if self.radiobutton6.get_active():
                                                for indice in xrange(self.n):
                                                        self.e[indice].modify_bg(gtk.STATE_NORMAL, self.gallery_color)
                                        fraction = 0.99 / len(selected)
                                        self.window5.show()
                                        for item in self.selected:
                                                bul = False
                                                self.progressbar2.set_fraction(self.progressbar2.get_fraction() + fraction)
                                                format = os.path.splitext(item)[1]
                                                if format.lower() in self.raw_formats:
                                                        source = item.replace('/thumb', '').replace('.thumb.jpg', '')
                                                        dest = self.ark + self.album
                                                        fname = dest + '/thumb/' + os.path.split(item)[1]
                                                        raw = True
                                                else:
                                                        source = item
                                                        dest = self.ark + self.album
                                                        fname = dest + '/' + os.path.split(item)[1]
                                                        raw = False
                                                if fname in self.albums[self.album]:
                                                        continue
                                                else:
                                                        shutil.copy2(source,dest)
                                                        if raw:
                                                                shutil.copy(item[:-len(format)], dest + '/thumb')
                                                self.albums[self.album] += [fname]
                                                while gtk.events_pending():
                                                        gtk.main_iteration(False)
                                        self.window5.hide()
                                        self.selected = []
                                        self.progressbar2.set_fraction(0)   
                                else:
					self.dialog4.hide()
                        if not images :
                                self.make_preview(album, self.albums[album][0])
                        self.boxentry2.set_text('')
                self.window1.window.set_cursor(None)

        def copy_and_move(self, obj):             # Copies or Moves selected files
                if obj in [self.menuitem14, self.menuitem18]:
                        command = shutil.copy2
                        title = 'Copying to...'
                elif obj in [self.menuitem15, self.menuitem19]:
                        command = shutil.move
                        title = 'Moving to...'
                if self.selection_control(self):
                        self.filechooserdialog3.show()
                        response = self.filechooserdialog3.run()
                        if response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_DELETE_EVENT:
                                self.filechooserdialog3.hide()
                                while gtk.events_pending():
                                        gtk.main_iteration(False)
                                return True
                        elif response == gtk.RESPONSE_OK:
                                self.filechooserdialog3.hide()
				while gtk.events_pending():
                                        gtk.main_iteration(False)
                                dest = self.filechooserdialog3.get_current_folder()
				self.progressbar2.set_text(title)
                                fraction = 0.99 / len(self.selected)
                                self.window5.show()
                                for item in self.selected:
                                        format = os.path.splitext(item)[1]
                                        if format.lower() in self.raw_formats:
                                                if self.version + 'Albums/' not in self.window1.get_title():
                                                        source = self.rawpath[item]
                                                else:
                                                        source = item.replace('/thumb', '').replace('.thumb.jpg', '')
                                        else:
                                                source = item
                                        outfile = dest + '/' + os.path.basename(source)
                                        if os.path.isfile(outfile):
                                                if not self.overwrite_all:
                                                        if self.overwrite_dialog2(os.path.basename(source)):
                                                                command(source, dest)
                                                else:
                                                        command(source, dest)
                                        else:
                                                command(source, dest)
                                        self.progressbar2.set_fraction(self.progressbar2.get_fraction() + fraction)
                                        while gtk.events_pending():
                                                gtk.main_iteration(False)
                                if obj in [self.menuitem14, self.menuitem18] and self.radiobutton6.get_active():
                                        for indice in xrange(self.n):
                                                self.e[indice].modify_bg(gtk.STATE_NORMAL, self.gallery_color)
                                elif obj in [self.menuitem15, self.menuitem19]:
                                        self.scrolledwindow2.get_child().destroy()
                                        if self.radiobutton7.get_active():
                                                self.hbox1.destroy()
                                        self.n = self.count_images(self)
                                        if self.n:
                                                self.make_table(self)
                                                self.attach_images(self)
                                                self.statusbar_pop(self.statusbar3, self.context_id3)
                                                self.statusbar_push(self.statusbar3, self.context_id3,\
                                                'There are %s images     Total size %f MB' % (self.n, self.total_size / 1000000.0))
                                                if self.radiobutton7.get_active():
                                                        self.make_bottom_panel(self, self.n)
                                                else:
                                                        self.make_thumbnails(self.width, self.height, self.n)

                                        else:
                                                self.statusbar_pop(self.statusbar3, self.context_id3)
                                                self.statusbar_push(self.statusbar3, self.context_id3,\
                                                'There are %s images' % self.n)
                                self.selected = []
                                self.window5.hide()
                                self.progressbar2.set_fraction(0)
                                self.overwrite_all = False

        def rename_image(self, obj):
		if self.radiobutton6.get_active():
                	if self.obj in self.event:
				self.indice = self.event.index(self.obj)
			elif  self.obj in self.e:
                        	self.indice = self.e.index(self.obj)
                        text = self.label[self.indice].get_text()
                else:
                        text = self.swin2_label.get_text()
                self.entry10.set_text(text)
                self.dialog23.show()
                response = self.dialog23.run()
                if response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_DELETE_EVENT:
                        self.dialog23.hide()
                        return True
                elif response == gtk.RESPONSE_OK:
                        self.dialog23.hide()
                        new_text = self.entry10.get_text()
                        if not new_text:
                                gtk.gdk.beep()
                                self.rename_image(self)
                        elif new_text == text:
                                self.dialog23.hide()
                        else:
                                format = os.path.splitext(self.list[self.indice])[1]
                                if format.lower() in self.raw_formats:
                                        if self.version + 'Albums/' not in self.window1.get_title():
                                                source = self.rawpath[self.list[self.indice]]
                                                if not self.overwrite_dialog(os.path.dirname(source), new_text):
                                                        return True
                                                dest = os.path.dirname(source) + '/' + new_text
                                                del self.rawpath[self.list[self.indice]]
                                                os.rename(self.list[self.indice][:-len(format)],os.path.dirname(self.list[self.indice])+'/'+\
                                                os.path.splitext(new_text)[0] + '.thumb.jpg')
                                                self.list[self.indice]=os.path.dirname(self.list[self.indice]) + '/' +\
                                                os.path.splitext(new_text)[0] + '.thumb.jpg' + format
                                                self.rawpath[self.list[self.indice]] = dest
                                        else:
                                                source = self.list[self.indice].replace('/thumb', '').replace('.thumb.jpg', '')
                                                if not self.overwrite_dialog(os.path.dirname(source), new_text):
                                                        return True
                                                os.rename(self.list[self.indice][:-len(format)], os.path.dirname(self.list[self.indice])+'/'+\
                                                os.path.splitext(new_text)[0] + '.thumb.jpg')
                                                self.list[self.indice] = os.path.dirname(self.list[self.indice]) + '/' +\
                                                os.path.splitext(new_text)[0] + '.thumb.jpg' + format
						self.albums[self.album] = self.list
                                                dest = os.path.dirname(source) + '/' + new_text
                                else:
                                        source = self.list[self.indice]
                                        if not self.overwrite_dialog(os.path.dirname(source), new_text):
                                                return True
                                        self.list[self.indice] = os.path.dirname(self.list[self.indice]) + '/' + new_text
                                        dest = os.path.dirname(source) + '/' + new_text
                                os.rename(source, dest)
                                if self.radiobutton6.get_active():
                                        self.label[self.indice].set_text(new_text)
                                        for indice in xrange(self.n):
                                                self.e[indice].modify_bg(gtk.STATE_NORMAL, self.gallery_color)
                                else:
                                        self.swin2_label.set_text(new_text)
				self.selected = []
                        self.overwrite_thumb = False
                           
        def delete_files(self, obj):                 # Deletes selected files from a directory.
                if self.selection_control(self):
                        self.dialog5.show()
                        gtk.gdk.beep()
                        response = self.dialog5.run()
                        if response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_DELETE_EVENT:
                                self.dialog5.hide()
                                return True
                        elif response == gtk.RESPONSE_OK:
                                self.dialog5.hide()
                                while gtk.events_pending():
                                        gtk.main_iteration(False)
		       		self.progressbar2.set_text('Deleting...')
                                fraction = 0.99 / len(self.selected)
                                self.window5.show()
                                for item in self.selected:
                                        format = os.path.splitext(item)[1]
                                        if format.lower() in self.raw_formats:
                                                source = self.rawpath[item]
                                        else:
                                                source = item
                                        os.remove(source)
                                        self.progressbar2.set_fraction(self.progressbar2.get_fraction() + fraction)
                                        while gtk.events_pending():
                                                gtk.main_iteration(False)
				self.scrolledwindow2.get_child().destroy()
                                if self.radiobutton7.get_active():
                                        self.hbox1.destroy()
                                self.n = self.count_images(self)
                                if self.n:
                                	self.make_table(self)
                                        self.attach_images(self)
                                        self.statusbar_pop(self.statusbar3, self.context_id3)
                                        self.statusbar_push(self.statusbar3, self.context_id3,\
					'There are %s images     Total size %f MB' % (self.n,self.total_size / 1000000.0))
                                        if self.radiobutton7.get_active():
                                                self.make_bottom_panel(self, self.n)
                                        else:
                                                self.make_thumbnails(self.width, self.height, self.n)

                                else:
                                        self.statusbar_pop(self.statusbar3, self.context_id3)
                                        self.statusbar_push(self.statusbar3, self.context_id3,\
					'There are %s images' % self.n)
                                self.selected = []
                                self.window5.hide()
                                self.progressbar2.set_fraction(0)
                                               
        def overwrite_dialog2(self, outfile):
                self.label93.set_text('A file named "%s" \nalready exists! Overwrite it?' % outfile)
                self.dialog22.show()
                gtk.gdk.beep()
                response = self.dialog22.run()
                if response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_DELETE_EVENT:
                        self.dialog22.hide()
                        while gtk.events_pending():
                                gtk.main_iteration(False)
                        return False
                elif response == gtk.RESPONSE_OK:
                        self.dialog22.hide()
                        while gtk.events_pending():
                                gtk.main_iteration(False)
                        return True
                elif response == gtk.RESPONSE_APPLY:
                        self.dialog22.hide()
                        while gtk.events_pending():
                                gtk.main_iteration(False)
                        self.overwrite_all = True
                        return True
                
	def set_album_preview(self, obj):
		while gtk.events_pending():
                        gtk.main_iteration(False)
		if self.radiobutton6.get_active():
			if self.obj in self.event:
				self.indice = self.event.index(self.obj)
			elif  self.obj in self.e:
                        	self.indice = self.e.index(self.obj)
		self.make_preview(self.album, self.list[self.indice])

        def make_preview(self,album, infile):
                format = os.path.splitext(infile)[1]
                if format.lower() in self.raw_formats:
                        outfile = infile[:-len(format)]
                else:
                        outfile = infile
                pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(outfile, 100, 53)
                pixbuf = self.add_thumbnail_border(pixbuf, 0x00000000, True)
                pixbuf.save(self.ark + album + '/_preview_.png', "png")
                iter0 = self.model.get_iter_first()
                value = ''
                while value != album:
                        value = self.model.get_value(iter0, 1)
                        if value == album:
                                break
                        iter0 = self.model.iter_next(iter0)
                self.model.set_value(iter0, 0, pixbuf)
                self.treeview1.set_model(self.model)
                del pixbuf
		
        def delete_selection(self, event):               #Deletes selection from album
                if self.selection_control(self):
                        if not self.selected:
                                self.dialog9.show()
                                gtk.gdk.beep()
                                response = self.dialog9.run()
                                if response == gtk.RESPONSE_CLOSE or response == gtk.RESPONSE_DELETE_EVENT:
                                        self.dialog9.hide()
                        else:        
                                self.dialog5.show()
                                response = self.dialog5.run()
                                if response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_DELETE_EVENT:
                                        self.dialog5.hide()
                                elif response == gtk.RESPONSE_OK:
                                        for item in self.selected:
                                                self.albums[self.album].remove(item)
                                        if self.radiobutton6.get_active():
                                                for item in xrange(self.n):
                                                        self.e[item].modify_bg(gtk.STATE_NORMAL, self.gallery_color)
                                        self.dialog5.hide()
                                        self.make_album_gallery(self)
                                for item in self.selected:
                                        bul = False
                                        format = os.path.splitext(item)[1]	
                                        for key in self.albums:
                                                if item in self.albums[key]:
                                                        bul = True
                                                        break
                                                else:
                                                        continue	
                                        if not bul:
                                                if format.lower() in self.raw_formats:
                                                        os.remove(item[:-len(format)])
                                                        os.remove(item.replace('/thumb', '').replace('.thumb.jpg', ''))
                                                        while gtk.events_pending():
                                                                gtk.main_iteration(False)
                                                else:
                                                        os.remove(item)
                                                        while gtk.events_pending():
                                                                gtk.main_iteration(False)
				if not self.n:
					iter0 = self.model.get_iter_first()
                			value=''
                			while value != self.album:
                        			value = self.model.get_value(iter0, 1)
                        			if value == self.album:
                                                        break
                        			iter0 = self.model.iter_next(iter0)
					self.model.set_value(iter0, 0, gtk.gdk.pixbuf_new_from_file('icons/no_preview.png'))
					self.treeview1.set_model(self.model)
                self.selected = []

        def make_raw(self, infile, format, i):
                preview = self.temp + os.path.splitext(os.path.split(infile)[1])[0] + '.thumb.jpg'  
                os.system('dcraw -c -e "%s" > "%s"' % (infile, preview))
                thumb = preview + format  
                self.list[i] = thumb
                self.rawpath[thumb] = infile
		if self.checkbutton2.get_active():
                        self.autorotate(infile, i)
                return thumb
                
	def autorotate(self, infile, i):               # Autorotates thumbnails
		f = open(infile, 'rb')
		tags = exif.process_file(f , details = False)
		f.close()
		if tags and tags.has_key('Image Orientation'):
			if 'Rotated 90 CCW' in str(tags['Image Orientation']):
				self.rotated[i] = gtk.gdk.PIXBUF_ROTATE_COUNTERCLOCKWISE
				self.rotate = gtk.gdk.PIXBUF_ROTATE_COUNTERCLOCKWISE	
			elif 'Rotated 90 CW' in str(tags['Image Orientation']):
				self.rotated[i] = gtk.gdk.PIXBUF_ROTATE_CLOCKWISE
				self.rotate = gtk.gdk.PIXBUF_ROTATE_CLOCKWISE
			else:
                                self.rotate = False
		else:
			status, output = commands.getstatusoutput('exiftool -s -s -s -n -Orientation -Rotation "%s" ' % infile)
			if output:
				if output in ['8','270']:
					self.rotated[i] = gtk.gdk.PIXBUF_ROTATE_COUNTERCLOCKWISE
					self.rotate = gtk.gdk.PIXBUF_ROTATE_COUNTERCLOCKWISE
				elif output in ['6','90']:
					self.rotated[i] = gtk.gdk.PIXBUF_ROTATE_CLOCKWISE
					self.rotate = gtk.gdk.PIXBUF_ROTATE_CLOCKWISE
				else:
                                        self.rotate = False
			
        def stop_thumbnails(self, event):
                self.stop_thumb = 1
		
	def sort_files(self, filelist):
		if self.sort_by_name.get_active():
			return sorted(filelist, cmp = lambda x, y: cmp(os.path.basename(x).lower(), os.path.basename(y).lower()))
		elif self.sort_by_type.get_active():
			filelist.sort(cmp = lambda x, y: cmp(os.path.basename(x).lower(), os.path.basename(y).lower()))
			return sorted(filelist, cmp = lambda x, y : cmp(os.path.splitext(x)[1].lower(), os.path.splitext(y)[1].lower()))
		elif self.sort_by_reverse.get_active():
			return sorted(filelist, cmp = lambda x, y: cmp(os.path.basename(x).lower(), os.path.basename(y).lower()),reverse = True)
		elif self.sort_by_random.get_active():
			return filelist

	def scan_subfolder(self, folder, tag, join, get_size, get_format, total_size, formats_, raw_formats, get_iptc_keywords):
		list_ = []
		for root, dirs, files in os.walk(folder):
			gobject.idle_add(self.progressbar5.set_text, root)
			for name in files:
				format = get_format(name)[1]
                                if format.lower() in formats_:
                                        item = join(root, name)
                                        info_list = get_iptc_keywords(item, format)
                                        if tag in info_list:
                                                list_ += [item]
                                                total_size += get_size(item)
						text = '%s images found' % len(list_)
                                                gobject.idle_add(self.label163.set_text, text)
                                elif format.lower() in raw_formats:
                                        item = join(root, name)
                                        info_list = get_iptc_keywords(item, format)
                                        if tag in info_list:
                                                list_ += [item]
                                                total_size += get_size(item)
						text = '%s images found' % len(list_)
                                                gobject.idle_add(self.label163.set_text, text)
                                if self.stop_progressbar5.isSet():
                                        break
                        if self.stop_progressbar5.isSet():
                                break
		self.list, self.total_size = list_, total_size
		if not self.stop_progressbar5.isSet():
			self.stop_progressbar5.set()
		gobject.idle_add(self.progressbar5.set_text, '')

	def pulse_progressbar5(self):
                while not self.stop_progressbar5.isSet():
                        self.progressbar5.pulse()
			while gtk.events_pending():
                                gtk.main_iteration(False)
                        time.sleep(1)
                self.stop_progressbar5.clear()

        def on_abort_button_clicked(self, obj):
		self.stop_progressbar5.set()
		while gtk.events_pending():
                        gtk.main_iteration(False)
							
	def count_images(self, event):
		self.list = []
		self.total_size = 0
		total_size = self.total_size
		get_size = os.path.getsize
		get_format = os.path.splitext
		formats_ = self.formats
		raw_formats = self.raw_formats
		get_iptc_keywords = self.get_iptc_keywords
		if not self.checkbutton28.get_active():
                        files = glob.glob(self.cartella + '/*')
                        for item in files:
                                format = get_format(item)[1]
                                if format.lower() in formats_:
                                        self.list += [item]
                                        total_size += get_size(item)
                                elif format.lower() in raw_formats:
                                        self.list += [item]
                                        total_size += get_size(item)
                        self.total_size = total_size
                        return len(self.list)
                else:
                        tag = self.combobox14.get_active_text()
                        tagged_list = []
			if not self.checkbutton29.get_active():
                        	files = glob.glob(self.cartella + '/*')
				self.label163.set_text('')
				len_files = len(files)
				if len_files < 2:
					len_files = 1.0
				fraction = 0.99 / len_files
                        	self.window9.show()
				while gtk.events_pending():
                        		gtk.main_iteration(False)
                        	for item in files:
                                	format = get_format(item)[1]
                                	if format.lower() in formats_ + raw_formats:
                                                info_list = get_iptc_keywords(item, format)
                                                if tag in info_list:
                                                        tagged_list += [item]
                                                        total_size += get_size(item)
							self.label163.set_text('%s images found' % len(tagged_list))
					self.progressbar5.set_fraction(self.progressbar5.get_fraction() + fraction)
					while gtk.events_pending():
                        			gtk.main_iteration(False)
					if self.stop_progressbar5.isSet():
                                        	break
				self.window9.hide()
				self.progressbar5.set_fraction(0)
                                self.total_size = total_size
                                self.list = tagged_list[:]
				self.stop_progressbar5.clear()
                                return len(self.list)
			else:
                        	thread.start_new_thread(self.scan_subfolder, (self.cartella, tag, os.path.join, \
                                                        get_size, get_format, total_size, formats_, raw_formats, \
                                                        get_iptc_keywords))
				self.label163.set_text('')
                        	self.window9.show()
                                self.pulse_progressbar5()
                                self.window9.hide()
                        return len(self.list)
                                
	def make_table(self, event):
                if self.scrolledwindow6:
                        self.scrolledwindow6.destroy()
		while gtk.events_pending():
                        gtk.main_iteration(False)
                self.rect2 = self.scrolledwindow2.get_allocation()
                self.n_columns = (self.rect2.width - 20) / (self.width+20)
		self.rows = int(math.ceil(self.n / float(self.n_columns)))
		self.table = gtk.Table(self.rows, self.n_columns, False)
		self.table.set_row_spacings(20)
		self.table.set_col_spacings(20)
		self.table.set_border_width(20)
		self.eb.add(self.table)
		self.eb.modify_bg(gtk.STATE_NORMAL, self.colorbutton1.get_color())
		self.scrolledwindow2.add_with_viewport(self.eb)
		self.table.show()
		
	def attach_images(self, event):
                img_n = self.n
		self.image = [ gtk.Image() for i in xrange(img_n) ]
		self.e = [ gtk.EventBox() for i in xrange(img_n) ]
		self.event = [ gtk.EventBox() for i in xrange(img_n) ]
		if self.rows > 1:
			n = 0
			for y in xrange(img_n / self.n_columns):
				for x in xrange(self.n_columns):
					self.vbox = gtk.VBox()
					self.event[n].add(self.image[n])
                                        self.event[n].add_events(gtk.gdk.BUTTON_PRESS_MASK)
                                        self.event[n].connect("button_press_event", self.select_photo)
                                        self.event[n].modify_bg(gtk.STATE_NORMAL, self.gallery_color)
 					self.e[n].add_events(gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.ENTER_NOTIFY_MASK)
 					self.e[n].connect("button_press_event", self.select_photo)
					self.e[n].modify_bg(gtk.STATE_NORMAL, self.gallery_color)
					self.table.attach(self.vbox, x, x + 1, y, y + 1, xoptions = 0, yoptions = 0)
					self.vbox.pack_start(self.event[n], expand = True, fill = True)
					self.vbox.pack_start(self.e[n], expand = False, fill = False)
					n += 1
			resto = img_n % self.n_columns
			if resto > 0:
				for x in xrange(resto):
					self.vbox = gtk.VBox()
					self.event[n].add(self.image[n])
                                        self.event[n].add_events(gtk.gdk.BUTTON_PRESS_MASK)
                                        self.event[n].connect("button_press_event", self.select_photo)
                                        self.event[n].modify_bg(gtk.STATE_NORMAL, self.gallery_color)
 					self.e[n].add_events(gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.ENTER_NOTIFY_MASK)
 					self.e[n].connect("button_press_event", self.select_photo)
					self.e[n].modify_bg(gtk.STATE_NORMAL, self.gallery_color)
					self.table.attach(self.vbox, x, x + 1, y + 1, y + 2, xoptions = 0, yoptions = 0)
					self.vbox.pack_start(self.event[n], expand = True, fill = True)
					self.vbox.pack_start(self.e[n], expand = False, fill = False)
					n += 1
		else:
			for x in xrange(img_n):
				self.vbox = gtk.VBox()
				self.event[x].add(self.image[x])
                                self.event[x].add_events(gtk.gdk.BUTTON_PRESS_MASK)
                                self.event[x].connect("button_press_event", self.select_photo)
                                self.event[x].modify_bg(gtk.STATE_NORMAL, self.gallery_color)
 				self.e[x].add_events(gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.ENTER_NOTIFY_MASK)
 				self.e[x].connect("button_press_event", self.select_photo)
				self.e[x].modify_bg(gtk.STATE_NORMAL, self.gallery_color)
				self.table.attach(self.vbox, x, x + 1, 0, 1, xoptions = 0, yoptions = 0)
				self.vbox.pack_start(self.event[x])
				self.vbox.pack_start(self.e[x], expand = False, fill = False)

        def make_thumbnails(self, width, height, img_n):
		self.rotated = {}
		cache_list = self.cache_list
		get_filename = self.get_filename
		add_thumbnail_border = self.add_thumbnail_border
		self.radiobutton6.set_active(True)
		self.settings['radiobutton6'] = True
		self.settings['radiobutton7'] = False
		self.toolbuttons(self, False, True)    
		self.b_pixlist = range(3)
		while gtk.events_pending():
                        gtk.main_iteration(False)
		self.progressbar3.show()        
		self.button5.show()             
                self.treeview1.handler_block(self.id3)
                self.open1.handler_block(self.id4)
		self.toolbutton16.handler_block(self.id1)
		self.toolbutton17.handler_block(self.id2)
		self.open_folder1.handler_block(self.id5)
		self.open_album1.handler_block(self.id6)
		self.treeview2.handler_block(self.id7)
		self.toolbutton1.handler_block(self.id8)
		self.toolbutton14.handler_block(self.id9)
		self.toolbutton15.handler_block(self.id10)
		self.toolbutton18.handler_block(self.id11)
		self.toolbutton19.handler_block(self.id12)
		self.toolbutton20.handler_block(self.id13)
		self.toolbutton21.handler_block(self.id19)
		self.toolbutton26.handler_block(self.id23)
		self.toolbutton27.handler_block(self.id24)
		self.toolbutton28.handler_block(self.id39)
		self.toolbutton29.handler_block(self.id26)
		self.toolbutton30.handler_block(self.id30)
		self.hpaned1.handler_block(self.id28)
		self.new1.handler_block(self.id14)
		self.delete2.handler_block(self.id15)
		self.add_selection1.handler_block(self.id16)
		self.delete_selection1.handler_block(self.id17)
		i = 0
		fraction = 0.99 / img_n 
		self.label = range(img_n) 
		self.list = self.sort_files(self.list)
		list_ = self.list
		for infile in list_:   	
			try:
				infile, filename = get_filename(infile, i)
                                preview = str(hash(filename)) + '.jpeg'
				if self.checkbutton7.get_active():
                                        if preview not in cache_list:
                                                pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(infile, 260, 174)
						if self.rotate:
                                                        pixbuf = pixbuf.rotate_simple(self.rotate)
                                                pixbuf.save(self.cache + preview, "jpeg")
                                        pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.cache + preview, self.width, self.height)
                                else:
                                        if preview in cache_list:
                                                pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.cache + preview, self.width, self.height)
                                        else:
                                                pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(infile, self.width, self.height)
                                new_pixbuf = add_thumbnail_border(pixbuf, self.border_color, False)
				self.image[i].set_from_pixbuf(new_pixbuf)       
				self.label[i].modify_fg(gtk.STATE_NORMAL, self.label_color)
				self.label[i].modify_font(self.font_desc)
				self.label[i].set_size_request(self.width, -1)
				self.e[i].add(self.label[i])
				self.e[i].add_events(gtk.gdk.ENTER_NOTIFY_MASK)
				self.e[i].connect("enter_notify_event", self.add_image_info, i)
				self.window1.show_all()
				i += 1
				del pixbuf, new_pixbuf
				self.progressbar3.set_fraction(self.progressbar3.get_fraction() + fraction)
				while gtk.events_pending():
                                        gtk.main_iteration(False)
				if self.stop_thumb == 1:
                                        break
			except gobject.GError :
				print 'error loading image'
                                self.image[i].set_from_stock(gtk.STOCK_MISSING_IMAGE, 5)
                                self.e[i].add(self.label[i])
                                i += 1
                                self.window1.show_all()
                                while gtk.events_pending():
                                        gtk.main_iteration(False)
       		self.progressbar3.set_fraction(0)
       		self.treeview1.handler_unblock(self.id3)
                self.open1.handler_unblock(self.id4)
		self.toolbutton16.handler_unblock(self.id1)
		self.toolbutton17.handler_unblock(self.id2)
		self.open_folder1.handler_unblock(self.id5)
		self.open_album1.handler_unblock(self.id6)
		self.treeview2.handler_unblock(self.id7)
		self.toolbutton1.handler_unblock(self.id8)
		self.toolbutton14.handler_unblock(self.id9)
		self.toolbutton15.handler_unblock(self.id10)
		self.toolbutton18.handler_unblock(self.id11)
		self.toolbutton19.handler_unblock(self.id12)
		self.toolbutton20.handler_unblock(self.id13)
		self.toolbutton21.handler_unblock(self.id19)
		self.toolbutton26.handler_unblock(self.id23)
		self.toolbutton27.handler_unblock(self.id24)
		self.toolbutton28.handler_unblock(self.id39)
		self.toolbutton29.handler_unblock(self.id26)
		self.hpaned1.handler_unblock(self.id28)
		self.toolbutton30.handler_unblock(self.id30)
		self.new1.handler_unblock(self.id14)
		self.delete2.handler_unblock(self.id15)
		self.add_selection1.handler_unblock(self.id16)
		self.delete_selection1.handler_unblock(self.id17)
		self.stop_thumb = 0
		self.progressbar3.hide()
		self.button5.hide()
		self.statusbar_pop(self.statusbar4, self.context_id4)
                self.statusbar_push(self.statusbar4, self.context_id4, '')
		self.cache_list = os.listdir(self.cache)
		thread.start_new_thread(self.cache_control, ())
		self.list = list_[:]
		gc.collect()
		
	def make_bottom_panel(self, event, img_n=None):
                if not img_n:
                        img_n = self.n
		self.rotated = {}
		cache_list = self.cache_list
		get_filename = self.get_filename
		add_thumbnail_border = self.add_thumbnail_border
		if self.radiobutton7.get_active() and self.hpaned1.get_position() != int(gtk.gdk.screen_width() * 0.15):
			self.vpaned2.handler_block(self.id27)	
			self.hpaned1.set_position(int(gtk.gdk.screen_width() * 0.15))
			self.vpaned2.handler_unblock(self.id27)
			return True
		if self.scrolledwindow6:
                        self.scrolledwindow6.destroy()	
		if self.radiobutton6.get_active() and not self.close_panel:
			self.hpaned1.set_position(int(gtk.gdk.screen_width() * 0.15))
			self.close_panel = False
			while gtk.events_pending():
                                gtk.main_iteration(False)
		elif self.radiobutton6.get_active() and self.close_panel:
			self.hpaned1.set_position(0)
			self.close_panel = False
			while gtk.events_pending():
                                gtk.main_iteration(False)		
		self.radiobutton7.set_active(True)
		self.settings['radiobutton7'] = True
		self.settings['radiobutton6'] = False
		self.toolbuttons(self, True, False)
		self.toolbutton1.handler_block(self.id8)
		self.toolbutton14.handler_block(self.id9)
		self.toolbutton15.handler_block(self.id10)
		self.toolbutton16.handler_block(self.id1)
		self.toolbutton17.handler_block(self.id2)
		self.toolbutton21.handler_block(self.id19)
		self.toolbutton26.handler_block(self.id23)
		self.toolbutton27.handler_block(self.id24)
		self.toolbutton28.handler_block(self.id39)
		self.toolbutton29.handler_block(self.id26)
		self.toolbutton30.handler_block(self.id30)
		self.toolbutton31.handler_block(self.id31)
		self.toolbutton32.handler_block(self.id32)
		self.toolbutton33.handler_block(self.id33)
		self.toolbutton34.handler_block(self.id34)
                self.vpaned2.handler_block(self.id27)
		self.hpaned1.handler_block(self.id28)
                self.progressbar3.show()
		self.button5.show()
                viewport = self.scrolledwindow2.get_child()  
                if viewport:
                        viewport.destroy()                 
                self.vbox1 = gtk.VBox(False,0)
                self.swin2_image = gtk.Image()
                self.swin2_label = gtk.Label()
		self.swin2_label.modify_fg(gtk.STATE_NORMAL, self.label_color)
		self.swin2_label.modify_font(self.font_desc)
                self.vbox1.pack_start(self.swin2_image, True, True, 0)
                self.vbox1.pack_start(self.swin2_label, False, False, 0)
                self.scrolledwindow2.add_with_viewport(self.vbox1)
		viewport = self.scrolledwindow2.get_child()  
		viewport.add_events(gtk.gdk.BUTTON_RELEASE_MASK | gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON1_MOTION_MASK | gtk.gdk.POINTER_MOTION_HINT_MASK)
		viewport.connect('button_release_event', self.on_scrolledwindow_release_event)
		viewport.connect('button_press_event', self.on_scrolledwindow_release_event)
		viewport.connect('motion_notify_event', self.hand_image)
                if img_n:
			self.scrolledwindow2.get_child().modify_bg(gtk.STATE_NORMAL, self.image_background_color)
		else:
                        self.scrolledwindow2.get_child().modify_bg(gtk.STATE_NORMAL, self.gallery_color)
		self.rect = self.scrolledwindow2.allocation
		self.scrolledwindow2.set_size_request(-1, self.rect.height - self.height + 30)
                self.eventbox9 = gtk.EventBox()
		self.eventbox9.set_size_request(-1, self.height + 30)
		self.eventbox9.modify_bg(gtk.STATE_NORMAL, self.gallery_color)
		self.eventbox9.add_events(gtk.gdk.SCROLL_MASK)
		self.eventbox9.connect("scroll_event", self.scroll_bottom_panel)
                self.scrolledwindow6 = gtk.ScrolledWindow()
                self.hbox1 = gtk.HBox(False, 0)
		self.eventbox9.add(self.hbox1)
                self.scrolledwindow6.set_policy(gtk.POLICY_ALWAYS, gtk.POLICY_NEVER)
                self.scrolledwindow6.add_with_viewport(self.eventbox9)
                self.vpaned2.pack2(self.scrolledwindow6, False, False)
		self.vpaned2.set_position(int(gtk.gdk.screen_height()) - self.height + 30)
                self.label = range(img_n) 
                self.b_img = [ gtk.Image() for i in xrange(img_n) ]
		self.b_event = [ gtk.EventBox() for i in xrange(img_n) ]
                for i in xrange(img_n):
			self.b_event[i].modify_bg(gtk.STATE_NORMAL, self.gallery_color)
			self.b_event[i].add_events(gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.ENTER_NOTIFY_MASK)
			self.b_event[i].add(self.b_img[i])
			self.hbox1.pack_start(self.b_event[i], True, True, 0)
		self.window1.show_all()
		while gtk.events_pending():
                        gtk.main_iteration(False)
		if img_n:
			self.b_event[0].modify_bg(gtk.STATE_NORMAL, self.selection_color)
			fraction = 0.99 / img_n
		self.window1.show_all()
		i = 0
		self.indice = 0
		self.pixindex = 1
		self.b_pixlist = range(3)
		self.list = self.sort_files(self.list)
		list_ = self.list
		for infile in list_:
                        try:
                                infile, filename = get_filename(infile, i)
                                preview = str(hash(filename)) + '.jpeg'
                                if self.checkbutton7.get_active():
                                        if preview not in cache_list:
						pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(infile, 260, 174)
						if self.rotate:
                                                        pixbuf = pixbuf.rotate_simple(self.rotate)
                                                pixbuf.save(self.cache + preview, "jpeg")
					pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.cache + preview, self.width, self.height)
				else:
                                        if preview in cache_list:
                                                pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(self.cache + preview, self.width,self.height)
                                        else:
                                                pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(infile, self.width, self.height)
				new_pixbuf = add_thumbnail_border(pixbuf, self.border_color, False)
				self.b_event[i].connect("button_press_event", self.select_b_photo)
				self.b_event[i].connect("enter_notify_event", self.add_image_info, i)
				self.b_event[i].set_size_request(new_pixbuf.get_width() + 20, self.height + 30)
                                self.b_img[i].set_from_pixbuf(new_pixbuf)
                                if i == 0:
					self.swin2_label.set_text(self.label[0].get_text())
					while gtk.events_pending():
                                                gtk.main_iteration(False)
					self.rect2 = self.scrolledwindow2.get_allocation()
					if self.rotated.has_key(i) and self.checkbutton2.get_active():
						self.b_pixlist[self.pixindex] = gtk.gdk.pixbuf_new_from_file_at_size(infile,\
                        			self.rect2.height - self.swin2_label.allocation.height, self.rect2.width)
						self.b_pixlist[self.pixindex] = self.b_pixlist[self.pixindex].rotate_simple(self.rotated[i])
					else:	
						self.b_pixlist[self.pixindex] = gtk.gdk.pixbuf_new_from_file_at_size(infile,\
                        			self.rect2.width,self.rect2.height - self.swin2_label.allocation.height)
					format = os.path.splitext(infile)[1]
					self.b_pixlist[self.pixindex] = self.check_icons(format, self.b_pixlist[self.pixindex])
					self.swin2_image.set_from_pixbuf(self.b_pixlist[self.pixindex])
					while gtk.events_pending():
                                                gtk.main_iteration(False)
				if i == 1:
					thread.start_new_thread(self.load_b_cache, (self.rect2.width, self.rect2.height))
                                self.window1.show_all()
                                i += 1
                                del pixbuf, new_pixbuf
                                self.progressbar3.set_fraction(self.progressbar3.get_fraction() + fraction)
                                while gtk.events_pending():
                                        gtk.main_iteration(False)
                                if self.stop_thumb == 1:
                                        break
                        except gobject.GError :
				print 'error loading image'
                                self.b_img[i].set_from_stock(gtk.STOCK_MISSING_IMAGE, 5)
                                i += 1
                                self.window1.show_all()
                                while gtk.events_pending():
                                        gtk.main_iteration(False)
                self.stop_thumb = 0
		self.progressbar3.hide()
                self.progressbar3.set_fraction(0)
		self.button5.hide()
		self.toolbutton1.handler_unblock(self.id8)
		self.toolbutton14.handler_unblock(self.id9)
		self.toolbutton15.handler_unblock(self.id10)
		self.toolbutton16.handler_unblock(self.id1)
		self.toolbutton17.handler_unblock(self.id2)
		self.toolbutton21.handler_unblock(self.id19)
		self.toolbutton26.handler_unblock(self.id23)
		self.toolbutton27.handler_unblock(self.id24)
		self.toolbutton28.handler_unblock(self.id39)
		self.toolbutton29.handler_unblock(self.id26)
		self.toolbutton30.handler_unblock(self.id30)
		self.toolbutton31.handler_unblock(self.id31)
		self.toolbutton32.handler_unblock(self.id32)
		self.toolbutton33.handler_unblock(self.id33)
		self.toolbutton34.handler_unblock(self.id34)
		self.vpaned2.handler_unblock(self.id27)
		self.hpaned1.handler_unblock(self.id28)
		self.cache_list = os.listdir(self.cache)
		thread.start_new_thread(self.cache_control, ())	
		self.calculate_percentage()
		gc.collect()
		
	def add_image_info(self, obj, event, i):
		try:
			if self.version + 'Albums/' in self.window1.get_title():
				filename = self.ark + self.album + '/' + self.label[i].get_text()
			else:
                                filename = self.cartella + '/' + self.label[i].get_text()
			cmd = 'exiftool -e -S -CreateDate -DateTimeOriginal -ModifyDate -Model -Software -CameraModelID -FileSize "%s" '
			output = commands.getoutput(cmd % filename)
			outputlist = output.split('\n')
			text = 'Filename: ' + self.label[i].get_text()
			for item in outputlist:
                                if 'CreateDate' in item or 'DateTimeOriginal' in item:
                                        text += '\nCreated: ' + item.split(': ')[1]
                                        break
                        for item in outputlist:
                                if 'ModifyDate' in item:
                                        text += '\nModified: ' + item.split(': ')[1]
                                        break
                        for item in outputlist:
                                if 'Model' in item:
                                        text += '\nCamera: ' + item.split(': ')[1]
                                        break
			for item in outputlist:
				if 'Software' in item:
					text += '\nSoftware: ' + item.split(': ')[1]
					break
                        for item in outputlist:
                                if 'FileSize' in item:
                                        text += '\nSize: ' + item.split(': ')[1]
                                        break
			if self.radiobutton7.get_active():
				self.tooltip.set_tip(self.b_event[i], text, None)
			else:
                                self.tooltip.set_tip(self.e[i], text, None)
		except:
			if self.radiobutton7.get_active():
				self.tooltip.set_tip(self.b_event[i], 'Filename:  ' + self.label[i].get_text(), None)
			else:
                                self.tooltip.set_tip(self.e[i], 'Filename:  ' + self.label[i].get_text(), None)         
		
	def add_thumbnail_border(self, pixbuf, border_color, data):
		if not self.checkbutton4.get_active() and not data:
                        return pixbuf
                pwidth = pixbuf.get_width()
		pheight = pixbuf.get_height()
		if border_color == 0x00000000:
			new_pixbuf = self.background.copy().scale_simple(pwidth + 2, pheight + 2, gtk.gdk.INTERP_BILINEAR)
			if pixbuf.get_has_alpha():
				new_pixbuf = new_pixbuf.add_alpha(False, chr(0), chr(0), chr(0))
			pixbuf.copy_area(0, 0, pwidth, pheight, new_pixbuf, 1, 1)
		else:
			new_pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, pwidth + 2, pheight + 2)
			new_pixbuf.fill(border_color)
			pixbuf.copy_area(0, 0, pwidth, pheight, new_pixbuf, 1, 1)
		return new_pixbuf

	def get_filename(self, infile, i):
		self.rotate = False
		autorotate = self.autorotate
		make_raw = self.make_raw
                format = os.path.splitext(infile)[1]
                if self.ark in infile:
                        if format.lower() in self.raw_formats:
				f = os.path.split(infile)[1].replace('.thumb.jpg', '')
                                self.label[i] = gtk.Label(f)
                                filename = infile.replace('/thumb', '').replace('.thumb.jpg', '')
                                infile = os.path.splitext(infile)[0]
                                if self.checkbutton2.get_active():
                                        autorotate(filename, i)
                        else:
                                self.label[i] = gtk.Label(os.path.split(infile)[1])
                                filename = infile[:]
                elif self.ark not in infile and format.lower() in self.raw_formats and self.temp not in infile:
                        infile = make_raw(infile, format, i)
                        filename = infile[:]
		else:
                        self.label[i]=gtk.Label(os.path.split(infile)[1])
                        filename = infile[:]
                if self.temp in infile:
                        f = os.path.split(infile)[1].replace('.thumb.jpg', '')		
                        self.label[i] = gtk.Label(f)
                        infile = os.path.splitext(infile)[0]
		if format.lower() in ['.jpg', '.jpeg']:
			if self.checkbutton2.get_active():
                                autorotate(filename,i)
                return infile, filename
		
	def cache_control(self):
		filelist = glob.glob(self.cache + '*')
		total_size = 0
		for item in filelist:
                        total_size += os.path.getsize(item)
		if total_size / 1000000.0 > self.cache_size:
			_dict = {}
			for item in filelist:
                                _dict[os.stat(item)[7]] = item
			lista = sorted(_dict)
			for item in _dict:
				if item == lista[0]:
					os.remove(_dict[item])
					break
		 	self.cache_control()
		else:
			self.progressbar1.set_fraction((total_size / 1000000.0) / self.cache_size)
			return True
	
	def clear_cache(self, obj):
		self.dialog8.show()
		response = self.dialog8.run()
		if response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_DELETE_EVENT:
			self.dialog8.hide()
			self.get_options(self)
		elif response == gtk.RESPONSE_OK:
			self.dialog8.hide()
			self.progressbar1.set_fraction(0)
			self.get_options(self)
			thread.start_new_thread(self.delete_cached, ())
			
	def delete_cached(self):
		for item in os.listdir(self.cache):
                        os.remove(self.cache + item)
		self.cache_list = []
		gc.collect()
		
	def close_window2(self, obj):
		self.on_delete_event(self.window2, obj)

        def on_notebook2_switched(self, *event):
		format = os.path.splitext(self.list[self.indice])[1]
		if event[0]  == self.notebook2 and event[2] in [1, 2, 3, 4, 5] and self.notebook2.get_current_page() == 0 and not self.raw_preview:
			if format.lower() in self.raw_formats:
				gobject.idle_add(self.load_raw_preview, self.rect.width, self.rect.height)
			else:
				if self.rotated.has_key(self.indice):
					self.pblist[self.pbindex] = gtk.gdk.pixbuf_new_from_file_at_size(self.list[self.indice],\
                                			            self.rect.width, self.rect.height)
					self.image1.set_from_pixbuf(self.pblist[self.pbindex])
					self.image1.show()	
		elif len(event) == 1:
			if self.notebook2.get_current_page() != 0:
			 	gobject.idle_add(self.load_raw_preview, self.rect.width, self.rect.height)
		if event[0] == self.notebook2:
                        self.set_sensitivity(format)
                        if event[2] == 3 and format.lower() in self.formats:
                                self.get_channel()
                        elif event[2] == 1:
                                self.show_tags(format)
			 
	def make_surface(self, text):
		width, height = 260, 150
                self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
                self.cr = cairo.Context(self.surface)
                self.cr.rectangle(0, 0, width, height)
                self.cr.clip()
		self.cr.set_source_rgb(0, 0, 0)
		self.cr.rectangle(0, 0, 259, 122)
        	self.cr.fill()
		self.cr.set_source_rgb(1.0, 1.0, 1.0)
        	self.cr.rectangle(1, 1, 257, 120)
        	self.cr.fill()
        	self.cr.stroke()
		self.cr.set_source_rgb(0.5, 0.5, 0.5)
		n = 51
		self.cr.set_line_width(1)
		for item in range(4):
			self.cr.move_to(0.5 + n, height - 29)
			self.cr.line_to(0.5 + n, 1)
			n += 51
		self.cr.stroke()
		if text:
			self.cr.set_source_rgb(0, 0, 0)
			self.cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
        		self.cr.set_font_size(10)
			self.cr.move_to(80, 70)
			self.cr.show_text('Loading histogram...')
		while gtk.events_pending(): 
				gtk.main_iteration(False)
		return width, height
		
	def draw_gradient(self, r, g, b):
                height = 150
		linear = cairo.LinearGradient(0, height - 20, 259, 0)
        	linear.add_color_stop_rgb(0, 0, 0, 0)
        	linear.add_color_stop_rgb(0.7, r, g, b)
		self.cr.set_source_rgb(0, 0, 0)
		self.cr.rectangle(0, height - 23 ,259, 10)
		self.cr.fill()
		self.cr.set_source(linear)
		self.cr.rectangle(1, height - 22, 257, 8)
		self.cr.fill()
        	self.cr.stroke()
		data = self.surface.get_data()  
		stride = self.surface.get_stride()
		pixbuf = gtk.gdk.pixbuf_new_from_data(data, gtk.gdk.COLORSPACE_RGB, True, 8, 259, height, stride)
		self.image19.set_from_pixbuf(pixbuf)
		while gtk.events_pending(): 
				gtk.main_iteration(False)

	def on_togglebutton1_toggled(self, obj):
		if obj == self.togglebutton1:
			self.togglebutton2.handler_block(self.id64)
                	self.togglebutton2.set_active(False)
			self.togglebutton2.handler_unblock(self.id64)
			self.togglebutton1.set_active(True)
		elif obj == self.togglebutton2:
			self.togglebutton1.handler_block(self.id63)
                	self.togglebutton1.set_active(False)
			self.togglebutton1.handler_unblock(self.id63)
			self.togglebutton2.set_active(True)
                self.get_channel()
                
	def pixbuf2image(self, data):
		assert(self.pblist[self.pbindex].get_colorspace() == gtk.gdk.COLORSPACE_RGB)
		dimensions = self.pblist[self.pbindex].get_width(), self.pblist[self.pbindex].get_height()
		stride = self.pblist[self.pbindex].get_rowstride()
		pixels = self.pblist[self.pbindex].get_pixels()
		mode = self.pblist[self.pbindex].get_has_alpha() and "RGBA" or "RGB"
		im = Image.frombuffer(mode, dimensions, pixels, "raw", mode, stride, 1)
		if data:
                        im = im.convert(data)
		hist = im.histogram()
		if self.togglebutton2.get_active():
                        hist = map(self.logarithmic_histogram, hist)
		return hist

	def logarithmic_histogram(self, x):
                if x > 1 :
                        return math.log10(x)
                else:
                        return 0
				
	def colors_histogram(self, hist):
		colors_hist = [0] * 256
		for item in xrange(256):
			colors_hist[item] = max(hist[item], hist[item + 256], hist[item + 512])
		return colors_hist
		
	def on_combobox1_changed(self, event):
                self.get_channel()
	
    	def get_channel(self):
                width = 260
                height = 150
		self.frame1.window.set_cursor(self.watch)
		channel = self.combobox1.get_active_text()
		self.make_surface(True)
		if 'Luminosity' in channel:
			self.r = 1; self.g = 1; self.b = 1; i = 0;
                        self.draw_gradient(1, 1, 1)
			self.make_surface(False)
			self.draw_gradient(1, 1, 1)
			hist = self.pixbuf2image('L')
			self.draw_channel(hist, None, 0, 0, 0, i, 1)	
		elif 'Red' in channel:
			self.r = 0; self.g = 0; self.b = 1; i = 0;
                        self.draw_gradient(self.r, self.g, self.b)
			self.make_surface(False)
			self.draw_gradient(self.r, self.g, self.b)
			hist = self.pixbuf2image(None)
			self.draw_channel(hist[:256], None, self.r, self.g, self.b, i, 1)
                elif 'Green' in channel:
			self.r = 0; self.g = 1; self.b = 0; i = 1;
                        self.draw_gradient(self.r, self.g, self.b)
			self.make_surface(False)
			self.draw_gradient(self.r, self.g, self.b)
			hist = self.pixbuf2image(None)
			self.draw_channel(hist[256:512], None, self.r, self.g, self.b, i, 1)
                elif 'Blue' in channel:
			self.r = 1; self.g = 0; self.b = 0; i = 2;
                        self.draw_gradient(self.r, self.g, self.b)
			self.make_surface(False)
			self.draw_gradient(self.r, self.g, self.b)
			hist = self.pixbuf2image(None)
			self.draw_channel(hist[512:768], None, self.r, self.g, self.b, i, 1)
                elif 'Alpha' in channel:
			self.r = 0; self.g = 1; self.b = 1 ; i = 3;
                        self.draw_gradient(self.r, self.g, self.b)
			self.make_surface(False)
			self.draw_gradient(self.r, self.g, self.b)
			hist = self.pixbuf2image(None)
			self.draw_channel(hist[768:], None, self.r, self.g, self.b, i, 2)
                elif 'Colors' in channel:
			self.r = 1; self.g = 1; self.b = 1;
                        self.draw_gradient(self.r, self.g, self.b)
                        self.make_surface(False)
			self.draw_gradient(self.r, self.g, self.b)
			hist = self.pixbuf2image(None)
			colors_hist = self.colors_histogram(hist)
			self.draw_channel(hist[:256], colors_hist, 0, 0, 1, 0, 0.7)
                       	self.draw_channel(hist[256:512], colors_hist, 0, 1, 0, 1, 0.7)
                        self.draw_channel(hist[512:768], colors_hist, 1, 0, 0, 2, 0.7)
		self.frame1.window.set_cursor(None) 

        def draw_channel(self, hist, colors_hist, r, g, b, i, w):
                height = 150
                if i == 3 and not self.pblist[self.pbindex].get_has_alpha():
                        return True
                if colors_hist:
                        h = max(colors_hist)
                else:
                        h = max(hist)
                self.cr.set_source_rgb(r, g, b)
                self.cr.set_line_width(w)
                n = 0
                for item in hist:
                        y=(item*(height - 30)) / h
                        self.cr.move_to(n + 2, height - 29)
                        self.cr.line_to(n + 2, height - 29 - y)
                        n += 1	
                self.cr.stroke()
                data = self.surface.get_data()  
		stride = self.surface.get_stride()
		pixbuf = gtk.gdk.pixbuf_new_from_data(data, gtk.gdk.COLORSPACE_RGB, True, 8, 259, height, stride)
		self.image19.set_from_pixbuf(pixbuf)
                if colors_hist:
                        hist = colors_hist[:]
		stat = ImageStat.Stat(hist)
		try:
			dimensions = self.image_size.split('x')
			self.label54.set_text('Pixels: %d' % (int(dimensions[0]) * int(dimensions[1])))
			self.label56.set_text('Count: %d' % (int(dimensions[0]) * int(dimensions[1])))
		except:
			self.label54.set_text('Pixels: ')
			self.label56.set_text('Count: ')
		self.label48.set_text('Mean: %.1f' % stat.mean[0])
		self.label49.set_text('Std Dev: %.1f' % stat.stddev[0])
		self.label53.set_text('Median: %.1f' % stat.median[0])
		self.label57.set_text('Percentile: 100.0')
		
	def on_window8_delete_event(self, *obj):
		self.window8.hide()
		return True
		
		
	def on_delete_event(self, obj, event):
		self.loop = 0
		if obj == self.window2 and self.workflow_started:
			if self.show_dialog21(True): 
				return True
		obj.hide()
		if obj != self.window7:
			for item in self.expander_list:
                        	if item.get_expanded():
                                	item.set_expanded(False)
                                	if item == self.expander17:
                                        	self.destroy_drawingarea()
                if obj == self.window2 and self.radiobutton7.get_active():
			indice = self.old_indice
                        self.indice = indice
			del self.pblist
			del self.fullpblist
			gc.collect()
                        self.pblist = range(3)
                        self.fullpblist = range(3)
		if obj == self.window4 and self.window2.get_property("visible"):
                        indice = self.win2_indice
                        self.indice = indice
			if self.checkbutton6.get_active() and self.pid:
				os.kill(self.pid, 9)
				os.wait()
                elif obj == self.window4 and not self.window2.get_property("visible"):
                        indice = self.old_indice
                        self.indice = indice
			if self.checkbutton6.get_active() and self.pid:
				os.kill(self.pid, 9)
				os.wait()
		self.pid = self.count = 0
		if obj == self.window2: 
			self.combobox1.set_active(0)
			self.image1.clear()
		return True

	def on_delete_window3(self, obj, event):
                if self.window2.get_property("visible"):
                        while gtk.events_pending(): 
				gtk.main_iteration(False)
                        format = os.path.splitext(self.list[self.indice])[1]
                        self.set_image1(format)
                        self.window2.show_all()
                        if self.settings['checkbutton1']: 
				self.frame1.hide_all()	
                        while gtk.events_pending(): 
				gtk.main_iteration(False)
                        self.add_dimensions(format, self._label)
			if self.notebook2.get_current_page() == 3: 
				self.on_notebook2_switched(self)
                        obj.hide()
                        del self.fullpblist
                        gc.collect()
                        self.fullpblist = range(3)
                        while gtk.events_pending(): 
				gtk.main_iteration(False)
                        thread.start_new_thread(self.load_cache, (self.rect.width, self.rect.height,None))
                else:
                        obj.hide()
                        del self.fullpblist
                        gc.collect()
                        self.fullpblist = range(3)
                        indice = self.old_indice
                        self.indice = indice
                        while gtk.events_pending(): 
				gtk.main_iteration(False)
		
	def hide_win6(self, obj):
		self.window6.hide()
		self.stop_thread.set()
		self.unselect(self)
		return True

	def main(self):
                gtk.main()
		
	def destroy(self, *widget):
		self.settings['filechooserbutton7'] = self.filechooserbutton7.get_current_folder()
		self.settings['combobox10'] = self.combobox10.get_active()
		self.settings['hscale23'] = self.hscale23.get_adjustment().value 
                self.settings['window1_size'] = self.window1.get_size()
                self.store_dcraw_settings(self)
                fl = open('settings', 'w')
                cPickle.dump(self.settings, fl)
                fl.close()
		f = open(self.ark + 'albums.db', 'w')
                cPickle.dump(self.albums, f)
	        f.close()
		self.batch_list[0] = [[row[0], row[2], row[3], row[4]] for row in self.batchmodel]
		self.batch_list[1] = self.batch_queue
		f = open('batch.db', 'w')
		cPickle.dump(self.batch_list, f)
	        f.close()
                for item in os.listdir('.thumbnails'): 
			os.remove('.thumbnails/' + item)
                for item in os.listdir('.raw'):        
			os.remove('.raw/' + item)	
		for item in os.listdir('.temp'):       
			os.remove('.temp/' + item)	
                gtk.main_quit()	

if __name__ == "__main__":
	gtkrawgallery = Gallery()
	gtkrawgallery.main()
