#!/usr/bin/perl

my $verbose = 1;

use Gtk2 '-init';

use XML::Simple;
use Locale::Messages qw(textdomain gettext dgettext bind_textdomain_filter turn_utf_8_on);
use strict;
use utf8;
use File::Find;
use IPC::Open3;

bind_textdomain_filter 'lemonrip', \&turn_utf_8_on;
bind_textdomain_filter 'iso_639', \&turn_utf_8_on;
textdomain("lemonrip");

binmode STDOUT, ":utf8";
binmode STDERR, ":utf8";

use constant FATAL_ERROR => "FATAL_ERROR";
use constant ERROR => "ERROR";
use constant INFO => "INFO";
use constant HINT => "HINT";
use constant MPLAYER => "MPLAYER";

use constant MEDIA_OK => 'media_ok';
use constant MEDIA_ERROR => 'media_error'; 
use constant MEDIA_NOT_FOUND => 'media_not_found';

use constant DVD => 'dvd';
use constant FILE => 'file';

use constant SEEK_UNKNOWN => 'seek_unknown';
use constant SEEK_BYTE => 'seek_byte';
use constant SEEK_FULL => 'seek_full';
use constant SEEK_NONE => 'seek_none';

use constant CROP_NO_CROP => 'crop_no_crop';
use constant CROP_AUTO => 'crop_auto';
use constant CROP_USER => 'crop_user';
use constant CROP_READY => 'crop_ready';

my $canceled;
my $menc_id = undef;
my $version = "1.20";
my $mplayer_timeout = 10;

my $iso_639 = {
	'aa'=> 'Afar',
	'ab'=> 'Abkhazian',
	'ae'=> 'Avestan',
	'af'=> 'Afrikaans',
	'ak'=> 'Akan',
	'am'=> 'Amharic',
	'an'=> 'Aragonese',
	'ar'=> 'Arabic',
	'as'=> 'Assamese',
	'av'=> 'Avaric',
	'ay'=> 'Aymara',
	'az'=> 'Azerbaijani',
	'ba'=> 'Bashkir',
	'be'=> 'Byelorussian',
	'bg'=> 'Bulgarian',
	'bh'=> 'Bihari',
	'bi'=> 'Bislama',
	'bm'=> 'Bambara',
	'bn'=> 'Bengali; Bangla',
	'bo'=> 'Tibetan',
	'br'=> 'Breton',
	'bs'=> 'Bosnian',
	'ca'=> 'Catalan',
	'ce'=> 'Chechen',
	'ch'=> 'Chamorro',
	'co'=> 'Corsican',
	'cr'=> 'Cree',
	'cs'=> 'Czech',
	'cu'=> 'Old Church Slavonic',
	'cv'=> 'Chuvash',
	'cy'=> 'Welsh',
	'da'=> 'Danish',
	'de'=> 'German',
	'dv'=> 'Divehi',
	'dz'=> 'Dzongkha',
	'ee'=> 'Ewe',
	'el'=> 'Greek, Modern',
	'en'=> 'English',
	'eo'=> 'Esperanto',
	'es'=> 'Spanish',
	'et'=> 'Estonian',
	'eu'=> 'Basque',
	'fa'=> 'Persian',
	'ff'=> 'Fulah',
	'fi'=> 'Finnish',
	'fj'=> 'Fiji',
	'fo'=> 'Faroese',
	'fr'=> 'French',
	'fy'=> 'Frisian',
	'ga'=> 'Irish',
	'gd'=> 'Scots Gaelic',
	'gl'=> 'Galician',
	'gn'=> 'Guarani',
	'gu'=> 'Gujarati',
	'gv'=> 'Manx',
	'ha'=> 'Hausa',
	'he'=> 'Hebrew',
	'hi'=> 'Hindi',
	'ho'=> 'Hiri Motu',
	'hr'=> 'Croatian',
	'hu'=> 'Hungarian',
	'hy'=> 'Armenian',
	'hz'=> 'Herero',
	'ia'=> 'Interlingua',
	'id'=> 'Indonesian',
	'ie'=> 'Interlingue',
	'ig'=> 'Igbo',
	'ii'=> 'Sichuan Yi',
	'ik'=> 'Inupiak',
	'io'=> 'Ido',
	'is'=> 'Icelandic',
	'it'=> 'Italian',
	'iu'=> 'Inuktitut',
	'ja'=> 'Japanese',
	'jv'=> 'Javanese',
	'ka'=> 'Georgian',
	'kg'=> 'Kongo',
	'ki'=> 'Kikuyu',
	'kj'=> 'Kuanyama',
	'kk'=> 'Kazakh',
	'kl'=> 'Greenlandic',
	'km'=> 'Khmer',
	'kn'=> 'Kannada',
	'ko'=> 'Korean',
	'kr'=> 'Kanuri',
	'ks'=> 'Kashmiri',
	'ku'=> 'Kurdish',
	'kv'=> 'Komi',
	'kw'=> 'Cornish',
	'ky'=> 'Kirghiz',
	'la'=> 'Latin',
	'lb'=> 'Luxembourgish',
	'lg'=> 'Ganda',
	'li'=> 'Limburgan',
	'ln'=> 'Lingala',
	'lo'=> 'Lao',
	'lt'=> 'Lithuanian',
	'lu'=> 'Luba-Katanga',
	'lv'=> 'Latvian',
	'mg'=> 'Malagasy',
	'mh'=> 'Marshallese',
	'mi'=> 'Maori',
	'mk'=> 'Macedonian',
	'ml'=> 'Malayalam',
	'mn'=> 'Mongolian',
	'mo'=> 'Moldavian',
	'mr'=> 'Marathi',
	'ms'=> 'Malay',
	'mt'=> 'Maltese',
	'my'=> 'Burmese',
	'na'=> 'Nauru',
	'nb'=> 'Norwegian Bokmal',
	'nd'=> 'North Ndebele',
	'ne'=> 'Nepali',
	'ng'=> 'Ndonga',
	'nl'=> 'Dutch',
	'nn'=> 'Norwegian Nynorsk',
	'no'=> 'Norwegian',
	'nr'=> 'South Ndebele',
	'nv'=> 'Navajo',
	'oc'=> 'Occitan',
	'oj'=> 'Ojibwa',
	'om'=> 'Oromo',
	'or'=> 'Oriya',
	'os'=> 'Ossetian',
	'pa'=> 'Punjabi',
	'pi'=> 'Pali',
	'pl'=> 'Polish',
	'ps'=> 'Pushto',
	'pt'=> 'Portuguese',
	'qu'=> 'Quechua',
	'rm'=> 'Rhaeto-Romance',
	'rn'=> 'Rundi',
	'ro'=> 'Romanian',
	'ru'=> 'Russian',
	'rw'=> 'Kinyarwanda',
	'sa'=> 'Sanskrit',
	'sc'=> 'Sardinian',
	'sd'=> 'Sindhi',
	'se'=> 'Northern Sami',
	'sg'=> 'Sango',
	'sh'=> 'Serbo-Croatian',
	'si'=> 'Sinhalese',
	'sk'=> 'Slovak',
	'sl'=> 'Slovenian',
	'sm'=> 'Samoan',
	'sn'=> 'Shona',
	'so'=> 'Somali',
	'sq'=> 'Albanian',
	'sr'=> 'Serbian',
	'ss'=> 'Swati',
	'st'=> 'Southern Sotho',
	'su'=> 'Sundanese',
	'sv'=> 'Swedish',
	'sw'=> 'Swahili',
	'ta'=> 'Tamil',
	'te'=> 'Telugu',
	'tg'=> 'Tajik',
	'th'=> 'Thai',
	'ti'=> 'Tigrinya',
	'tk'=> 'Turkmen',
	'tl'=> 'Tagalog',
	'tn'=> 'Tswana',
	'to'=> 'Tonga',
	'tr'=> 'Turkish',
	'ts'=> 'Tsonga',
	'tt'=> 'Tatar',
	'tw'=> 'Twi',
	'ty'=> 'Tahitian',
	'ug'=> 'Uighur',
	'uk'=> 'Ukrainian',
	'ur'=> 'Urdu',
	'uz'=> 'Uzbek',
	've'=> 'Venda',
	'vi'=> 'Vietnamese',
	'vo'=> 'Volapuk',
	'wa'=> 'Walloon',
	'wo'=> 'Wolof',
	'xh'=> 'Xhosa',
	'yi'=> 'Yiddish',
	'yo'=> 'Yoruba',
	'za'=> 'Zhuang',
	'zh'=> 'Chinese',
	'zu'=> 'Zulu',
};

sub name_from_639_code {
	my ($code) = @_;
	if ((!defined($code)) || ($code eq '') || (!defined($iso_639->{$code}))) {
		return msg('Unknown');
	} else {
		return dgettext('iso_639', $iso_639->{$code});
	}
}

my $program_mencoder = undef;
my $program_mplayer = undef;
my $program_hal_capability = undef;
my $program_hal_ls = undef;
my $program_lsdvd = undef;
my $have_hal = undef;


my @hal_dvd_devices;
my $mount_point;

sub get_env_language {
	my $code;
	my $lang = "$ENV{LANG}";
	$lang =~ /([^\.]+).*/i;
	$code->{'local'} = $1;
	$lang =~ /([^_]+).*/i;
	$code->{'global'} = $1;
	return $code;
}


my $config = {
	'default_profile' => 0,
	'language' => 'en',
	'dvd_device' => '',
	'mplay_err' => '',
	'mplay_out' => '',
	'crop_slices' => 5,
	'crop_frames' => 30,
	'output_directory' => $ENV{HOME},
	'eject_after' => 1,
	'eject_cmd' => 'eject',
	'shutdown_after' => 0,
	'copy_on_disc' => 0,
	'shutdown_cmd' => 'sudo /sbin/shutdown -h 0',
	'lemonrip_icon' => '/usr/share/icons/lemonrip.png',
};


#this could be removed in future version 
#begin of remove
if ( -f "$ENV{HOME}/.lemonrip") {
	msgg(INFO, "An old version of config file found, you need configure again\n");
	unlink "$ENV{HOME}/.lemonrip";
}
#end of remove

mkdir "$ENV{HOME}/.lemonrip" if (!( -d "$ENV{HOME}/.lemonrip"));

unlink "$ENV{HOME}/.lemonrip/log";

my $logfile = "$ENV{HOME}/.lemonrip/log";

open (LOGFILE, ">>", $logfile);


if (open (CONFIG, "$ENV{HOME}/.lemonrip/config")) {
	msgg (INFO, "Using user config $ENV{HOME}/.lemonrip/config\n");
	
	while (<CONFIG>) {
		if ($_ =~/(\w+)=(.*)/i) {
			$config->{$1} = $2;
		}
	}
	close CONFIG;
} else {
	msgg (INFO, "Using defaulf settings, config not found\n");
}

$program_hal_capability = `hal-find-by-capability --version`;
$program_hal_ls = `lshal --version`;
$program_mplayer = `mplayer -msglevel all=0`;
$program_mencoder = `mencoder -msglevel all=0`;
$program_lsdvd = `lsdvd -V 2>&1`;
$have_hal = (defined($program_hal_ls) & defined($program_hal_capability));

if (defined($program_hal_capability)) {
	msgg(INFO, "Found $program_hal_capability");
} else {
	msgg(INFO, "Could not locate program 'hal-find-by-capability', some of fetures will not work\n");
}

if (defined($program_hal_ls)) {
	msgg(INFO, "Found $program_hal_ls");
} else {
	msgg(INFO, "Could not locate program 'lshal', some of fetures will not work\n");
}

if (defined($program_lsdvd)) {
	msgg(INFO, "Found $program_lsdvd");
} else {
	msgg(INFO, "Could not locate program 'lsdvd', some of fetures will not work\n");
}


if (!defined($program_mplayer)) {
	msgg(ERROR, "Could not locate program 'mplayer'. Install mplayer first\n");
} else {
	msgg(INFO, "Found MPLAYER\n$program_mplayer");
}

if (!defined($program_mencoder)) {
	msgg(ERROR, "Could not locate program 'mencoder'. Install mencoder first\n");
} else {
	msgg(INFO, "Found MENCODER\n$program_mencoder");
}


sub unspace {
	my ($str) = @_;
	$str =~s/ /<space>/g;
	return $str;
}

sub space {
	my ($str) = @_;
	$str =~s/<space>/ /g;
	return $str;
}

sub hal_get_udi_info {
	my ($udi) = @_;
	my $info = {};
	$info->{'dvd'} = 0;
	$info->{'device'} = '';
	$info->{'name'} = $udi;
	foreach my $line (`lshal --long --show $udi`) {
		if ($line =~/info\.product\W+[\'\"](.*)[\'\"]/i) {
			$info->{'name'} = $1;
		} elsif ($line =~/storage\.cdrom\.dvd\W+true/) {
			$info->{'dvd'} = 1;
		} elsif ($line =~/block\.device\W+[\'\"](.*)[\'\"]/i) {
			$info->{'device'} = $1;
		}
	}
	$info->{'dvd'} = 0 if ($info->{'device'} eq '');
	
	return $info;
}

sub hal_volume_name {
	foreach (`hal-find-by-capability --capability volume`) {
		my $info = hal_get_udi_info($_);
		if (($info->{'dvd'} == 0) && ($info->{'device'} eq $config->{'dvd_device'})) {
			return $info->{'name'};
		}
	}
	return undef;
}

sub lsdvd_disc_info {
	my $info = {};
	my %lsdvd;
	my $cmd = "lsdvd -Op";
	my $pid = open OUT, "-|", $cmd;
	my $ok = 1;
	my $aid = alarm_start(
			sub {
				msgg(INFO, "lsdvd disc info timeout\n");
				mplayer_kill($pid);
				undef $ok;
			},
			$mplayer_timeout);

	
	my $eval = '';
	while(<OUT>) {
		$eval .= $_;
	}	#while
	alarm_stop($aid);
	close OUT;
	%lsdvd = eval($eval);
	$info->{'name'} = $lsdvd{'title'};
	$info->{'title_count'} = $#{$lsdvd{'track'}} + 1;		
	$info->{'main_title'} = $lsdvd{'longest_track'};
	$info->{'dvd_device'} = $lsdvd{'device'};
	undef $info if (!$ok);
	return $info;
}

sub disc_name {
	my $name;
	if ($have_hal == 1) {
		$name = hal_volume_name;		
	} elsif (defined($program_lsdvd)) {
		$name = lsdvd_disc_info;
		if (defined($name)) {
			$name = $name->{'name'};
		} else {
			$name = '';
		}
	} else {
		$name = '';
	}
	$name =~s/_/ /g;
	$name =~s/(\w+)/\L\u\1/g;
	return $name;
}

if ($have_hal == 1) {
	my $have_device = 0;

	foreach (`hal-find-by-capability --capability storage.cdrom`) {
		my $info = hal_get_udi_info($_);
		if ($info->{'dvd'} == 1) {
			$have_device = 1 if ($info->{'device'} eq $config->{'dvd_device'});
			delete $info->{'dvd'};
			push @hal_dvd_devices, $info;
		}
	}

	if ((!$config->{'dvd_device'}) || $config->{'dvd_device'} eq '') {
		if (@hal_dvd_devices[0]) {
			$config->{'dvd_device'} = @hal_dvd_devices[0]->{'device'};
		} else {
			$config->{'dvd_device'} = '/dev/hdc';
			my $info = {};
			$info->{'name'} = $config->{'dvd_device'};
			$info->{'device'} = $config->{'dvd_device'};
			push @hal_dvd_devices, $info;
		}
	} else {
		if ($have_device == 0) {
			my $info = {};
			$info->{'name'} = $config->{'dvd_device'};
			$info->{'device'} = $config->{'dvd_device'};
			push @hal_dvd_devices, $info;
		}
	}	
} else {
	$config->{'dvd_device'} = '/dev/hdc'
		if ((!$config->{'dvd_device'}) || $config->{'dvd_device'} eq '');
}

sub get_uri_type {
	my ($uri) = @_;
	my $type = FILE;
	$type = DVD if ($uri =~ /dvd/i);
	return $type;
}

sub msgg {
	my ($priority, $msg) = @_;
	print LOGFILE "$priority: $msg" if (($verbose == 1) || ($priority ne MPLAYER)); 
}


#just hardcoded default profiles
#it is posible to override them troght user profiles
my @default_profiles = (
  	{
		avprofileid => 'XVID 700MB',
		name => {
			en => 'XVID - 2 pass, 700MB file size',
			cs => 'XVID - 2 pass, 700MB velikost'
			},
		format => 'avi',
		size => 700,
		abitrate => 128,
		width => 640,
		height => -1,
		cmd => {
			passcount => 2,
			pass1 => 'mencoder $url -ovc xvid -oac mp3lame -lameopts cbr:br=$abitrate -vf pullup,softskip,crop=$autocrop,scale=$autoscale -af resample=44100:0:0 -xvidencopts chroma_opt:vhq=4:bvhq=1:quant_type=mpeg:pass=1:turbo -o $dir/$name.avi -passlogfile $dir/$name.log',
 			pass2 => 'mencoder $url -ovc xvid -oac mp3lame -lameopts cbr:br=$abitrate -vf pullup,softskip,crop=$autocrop,scale=$autoscale -af resample=44100:0:0 -xvidencopts chroma_opt:vhq=4:bvhq=1:quant_type=mpeg:bitrate=$vbitrate:pass=2 -o $dir/$name.avi -passlogfile $dir/$name.log'
			},
		proggresstimekoeficient => {
			pass2 => 2
			}
	},{
		avprofileid => 'XVID 1100MB',
		name => {
			en => 'XVID - 2 pass, 1100MB file size',
			cs => 'XVID - 2 pass, 1100MB velikost'
			},
		format => 'avi',
		size => 1100,
		abitrate => 128,
		width => 640,
		height => -1,
		cmd => {
			passcount => 2,
			pass1 => 'mencoder $url -ovc xvid -oac mp3lame -lameopts cbr:br=$abitrate  -vf pullup,softskip,crop=$autocrop,scale=$autoscale -af resample=44100:0:0 -xvidencopts chroma_opt:vhq=4:bvhq=1:quant_type=mpeg:pass=1:turbo -o $dir/$name.avi -passlogfile $dir/$name.log',
 			pass2 => 'mencoder $url -ovc xvid -oac mp3lame -lameopts cbr:br=$abitrate  -vf pullup,softskip,crop=$autocrop,scale=$autoscale -af resample=44100:0:0 -xvidencopts chroma_opt:vhq=4:bvhq=1:quant_type=mpeg:bitrate=$vbitrate:pass=2 -o $dir/$name.avi -passlogfile $dir/$name.log'
			},
		proggresstimekoeficient => {
			pass2 => 2
			}
	},{
		avprofileid => 'X264 Medium quality',
		name => {
			en => 'H.264 Medium quality',
			cs => 'H.264 Střední kvalita'
			},
		format => 'avi',
		size => 500,
		abitrate => 128,
		width => 640,
		height => -1,
		cmd => {
			passcount => 1,																													
			pass1 => 'mencoder $url -ovc x264 -oac mp3lame -lameopts cbr:br=$abitrate -vf pullup,softskip,crop=$autocrop,scale=$autoscale -af resample=44100:0:0 -x264encopts crf=22:subq=6:partitions=all:8x8dct:me=umh:frameref=5:bframes=3:b_pyramid:weight_b -o $dir/$name.avi',
			},
	},{
		avprofileid => 'MPEG4 2pass 700MB',
		name => {
			en => 'MPEG4(DivX5) - 2 pass, 700MB file size',
			cs => 'MPEG4(DivX5) - 2 pass, 700MB velikost'
			},
		format => 'avi',
		size => 700,
		abitrate => 128,
		width => 640,
		height => -1,
		cmd => {
			passcount => 2,																						
			pass1 => 'mencoder $url -ffourcc DX50 -ovc lavc -oac mp3lame -lameopts cbr:br=$abitrate -lavcopts vcodec=mpeg4:mbd=2:mv0:trell:v4mv:cbp:last_pred=3:predia=2:dia=2:vmax_b_frames=2:vb_strategy=1:precmp=2:cmp=2:subcmp=2:preme=2:qns=2:vpass=1:vbitrate=$vbitrate:turbo -vf pullup,softskip,crop=$autocrop,scale=$autoscale -af resample=44100:0:0 -o $dir/$name.avi -passlogfile $dir/$name.log',
 			pass2 => 'mencoder $url -ffourcc DX50 -ovc lavc -oac mp3lame -lameopts cbr:br=$abitrate -lavcopts vcodec=mpeg4:mbd=2:mv0:trell:v4mv:cbp:last_pred=3:predia=2:dia=2:vmax_b_frames=2:vb_strategy=1:precmp=2:cmp=2:subcmp=2:preme=2:qns=2:vpass=2:vbitrate=$vbitrate -vf pullup,softskip,crop=$autocrop,scale=$autoscale -af resample=44100:0:0 -o $dir/$name.avi -passlogfile $dir/$name.log'
			},
		proggresstimekoeficient => {
			pass2 => 2
			}
	},{
		avprofileid => 'MPEG4 Quick',
		name => {
			en => 'MPEG4(DivX5) - Low Quality, Quick',
			cs => 'MPEG4(DivX5) - Nízká kvalita, Velmi rychlé'
			},
		format => 'avi',
		size => 700,
		abitrate => 128,
		width => 640,
		height => -1,
		cmd => {
			passcount => 1,																				
			pass1 => 'mencoder $url -ffourcc DX50 -ovc lavc -oac mp3lame -lameopts cbr:br=$abitrate  -lavcopts vcodec=mpeg4:mbd=2:turbo -vf pullup,softskip,crop=$autocrop,scale=$autoscale -af resample=44100:0:0 -o $dir/$name.avi',
			}
	}
);

my @profiles = ();

sub add_profile {
	my ($profile, $file) = @_;
	my $language = get_env_language;
	if (defined($profile->{'avprofileid'})) {
		my $exist = undef;
		foreach my $p (@profiles) {
			$exist = 1 if ($profile->{'avprofileid'} eq $p->{'avprofileid'});
		}
		if (!$exist) {	 		
			my $name = $profile->{'name'}->{$language->{'local'}};
			$name = $profile->{'name'}->{$language->{'global'}} if (!$name);
			$name = $profile->{'avprofileid'} if (!$name);
			$profile->{'name'} = $name;
				push @profiles, $profile;
				msgg(INFO, "Using profile $name\n");
			}

	} else {
		msgg(INFO, "Unknown profile: $file\n");
	} 
}

sub read_profiles_user_profiles {
	my $xml = new XML::Simple;
	
	my @dirs = ("$ENV{HOME}/\.lemonrip/profiles",
				"/usr/local/share/lemonrip/profiles",
				"/usr/share/lemonrip/profiles"
				);
	foreach my $dir (@dirs) {
		if (-d $dir) {
	  		while (defined(my $file = <$dir/*>)) {
	  			my $profile = $xml->XMLin($file);
				add_profile($profile, $file);
	  		}
		}
	}

}

read_profiles_user_profiles;

foreach (@default_profiles) {
	add_profile($_, undef);
}

msgg(INFO, "$#profiles profiles loaded\n");

#if in config is wrong default profile change it to first one
$config->{'default_profile'} = 0 if ($#profiles < $config->{'default_profile'});

sub alarm_start {
	my ($on_activate, $time) = @_;
	$SIG{ALRM} = $on_activate;
	alarm($time);
	return 1;
}

sub alarm_stop {
	my ($aid) = @_;
	$SIG{ALRM} = sub {};
	alarm(0);
}


sub mplayer_kill {
	my ($pid) = @_;
	return if (!$pid);
	msgg (INFO, "MPLAYER KILL: $pid\n");
	kill 'INT', $pid;
	$pid++;
	kill 'INT', $pid if `ps $pid | grep mencoder` || `ps $pid | grep mplayer`;
	#we will try to handle better way
}


sub mplayer_get_cmd {
		my ($cmd, $piped) = @_;
		my $exist_null = (-w "/dev/null");
		$cmd =~s/<quote>/\"/g;
		$cmd = space("mplayer $cmd -loop 1");
		if ($verbose == 1) {
			$cmd .= " 2>>$logfile";
		} else {
			$cmd .= " 2>/dev/null" if ((defined ($exist_null)) && ($exist_null == 1)); 
		}
		if ((defined ($piped)) && ($piped == 0)) {
			$cmd .= " 1>/dev/null" if ((defined ($exist_null)) && ($exist_null == 1));
			$cmd .= " &";
		}
		return $cmd;
}

use constant MAXINT => 65536;
use constant MAXINT => 65536;

use constant CROP_SLICE_OK => 'crop_slice_ok';
use constant CROP_SLICE_BAD_SEEK => 'crop_slice_bad_seek';
use constant CROP_SLICE_FAILED => 'crop_slice_failed';


sub msg {
	my ($name) = @_;
	my $r;
	$r = gettext($name);
	return $r;
}



#############################INTERFACE##########################################
sub create_stock_buttons {
  my $factory = Gtk2::IconFactory->new;
  $factory->add_default;
  my $style = new Gtk2::Style;
  my @items = (
    { stock_id => "lemonrip",    label => msg("Lemonrip"),  icon => 'gtk-cdrom' },
    { stock_id => "er-rip",    label => msg("_Convert"),  icon => 'gtk-media-record' },
    { stock_id => "er-reload",     label => msg("_Reload"),    icon => 'gtk-refresh' },
    { stock_id => "er-play",  label => msg("_Play"), icon => 'gtk-media-play' },
    { stock_id => "er-eject",     label => msg("_Eject"), icon => 'gtk-remove'},
    { stock_id => "er-settings",    label => msg("_Settings"),  icon => 'gtk-properties' },
    { stock_id => "er-preview",  label => msg("Pre_view"), icon => 'gtk-zoom-100' },
    { stock_id => "er-quit",  label => msg("_Quit"), icon => 'gtk-quit' },
    { stock_id => "er-close",  label => msg("_Close"), icon => 'gtk-close' },
    { stock_id => "er-apply",  label => msg("_Apply"), icon => 'gtk-apply' },
    { stock_id => "er-yes",  label => msg("_Yes"), icon => 'gtk-yes' },
    { stock_id => "er-no",  label => msg("_No"), icon => 'gtk-no' },
    { stock_id => "er-pref",  label => msg("_Preference"), icon => 'gtk-preferences' },
    { stock_id => "er-about",  label => msg("_About"), icon => 'gtk-about' },
    { stock_id => "er-cancel",    label => msg("Cancel"),   icon => 'gtk-stop' }
  );
  Gtk2::Stock->add(@items);
  foreach (@items) {
    $factory->add( $_->{'stock_id'}, $style->lookup_icon_set( $_->{'icon'} ) );
  }
}

&create_stock_buttons;

sub new_titles_model {
	my $model = Gtk2::ListStore->new ('Glib::Scalar', 'Glib::Boolean', 'Glib::String',
		,'Glib::String', 'Glib::String', 'Glib::String', 'Glib::String', 'Glib::String');
	return ($model);
}

sub new_title_view {
	my $model = &new_titles_model;

	my $view = Gtk2::TreeView->new_with_model ($model);

	my $renderer = Gtk2::CellRendererToggle->new;
	my $column = Gtk2::TreeViewColumn->new_with_attributes ("", $renderer, active => 1);
	$view->append_column ($column);
	$renderer->signal_connect(toggled => \&selected_toggled, $model);

	$renderer = Gtk2::CellRendererText->new;
	$renderer->set('editable', 1);
	$renderer->signal_connect(edited => \&title_edited, $model);
	
	$column = Gtk2::TreeViewColumn->new_with_attributes (msg('Title'), $renderer, text => 2);
	
	$view->append_column ($column);

	$renderer = Gtk2::CellRendererText->new;
	$renderer->set('xalign', 1);
	$column = Gtk2::TreeViewColumn->new_with_attributes (msg("Duration"), $renderer, text => 3);
	$view->append_column ($column);

	$renderer = Gtk2::CellRendererText->new;
	$column = Gtk2::TreeViewColumn->new_with_attributes (msg("Aspect"), $renderer, text => 4);
	$renderer->set('xalign', .5);
	$view->append_column ($column);

	$renderer = Gtk2::CellRendererText->new;
	$column = Gtk2::TreeViewColumn->new_with_attributes (msg("Language"), $renderer, text => 5);
	$renderer->set('xalign', .5);
	$view->append_column ($column);

	$renderer = Gtk2::CellRendererText->new;
	$column = Gtk2::TreeViewColumn->new_with_attributes (msg("Subtitles"), $renderer, text => 6);
	$renderer->set('xalign', .5);
	$view->append_column ($column);

	$renderer = Gtk2::CellRendererText->new;
	$column = Gtk2::TreeViewColumn->new_with_attributes (msg("Profile"), $renderer, text => 7);
	$view->append_column ($column);

	return ($view, $model);
}

my $app_window = Gtk2::Window->new;

#preference window#########################################################
my $pref_win = Gtk2::Window->new;
$pref_win->set_title(msg('Preference'));
$pref_win->set_icon_name('gtk-preferences');
$pref_win->set_type_hint('dialog');
$pref_win->set_transient_for($app_window);
$pref_win->set_destroy_with_parent(1);
$pref_win->set_modal(1);
my $vbox = Gtk2::VBox->new;
$vbox->set_border_width(6);
$pref_win->add($vbox);
$pref_win->signal_connect (delete_event => \&preference_save);

my $table = Gtk2::Table->new(2, 9);
$vbox->pack_start($table, 0, 0, 0);
$table->set_row_spacings(3);
my $lbl = Gtk2::Label->new;
$lbl->set_alignment( 0, 0.5 );
$lbl->set_markup('<b>'.msg('Input Output').'</b>');
$table->attach($lbl, 0,2,0,1,['fill'],[],0,6);

my $lbl = Gtk2::Label->new(msg('DVD device:'));
$lbl->set_alignment( 0, 0.5 );
$table->attach($lbl, 0,1,1,2,['fill'],[],10,0);

my $edit_dvd_device;
my $cmb_dvd_device;

if ($have_hal == 1) {
	$cmb_dvd_device = Gtk2::ComboBox->new_text;
	$table->attach($cmb_dvd_device, 1,2,1,2,['fill','expand'],[],0,0);
	foreach (@hal_dvd_devices) {
		$cmb_dvd_device->append_text($_->{'name'});
	}
} else {
	$edit_dvd_device = Gtk2::Entry->new;
	$table->attach($edit_dvd_device, 1,2,1,2,['fill','expand'],[],0,0);
}

my $lbl = Gtk2::Label->new(msg('Output directory:'));
$lbl->set_alignment( 0, 0.5 );
$table->attach($lbl, 0,1,2,3,['fill'],[],10,0);

my $dir_button = Gtk2::FileChooserButton->new(msg('Output directory:'), 'select_folder');
$table->attach($dir_button, 1,2,2,3,['fill','expand'],[],0,0);


my $lbl = Gtk2::Label->new;
$lbl->set_markup('<b>'.msg('Automatic cropping settings').'</b>');
$lbl->set_alignment( 0, 0.5 );
$table->attach($lbl, 0,2,3,4,['fill'],[],0,6);

my $lbl = Gtk2::Label->new(msg('Count of slices:'));
$lbl->set_alignment( 0, 0.5 );
$table->attach($lbl, 0,1,4,5,['fill'],[],10,0);
my $lbl = Gtk2::Label->new(msg('Count of frames:'));
$lbl->set_alignment( 0, 0.5 );
$table->attach($lbl, 0,1,5,6,['fill'],[],10,0);

my $slice_scale = Gtk2::HScale->new_with_range(1, 20, 1);
$slice_scale->set_value_pos('right');
$table->attach($slice_scale, 1,2,4,5,['fill','expand'],[],0,0);

my $frames_scale = Gtk2::HScale->new_with_range(5, 200, 1);
$frames_scale->set_value_pos('right');
$table->attach($frames_scale, 1,2,5,6,['fill','expand'],[],0,0);

my $lbl = Gtk2::Label->new;
$lbl->set_markup('<b>'.msg('Converting defaults').'</b>');
$lbl->set_alignment( 0, 0.5 );
$table->attach($lbl, 0,2,6,7,['fill'],[],0,6);

my $lbl = Gtk2::Label->new(msg('Profile:'));
$lbl->set_alignment( 0, 0.5 );
$table->attach($lbl, 0,1,7,8,['fill'],[],10,0);

my $cmb_defaultprofile = Gtk2::ComboBox->new_text;
for(my $x = 0; $x <= $#profiles;$x++) {
	$cmb_defaultprofile->append_text($profiles[$x]->{'name'});
}
$table->attach($cmb_defaultprofile, 1,2,7,8,['fill', 'expand'],[],0,0);

my $check_eject = Gtk2::CheckButton->new(msg('Eject DVD after process'));
$table->attach($check_eject, 0,2,8,9,['fill'],[],10,0);
my $check_shutdown = Gtk2::CheckButton->new(msg('Switch off computer after process'));
$table->attach($check_shutdown, 0,2,9,10,['fill'],[],10,0);


my $fixed = Gtk2::Fixed->new;
$vbox->pack_start($fixed, 1, 1, 0);

my $sep = Gtk2::HSeparator->new;
$vbox->pack_start($sep, 0, 0, 3);

my $hbox = Gtk2::HBox->new;
$vbox->pack_start($hbox, 0, 0, 0);
$fixed = Gtk2::Fixed->new;
$hbox->pack_start($fixed, 1, 1, 0);

my $btn = Gtk2::Button->new_from_stock('er-close');
$btn->signal_connect (clicked => \&preference_save);
$hbox->pack_start($btn, 0, 0, 0);

sub preference {
	my $c = 0;
	if ($have_hal == 1) {
		foreach (@hal_dvd_devices) {
			last if ($config->{'dvd_device'} eq $_->{'device'});
			$c++;
		}
		$cmb_dvd_device->set_active($c);
	} else {
		$edit_dvd_device->set_text($config->{'dvd_device'});
	}
	$dir_button->set_current_folder($config->{'output_directory'});
	$slice_scale->set_value($config->{'crop_slices'});
	$frames_scale->set_value($config->{'crop_frames'});
	$cmb_defaultprofile->set_active($config->{'default_profile'});
	$check_eject->set_active($config->{'eject_after'});
	$check_shutdown->set_active($config->{'shutdown_after'});
	$pref_win->show_all;
}

sub preference_save {
	if ($have_hal == 1) {
		$config->{'dvd_device'} = (@hal_dvd_devices[$cmb_dvd_device->get_active])->{'device'};
	} else {
		$config->{'dvd_device'} = $edit_dvd_device->get_text;
	}
	$config->{'output_directory'} = $dir_button->get_current_folder;
	$config->{'crop_slices'} = $slice_scale->get_value;
	$config->{'crop_frames'} = $frames_scale->get_value;
	$config->{'default_profile'}= $cmb_defaultprofile->get_active;
	$config->{'eject_after'}  = $check_eject->get_active;
	$config->{'shutdown_after'} = $check_shutdown->get_active; 
	$pref_win->hide;
	my @save = ('default_profile','language','dvd_device','mplay_err','mplay_out',
	'crop_slices','crop_frames','output_directory','eject_after',
	'eject_cmd','shutdown_after','copy_on_disc','shutdown_cmd');

	if ( open( CONFIGFILE, '>', "$ENV{HOME}/.lemonrip/config" ) ) {
		foreach my $key (@save) {
	    	print CONFIGFILE "$key=$config->{$key}\n";
		}
		close CONFIGFILE;
	} else {
	}


	return 1;
}

############################################################################
$app_window->set_title(msg("Lemonrip"));
if (lstat $config->{'lemonrip_icon'}) { 
	$app_window->set_icon_from_file($config->{'lemonrip_icon'});
} else {
	$app_window->set_icon_name('gtk-cdrom');
}
$app_window->set_size_request(600, 400);	
my $vbox = Gtk2::VBox->new( 0, 0);
$app_window->add($vbox);
$app_window->signal_connect (delete_event => \&app_quit);

my $accel = Gtk2::AccelGroup->new;
$app_window->add_accel_group($accel);
$accel->connect(42,'control-mask',['visible'],'r');

my $menu = Gtk2::MenuBar->new;
$vbox->pack_start($menu, 0, 0, 0);

my $dvd_menu = Gtk2::Menu->new;
my $dvd_menu_refresh = Gtk2::ImageMenuItem->new_from_stock('er-reload', $accel);
$dvd_menu_refresh->signal_connect(activate => \&disc_refresh);
#$dvd_menu_refresh->set_accel_path('<dvd_refresh>');
my $dvd_menu_record = Gtk2::ImageMenuItem->new_from_stock('er-rip', undef);
$dvd_menu_record->signal_connect(activate => \&rip);
my $dvd_menu_eject = Gtk2::ImageMenuItem->new_from_stock('er-eject', undef);
$dvd_menu_eject->signal_connect(activate => \&eject);
my $dvd_menu_quit = Gtk2::ImageMenuItem->new_from_stock('er-quit', undef);
$dvd_menu_quit->signal_connect(activate => \&app_quit);
my $sepitem  = Gtk2::SeparatorMenuItem->new;
$dvd_menu->append($dvd_menu_refresh);
$dvd_menu->append($dvd_menu_eject);
$dvd_menu->append($dvd_menu_record);
$dvd_menu->append($sepitem);
$dvd_menu->append($dvd_menu_quit);
my $dvd_menu_item = Gtk2::MenuItem->new(msg('_Disc DVD'));
$dvd_menu_item->set_submenu($dvd_menu);
my $edit_menu = Gtk2::Menu->new;
my $edit_menu_pref = Gtk2::ImageMenuItem->new_from_stock('er-pref', undef);
$edit_menu_pref->signal_connect(activate => \&preference);
$edit_menu->append($edit_menu_pref);
my $edit_menu_item = Gtk2::MenuItem->new(msg('_Edit'));
$edit_menu_item->set_submenu($edit_menu);

my $help_menu = Gtk2::Menu->new;
my $help_menu_item = Gtk2::MenuItem->new(msg('_Help'));
$help_menu_item->set_submenu($help_menu);


my $title_menu = Gtk2::Menu->new;
my $title_menu_play = Gtk2::ImageMenuItem->new_from_stock('er-play', undef);
$title_menu_play->signal_connect(activate => \&title_play);
my $title_menu_preview = Gtk2::ImageMenuItem->new_from_stock('er-preview', undef);
$title_menu_preview->signal_connect(activate => \&title_preview);
my $title_menu_settings = Gtk2::ImageMenuItem->new_from_stock('er-settings', undef);
$title_menu_settings->signal_connect(activate => \&title_settings);
my $help_menu_about = Gtk2::ImageMenuItem->new_from_stock('er-about', undef);
$help_menu_about->signal_connect(activate => \&about);
$help_menu->append($help_menu_about);


$title_menu->append($title_menu_play);
$title_menu->append($title_menu_settings);
$title_menu->append($title_menu_preview);
my $title_menu_item = Gtk2::MenuItem->new(msg('_Title'));
$title_menu_item->set_submenu($title_menu);
$menu->append($dvd_menu_item);
$menu->append($edit_menu_item);
$menu->append($title_menu_item);
$menu->append($help_menu_item);

my $icon_bar = Gtk2::Toolbar->new;
$vbox->pack_start($icon_bar, 0, 0, 0);

my $icon_refresh = Gtk2::ToolButton->new_from_stock('er-reload');
$icon_bar->insert($icon_refresh, -1);
$icon_refresh->signal_connect(clicked => \&disc_refresh);
my $icon_rip = Gtk2::ToolButton->new_from_stock('er-rip');
$icon_bar->insert($icon_rip, -1);
$icon_rip->signal_connect(clicked => \&rip);
my $sep = Gtk2::SeparatorToolItem->new;
$icon_bar->insert($sep, -1);
my $icon_pref = Gtk2::ToolButton->new_from_stock('er-pref');
$icon_bar->insert($icon_pref, -1);
$icon_pref->signal_connect(clicked => \&preference);
my $sep = Gtk2::SeparatorToolItem->new;
$icon_bar->insert($sep, -1);
my $icon_play = Gtk2::ToolButton->new_from_stock('er-play');
$icon_bar->insert($icon_play, -1);
$icon_play->signal_connect(clicked => \&title_play);

my $icon_settings = Gtk2::ToolButton->new_from_stock('er-settings');
$icon_bar->insert($icon_settings, -1);
$icon_settings->signal_connect(clicked => \&title_settings);

my $icon_preview = Gtk2::ToolButton->new_from_stock('er-preview');
$icon_bar->insert($icon_preview, -1);
$icon_preview->signal_connect(clicked => \&title_preview);

my $frame = Gtk2::Frame->new('');
$frame->set_shadow_type('none');
my $title_lbl = Gtk2::Label->new;
$title_lbl->set_markup('<b>'.msg('DVD titles').'</b>');
$frame->set_label_widget($title_lbl);
$vbox->pack_start($frame, 1, 1, 2);
my $scroll = Gtk2::ScrolledWindow->new;
$scroll->set_policy('automatic', 'automatic');
$frame->add($scroll);
my $title_view;
my $title_model;
($title_view, $title_model) = &new_title_view;
$title_view->get_selection->set_mode('browse');
$scroll->add( $title_view );

my $status_bar = Gtk2::Statusbar->new;
$vbox->pack_start($status_bar, 0, 0, 0);

my $progress_bar = new Gtk2::ProgressBar;
$status_bar->pack_start($progress_bar, 1, 1, 0);

my $btn_cancel = Gtk2::Button->new_from_stock('er-cancel');
$btn_cancel->signal_connect(clicked => \&cancel);
$status_bar->pack_start($btn_cancel, 0, 0, 0);


sub about {
	my $win = Gtk2::AboutDialog->new;
	$win->set_title(msg('About'));
	$win->set_name(msg('Lemonrip'));
	$win->set_version($version);
	if (lstat $config->{'lemonrip_icon'}) { 
		$win->set_icon_from_file($config->{'lemonrip_icon'});
	} else {
		$win->set_icon_name('gtk-cdrom');
	}
	$win->set_comments(msg('Very easy to use DVD converter to AVI files'));
	$win->set_website('http://jaromes.projects.googlepages.com/lemonrip.html');
	$win->set_website_label('http://jaromes.projects.googlepages.com/lemonrip.html');
	$win->set_license('GPL');
	$win->set_wrap_license(1);
	$win->set_authors('Jaromir Skubala <jaromes.projects@gmail.com>');
	$win->run;
	1;
}

##################### window properties ##############################	
my $win_settings = Gtk2::Window->new;
$win_settings->set_title(msg("Title settings"));
$win_settings->set_icon_name('gtk-properties');
$win_settings->set_type_hint('dialog');
$win_settings->set_transient_for($app_window);
$win_settings->set_destroy_with_parent(1);
$win_settings->set_modal(1);
$win_settings->signal_connect (delete_event => sub { $win_settings->hide; 1 });

my $vbox = Gtk2::VBox->new;
$vbox->set_border_width(6);
$win_settings->add($vbox);


my $table = Gtk2::Table->new(2, 6);
$vbox->pack_start($table, 0, 0, 0);
$table->set_row_spacings(3);

my $lbl = Gtk2::Label->new;
$lbl->set_alignment( 0, 0.5 );
$lbl->set_markup('<b>'.msg('Language selection').'</b>');
$table->attach($lbl, 0,2,0,1,['fill'],[],0,6);

my $lbl = Gtk2::Label->new(msg('Audio:'));
$lbl->set_alignment( 0, 0.5 );
$table->attach($lbl, 0,1,1,2,['fill'],[],10,0);
my $cmb_language = Gtk2::ComboBox->new_text;
$table->attach($cmb_language, 1,2,1,2,['fill', 'expand'],[],0,0);

my $lbl = Gtk2::Label->new(msg('Subtitles:'));
$lbl->set_alignment( 0, 0.5 );
$table->attach($lbl, 0,1,2,3,['fill'],[],10,0);
my $cmb_subtitles = Gtk2::ComboBox->new_text;
$table->attach($cmb_subtitles, 1,2,2,3,['fill', 'expand'],[],0,0);

my $lbl = Gtk2::Label->new;
$lbl->set_alignment( 0, 0.5 );
$lbl->set_markup('<b>'.msg('Quality settings').'</b>');
$table->attach($lbl, 0,2,3,4,['fill'],[],0,6);

my $lbl = Gtk2::Label->new(msg('Profile:'));
$lbl->set_alignment( 0, 0.5 );
$table->attach($lbl, 0,1,4,5,['fill'],[],10,0);
my $cmb_profiles = Gtk2::ComboBox->new_text;
$table->attach($cmb_profiles, 1,2,4,5,['fill', 'expand'],[],0,0);
for(my $x = 0; $x <= $#profiles;$x++) {
	$cmb_profiles->append_text($profiles[$x]->{'name'});
}

my $fixed = Gtk2::Fixed->new;
$vbox->pack_start($fixed, 1, 1, 0);

my $sep = Gtk2::HSeparator->new;
$vbox->pack_start($sep, 0, 0, 3);

my $hbox = Gtk2::HBox->new;
$vbox->pack_start($hbox, 0, 0, 0);

my $btn_cancel_settings = Gtk2::Button->new_from_stock('er-close');
$btn_cancel_settings->signal_connect (clicked => sub { $win_settings->hide; 1 });
$hbox->pack_start($btn_cancel_settings, 0, 0, 0);

my $fixed = Gtk2::Fixed->new;
$hbox->pack_start($fixed, 1, 1, 0);

my $btn_apply = Gtk2::Button->new_from_stock('er-apply');
$btn_apply->signal_connect (clicked => \&title_settings_apply);
$hbox->pack_start($btn_apply, 0, 0, 0);

##############################Functions####################################
my %lsdvd;
my $rows;
my $titles;
my $processing = 0;
my $dvd_inserted = -1;


sub mplayer_get_slice_crop {
	my ($info, $seek_cmd, $frames) = @_;
	my $cmd = mplayer_get_cmd("$info->{'uri'} $seek_cmd -speed 100 -vf cropdetect=24:16 -frames $frames -vo null -ao null", 1);
	msgg(INFO, "MPLAYER CROP COMMAND: $cmd\n");
	my $pid = open OUT, "-|", $cmd;
	my $crop_ret = CROP_SLICE_FAILED;
	my $aid = alarm_start(
			sub {
				msgg(INFO, "GET SLICE CROP: timeout\n");
				mplayer_kill($pid);
				$crop_ret = CROP_SLICE_BAD_SEEK;
			},
			$mplayer_timeout);

	
	my $line;
	while(<OUT>) {
		$line = $_;
		if ($line =~ /crop=([\d-]+):([\d-]+):([\d-]+):([\d-]+)/i ) {
			$crop_ret = CROP_SLICE_OK;
			if (($1 > 0) && ($2 > 0)) {
				if ($info->{'video'}->{'crop'}->{'xres'} < $1) {
					$info->{'video'}->{'crop'}->{'xres'} = $1;
					$info->{'video'}->{'crop'}->{'left'} = $3;
				}
				if ($info->{'video'}->{'crop'}->{'yres'} < $2) {
					$info->{'video'}->{'crop'}->{'yres'} = $2;
					$info->{'video'}->{'crop'}->{'top'} = $4;
				}
			}
		}

	}	#while
	alarm_stop($aid);
	close OUT;
	return $crop_ret;
}

sub crop {
	my ($info) = @_;
	if ($info->{'status'} ne MEDIA_OK) {
		msgg(HINT, "crop: exit... media error\n");
		return;
	}
	if (!defined($info->{'video'})) {
		msgg(HINT, "crop: exit... no video\n");
		return;
	}
	if ($info->{'video'}->{'crop'}->{'status'} eq CROP_READY) {
		msgg(HINT, "crop: exit... crop ready\n");
		return;
	}
	
	if ($info->{'video'}->{'crop'}->{'status'} eq CROP_AUTO) {
		&crop_auto($info);
	}
}

sub status_crop {
	my ($slice) = @_;
	my $msg = '$msg="'.msg('Automatic cropping, slice $slice').'"';
	eval($msg);
	status($msg);
	while ( Gtk2->events_pending() ) { Gtk2->main_iteration() };
}

sub crop_auto {
	my ($info) = @_;
	$info->{'video'}->{'crop'}->{'left'} = 0;
	$info->{'video'}->{'crop'}->{'top'} = 0;
	$info->{'video'}->{'crop'}->{'xres'} = 0;
	$info->{'video'}->{'crop'}->{'yres'} = 0;
	my $pos;
	my $ret;
	my $step;
	my $slice = 1;

	if (($info->{'seek_status'} eq SEEK_UNKNOWN) || ($info->{'seek_status'} eq SEEK_FULL)) {
		$step = $info->{'length'} / $config->{'crop_slices'};
		$pos = $step;
		$info->{'seek_status'} = SEEK_NONE;
		do {
			status_crop($slice++);
			$ret = mplayer_get_slice_crop($info, '-ss '.&hhmmss($pos), $config->{'crop_frames'});
			$info->{'seek_status'} = SEEK_BYTE if ($ret eq CROP_SLICE_BAD_SEEK);
			$info->{'seek_status'} = SEEK_FULL if ($ret eq CROP_SLICE_OK);
			$pos+= $step;
		} while ($ret eq CROP_SLICE_OK);
	}

	if ($info->{'seek_status'} eq SEEK_BYTE) {
		$step = 800000000;
		$pos = $step;
		$info->{'seek_status'} = SEEK_NONE;
		do {
			status_crop($slice++);
			$ret = mplayer_get_slice_crop($info, "-sb $pos", $config->{'crop_frames'});
			$info->{'seek_status'} = SEEK_BYTE if ($ret eq CROP_SLICE_OK);
			$pos+= $step;
		} while ($ret eq CROP_SLICE_OK);
	}
	
	status_crop($slice++);
	if ($info->{'seek_status'} eq SEEK_NONE) {
		mplayer_get_slice_crop($info, '', 150) ;
	} else {
		mplayer_get_slice_crop($info, '', $config->{'crop_frames'});
	}
	
	if 	(($info->{'video'}->{'crop'}->{'xres'} == 0) ||
		($info->{'video'}->{'crop'}->{'yres'} == 0)) {
		
		$info->{'video'}->{'crop'}->{'left'} = 0;
		$info->{'video'}->{'crop'}->{'top'} = 0;
		$info->{'video'}->{'crop'}->{'xres'} = $info->{'video'}->{'width'};
		$info->{'video'}->{'crop'}->{'yres'} = $info->{'video'}->{'height'};
		msgg(INFO, "AUTO CROP: could not get crop\n");
		#in future set fall back to crop by user
	}
	$info->{'video'}->{'crop'}->{'status'} = CROP_READY;
	status('');
}

sub mplayer_get_dvd_info {
	my ($dvd_device) = @_;

	my $info = {};
	$info->{'dvd_device'} = $dvd_device;
	
	my $cmd = mplayer_get_cmd("dvd:// -dvd-device $dvd_device -identify -frames 0 -vo null -ao null");
	msgg(INFO, "MPLAYER GET DVD INFO: $cmd\n");
	my $pid = open OUT, "-|", $cmd;
	my $media_ok = 1;
	my $aid = alarm_start(
			sub {
				msgg(INFO, "GET STREAM INFO: timeout\n");
				mplayer_kill($pid);
			},
			$mplayer_timeout);

	
	my $line;
	my $errstr;
	while(<OUT>) {
		$line = $_;
		if ($line =~ /ID_DVD_TITLES=(\d+)/i) {
			$info->{'title_count'} = $1;
		} elsif ($line =~ /ID_DVD_DISC_ID=(\w+)/i) {
			$info->{'name'} = $1;
		} elsif ($line =~ /ID_DVD_CURRENT_TITLE=(\d+)/i) {
			$info->{'main_title'} = $1;
		}
		
	}	#while
	alarm_stop($aid);
	close OUT;
	undef $info if (!defined($info->{'title_count'}));
	return $info;
}


sub get_dvd_info {
	my ($dvd_device) = @_;
	my $info;
	$info = mplayer_get_dvd_info($dvd_device);
	if (!defined($info)) {
		#we will try find subdirectories
		msgg(INFO, "Trying have a look in subdirectiories\n");
		find(sub {
			if (-d and /VIDEO_TS/i) {
				msgg(INFO, "found directory VIDEO_TS in directory $File::Find::dir\n");
				$info = mplayer_get_dvd_info("<quote>$File::Find::dir<quote>");
			}
		
		}, "$mount_point/"); 
	}
	$info->{'name'} = (&disc_name);
	return $info;		
}

sub mplayer_get_stream_info {
	my ($stream_uri) = @_;
	my $cmd = mplayer_get_cmd("$stream_uri -identify -frames 1 -vo null -ao null", 1);
	msgg(INFO, "MPLAYER GET INFO COMMAND: $cmd\n");
	my $pid = open OUT, "-|", $cmd;
	my $media_ok = 1;
	my $aid = alarm_start(
			sub {
				msgg(INFO, "GET STREAM INFO: timeout\n");
				mplayer_kill($pid);
				undef $media_ok;
			},
			$mplayer_timeout);

	my $info = {};
	$info->{'uri'} = $stream_uri;
	$info->{'status'} = MEDIA_ERROR;
	$info->{'seek_status'} = SEEK_UNKNOWN;
	$info->{'audio_count'} = 0;
	$info->{'subtitle_count'} = 0;
	
	my $line;
	my $errstr;
	while(<OUT>) {
		$line = $_;
		if ($line =~ /ID_AUDIO_ID=(\d+)/i) {
			if (!$info->{'audio'}->{$1}) {
				$info->{'audio_count'}++;
				$info->{'audio'}->{$1}->{'langcode'} = undef; 
			}
		} elsif ($line =~ /ID_AID_(\d+)_LANG=(.+)/i) {
			$info->{'audio'}->{$1}->{'langcode'} = $2;
		} elsif ($line =~ /ID_SUBTITLE_ID=(\d+)/i) {
			if (!$info->{'subtitle'}->{$1}) {
				$info->{'subtitle_count'}++;
				$info->{'subtitle'}->{$1}->{'langcode'} = undef; 
			}
		} elsif ($line =~ /ID_SID_(\d+)_LANG=(.+)/i) {
			$info->{'subtitle'}->{$1}->{'langcode'} = $2;
		} elsif ($line =~ /ID_LENGTH=(\d+.\d*)/i) {
			$info->{'length'} = $1;
		} elsif ($line =~ /ID_VIDEO_HEIGHT=(\d+)/i) {
			$info->{'video'}->{'height'} = $1;
		} elsif ($line =~ /ID_VIDEO_WIDTH=(\d+)/i) {
			$info->{'video'}->{'width'} = $1;
		} elsif ($line =~ /ID_VIDEO_ASPECT=(\d+.\d*)/i) {
			$info->{'video'}->{'aspect'} = $1;
		} elsif ($line =~ /Movie-Aspect is (\d+.\d*)/i) {
			$info->{'video'}->{'aspect'} = $1;
		} 
		foreach $errstr('invalid dvd title', 'failed to open',
						'file not found',  'no stream found') {
			if ($line =~ /$errstr/i) {
				$info->{'status'} = MEDIA_NOT_FOUND;
				undef $media_ok;
				last;
			}
		}
	}	#while
	alarm_stop($aid);
	close OUT;
	if (defined($media_ok)) {
		$info->{'status'} = MEDIA_OK;
		
		if (!(defined($info->{'video'}) || defined($info->{'audio'})) ) {
			undef $info;
		} else {
			#this is hack as some dvds has bad aspect
			if (get_uri_type($stream_uri) eq DVD) {
				$info->{'video'}->{'aspect'} = 16/9 if ($info->{'video'}->{'aspect'} == 0);
				$info->{'video'}->{'aspect'} = 4/3 if ($info->{'video'}->{'aspect'} < 1.34);
				$info->{'video'}->{'aspect'} = 16/9 if ($info->{'video'}->{'aspect'} > 1.69);
			} else {
				$info->{'video'}->{'aspect'} = $info->{'video'}->{'width'} / $info->{'video'}->{'height'}
					if ($info->{'video'}->{'aspect'} == 0);
			}
			if (defined($info->{'video'})) {
				$info->{'video'}->{'crop'}->{'status'} = CROP_AUTO;
			} 
		}
	}
	
	return $info;
}


#################################################################################


sub status {
	my ($msg) = @_;
	$status_bar->push(0, $msg);
}


sub hhmmss ($) {
	my $s    = shift;
	my $m    = int ($s / 60);
	my $mins = $m % 60;
	my $hour = int ($m / 60);
	return sprintf( "%d:%02d:%02d", $hour, $mins, $s % 60 );
}

sub sec_to_str {
	my ($sec) = @_;
	my $m    = int ($sec / 60);
  	my $mins = $m % 60;
	my $hour = int ($m / 60);
	return sprintf( "%d:%02d ".msg('hours'), $hour, $mins) if ($hour > 0);
	return sprintf( "%d:%02d ".msg('mins'), $mins, $sec % 60) if ($mins > 0);
	return sprintf( "%d ".msg('secs'), $sec);
}

sub profile_desc {
	my ($id) = @_;

	return $profiles[$id]->{'name'};
}



my $dvd_info = {};

sub get_stream {
	my ($uri) = @_;
	my $stream = {};
	$stream->{'stream'} = mplayer_get_stream_info($uri);
	if (defined($stream->{'stream'}) && $stream->{'stream'}->{'status'} eq MEDIA_OK) {
		#set defaults values
		$stream->{'setting'}->{'profile_id'} = $config->{'default_profile'};
		if (defined($stream->{'stream'}->{'audio'})) {
			$stream->{'setting'}->{'audio_id'} = (sort keys %{$stream->{'stream'}->{'audio'}})[0];
		} else {
			$stream->{'setting'}->{'audio_id'} = -1;
		}
		$stream->{'setting'}->{'subtitle_id'} = -1;
	} else {
		undef $stream;
	}
	return $stream;
}

sub lang_desc {
	my ($stream, $id) = @_;
	my $desc;
	if ($id == -1) {
		$desc = msg('<none>');
	} else {
		$desc = name_from_639_code($stream->{$id}->{'langcode'});
	}
	return $desc;
}

sub get_stream_desc {
	my ($stream) = @_;
	my $desc = {};
	$desc->{'length'} = sec_to_str($stream->{'stream'}->{'length'});
	my $aspect = $stream->{'stream'}->{'video'}->{'aspect'};
	$aspect = '16/9' if $aspect == 16/9;
	$aspect = '4/3' if $aspect == 4/3;
	$desc->{'aspect'} = $aspect;
	$desc->{'audio'} = lang_desc($stream->{'stream'}->{'audio'}, $stream->{'setting'}->{'audio_id'});
	$desc->{'subtitle'} = lang_desc($stream->{'stream'}->{'subtitle'}, $stream->{'setting'}->{'subtitle_id'});
	$desc->{'profile'} = @profiles[$stream->{'setting'}->{'profile_id'}]->{'name'};
	return $desc;
}

sub disc_refresh {
	$title_model->clear;
	while ( Gtk2->events_pending() ) { Gtk2->main_iteration() };
	$dvd_info = get_dvd_info($config->{'dvd_device'});
	my $stream = {};
	my $desc;
	my $aid;
	my $iter;
	my $audio;
	my $len;
	my $title_name = &disc_name;
	my $dvd_name = $title_name;
	$rows = 0;
	my $main_row = 0;
	for (my $t=1; $t <= $dvd_info->{'title_count'};$t++) {
		my $status = '$status="'.msg('Reading DVD $dvd_name Title $t').'"';
		eval($status);
		&status($status);
		while ( Gtk2->events_pending() ) { Gtk2->main_iteration() };
		$stream = get_stream("dvd://$t -dvd-device ". unspace($dvd_info->{'dvd_device'}));
		if (defined($stream)) {
			$desc = get_stream_desc($stream);
			$iter = $title_model->append;
			$title_model->set ($iter,
				0 => $stream,
				1 => (($t == $dvd_info->{'main_title'}) ? 1 : 0),
				2 => (($t == $dvd_info->{'main_title'}) ? ($dvd_info->{'name'}) : ($dvd_info->{'name'}.' - '."Title $t")),
				3 => $desc->{'length'},
				4 => $desc->{'aspect'},
				5 => $desc->{'audio'},
				6 => $desc->{'subtitle'},
				7 => $desc->{'profile'}
			);
			$main_row = $rows if ($t == $dvd_info->{'main_title'});
			$rows++;
		}
	}
	&update_one_toogled;
	$title_view->get_selection->select_path(Gtk2::TreePath->new_from_string ($main_row));
	&update_controls;
	&status('');
}

sub selected_row {
	my $path =  $title_view->get_selection->get_selected_rows;
	if ($path) {
		$path = int ($path->to_string);
	} else {
		$path = -1;
	}
	return $path;
}

sub get_list_value {
	my ($row, $col) = @_;

	if ($row == -1) {
		return;
	}
	my $value = $title_view->get_model->get(
		$title_view->get_model->get_iter(
			Gtk2::TreePath->new_from_string ($row)), $col);

	return $value;
}

sub set_list_value {
	my ($row, $col, $value) = @_;

	$title_view->get_model->set(
		$title_view->get_model->get_iter(
			Gtk2::TreePath->new_from_string ($row)), $col, $value);
}

sub mplayer_get_uri {
	my ($stream) = @_;
	
	my $uri = $stream->{'stream'}->{'uri'};
	if ($stream->{'setting'}->{'audio_id'} == -1) {
		$uri.=' -nosound';
	} else {
		$uri .= " -aid $stream->{'setting'}->{'audio_id'}";
	}

	if ($stream->{'setting'}->{'subtitle_id'} == -1) {
#		$uri.=' -ao null';
	} else {
		$uri .= " -sid $stream->{'setting'}->{'subtitle_id'}";
	}
	return $uri;
}

sub get_output_size {
	my ($stream) = @_;
	my $profile = $stream->{'setting'}->{'profile_id'};

	my $aspect = $stream->{'stream'}->{'video'}->{'aspect'};
	my $source_xres = $stream->{'stream'}->{'video'}->{'width'};
	my $source_yres = $stream->{'stream'}->{'video'}->{'height'};
	crop($stream->{'stream'});
	my $crop_l = $stream->{'stream'}->{'video'}->{'crop'}->{'left'};
	my $crop_t = $stream->{'stream'}->{'video'}->{'crop'}->{'top'};
	my $crop_w = $stream->{'stream'}->{'video'}->{'crop'}->{'xres'};
	my $crop_h = $stream->{'stream'}->{'video'}->{'crop'}->{'yres'};

	my $crop_aspect = ($source_yres * $aspect / $source_xres * $crop_w) / $crop_h;
	
	my $xres = $profiles[$profile]->{'width'};
	$xres = eval("$xres");
	$xres = $crop_w if $xres > $crop_w;
	
	my $yres = int ($xres / $crop_aspect);

	$yres = (int ($yres / 16)) * 16;
	return ($crop_w, $crop_h, $crop_l, $crop_t, $xres, $yres);
}

sub prepare_job {
	my @job = ();
	my $dir = unspace($config->{'output_directory'});
	for (my $row=0;$row < $rows;$row++) {
		if (get_list_value($row, 1) == 1) {
			my $stream = get_list_value($row, 0);
			my $url = mplayer_get_uri($stream);
			my $name = unspace(get_list_value($row, 2));
			my ($crop_w, $crop_h, $crop_l, $crop_t, $xres, $yres) = get_output_size($stream);
			my $autocrop = "$crop_w:$crop_h:$crop_l:$crop_t";
			my $autoscale = "$xres:$yres";
			my $profile = $profiles[$stream->{'setting'}->{'profile_id'}];
			#it is dirty we should pass spaces as something and before run and 
			# tranlate command back to spaces as the shell may interpret the spaces differnet way
			# but it is working now :)
			my $abitrate = $profile->{'abitrate'};
			my $vbitrate = (int ($profile->{'size'} / $stream->{'stream'}->{'length'} * 8192)) - $abitrate;
			$vbitrate=5000 if ($vbitrate>=5000);

			for (my $pass_c = 1;$pass_c <= $profile->{'cmd'}->{'passcount'}; $pass_c++) {
				my $rec = {};
				my $cmd = '$cmd="'.$profile->{'cmd'}->{"pass$pass_c"}.'"';
				eval $cmd;
				$rec->{'cmd'} = $cmd;
				$rec->{'video_time'} = int($stream->{'stream'}->{'length'});
				my $koef = $profile->{'proggresstimekoeficient'}->{"pass$pass_c"};
				$koef = 1 if (!$koef);
				$rec->{'prog_time'} = int($stream->{'stream'}->{'length'} * $koef);
				my $job_name = '$job_name="'.msg('Converting $name').'"';
				$name = space($name);
				eval($job_name);
				$name = unspace($name);
				$rec->{'name'} = $job_name;
				push @job, $rec;
			}

		}
	}
	return @job;
}

my $one_toogled;

sub update_one_toogled {
	my $c = 0;
	for(my $x = 0; $x < $rows; $x++) {
		$c++ if (get_list_value($x, 1) == 1);
	}
	$one_toogled = ($c > 0 ? 1 : 0);
}

sub update_controls {
	$progress_bar->set('visible', $processing == 1);
	$btn_cancel->set('visible', $processing == 1);
	$icon_rip->set('sensitive', $processing != 1 && $dvd_inserted == 1 && $one_toogled == 1);
	$dvd_menu_record->set('sensitive', $processing != 1 && $dvd_inserted == 1 && $one_toogled == 1);
	$dvd_menu_eject->set('sensitive', $processing != 1 && $dvd_inserted == 1);
	$dvd_menu_refresh->set('sensitive', $processing != 1 && $dvd_inserted == 1);
	$icon_refresh->set('sensitive', $processing != 1 && $dvd_inserted == 1);
	$icon_play->set('sensitive', $dvd_inserted == 1);
	$icon_preview->set('sensitive', $dvd_inserted == 1);
	$icon_settings->set('sensitive', $dvd_inserted == 1);
	$title_menu_play->set('sensitive', $dvd_inserted == 1);
	$title_menu_settings->set('sensitive', $dvd_inserted == 1);
	$title_menu_preview->set('sensitive', $dvd_inserted == 1);
	$status_bar->set_has_resize_grip($processing != 1); 
	
}

################################Signals#################################
sub title_settings_apply {
	my $row = &selected_row;
	my $stream = get_list_value($row, 0);

	$stream->{'setting'}->{'profile_id'} = $cmb_profiles->get('active');
	my $i = $cmb_language->get('active');
	if ($i == 0) {
		$stream->{'setting'}->{'audio_id'} = -1;
	} else {
		$stream->{'setting'}->{'audio_id'} =
			(sort keys %{$stream->{'stream'}->{'audio'}})[$i - 1];
	}

	$i = $cmb_subtitles->get('active');
	if ($i == 0) {
		$stream->{'setting'}->{'subtitle_id'} = -1;
	} else {
		$stream->{'setting'}->{'subtitle_id'} =
			(sort keys %{$stream->{'stream'}->{'subtitle'}})[$i - 1];
	}

	my $desc = get_stream_desc($stream);	
	set_list_value($row, 7, $desc->{'profile'});
	set_list_value($row, 6, $desc->{'subtitle'});
	set_list_value($row, 5, $desc->{'audio'});
	$win_settings->hide;	
}

sub title_edited {
	my ($render, $text1, $text2, $model) = @_;
	return 1 if ($processing == 1);
	my $path = Gtk2::TreePath->new_from_string ($text1);
	my $iter = $model->get_iter ($path);
	$model->set ($iter, 2, $text2);
}

sub selected_toggled {
	my ($r, $op, $model) = @_;
	return 1 if ($processing == 1);
	my $path = Gtk2::TreePath->new_from_string ($op);
	my $iter = $model->get_iter ($path);
	if ($model->get($iter, 1) == 0) {
		$model->set ($iter, 1, 1);
		$one_toogled = 1;
	} else {
		$model->set ($iter, 1, 0);
		&update_one_toogled;
	}
	&update_controls;
}

sub eject {
	system($config->{'eject_cmd'});
}

sub poweroff {
	system($config->{'shutdown_cmd'});
}

sub title_play {
	my $stream = get_list_value(selected_row, 0);
	my $uri = mplayer_get_uri($stream);
	my $cmd = mplayer_get_cmd("$uri -aspect $stream->{'stream'}->{'video'}->{'aspect'}", 0);
	msgg(INFO, "MPLAYER PLAY CMD: $cmd\n");
	system($cmd);
}


sub rip {
	my (@jobs) = &prepare_job;	
	$processing = 1;
	&update_controls;
	my $prog_time = 0;

	my $pc;
	my $job_cmd;
	my $job_name;
	my $i;
	for($pc=0;$pc <= $#jobs; $pc++) {
		$prog_time += $jobs[$pc]->{'prog_time'};
	}
	my $fraction = 1 / $prog_time;
	my $low_frac;
	my $job_frac;
	my $start_time = time;
	my $job_prog;
	my $rip_time;
	my $time_left;
	my $prog_text;
	$canceled = 0;
	my $job;
	my $job_count = $#jobs + 1;
	my $rip;
	for($pc=0;$pc < $job_count; $pc++) {
		$job_cmd = $jobs[$pc]->{'cmd'};
		$job = $pc+1;
		$job_name = $jobs[$pc]->{'name'};
		&status($job_name);
		$prog_time = 0;
		for ($i = 0; $i < $pc; $i++) {
			$prog_time += $jobs[$i]->{'prog_time'};
		}
		$job_frac = $jobs[$pc]->{'prog_time'};
		$job_frac = $job_frac * $fraction / 100;
		$low_frac = $prog_time * $fraction;
		#we need to split command and run it as arguments as we prevent to run in shell
		# and maybe we need workaround wit spaces (the filename) butit`s working now
		my @cmd = split " ", $job_cmd;
		for(my $cc = 0;$cc <= $#cmd; $cc++) {
			@cmd[$cc] =~ s/<quote>//g;
			@cmd[$cc] = space(@cmd[$cc]);
		}
		msgg(INFO, "MENCODER CMD: ".join " ", @cmd, "\n");
		$menc_id  = open3(undef, $rip, undef, @cmd);
		my $video_time = $jobs[$pc]->{'video_time'};
		$/ = "\r";
		while (<$rip>) {
			my $line = $_;
			if ($line =~/^Pos\D*([\d\.]+)\D*(\d+)\D*(\d+)\D*([\d\.]+)\D*(\d+)\D*(\d+)\D*([\d\.]+)\D*(\d+)\D*(\d+)/) {
				my $pp = $1 / ($video_time / 100);
				$pp = 100 if ($pp > 100);
				$job_prog = $low_frac + ($pp * $job_frac);
				$progress_bar->set_fraction($job_prog);
				$rip_time = (time - $start_time);
				if ($rip_time > 0 && $job_prog > 0) {
					$time_left = int ((1 - $job_prog) * ((1 / $job_prog) * $rip_time));
				} else {
					$time_left = 9000;
				}
				$time_left = &sec_to_str($time_left);
				$prog_text = '$prog_text="'.msg('Job: $job of $job_count ( $time_left remaining ) Speed: $4fps Size: $6mb').'"';
				eval($prog_text);

				if ($rip_time > 0) {
					$progress_bar->set_text ($prog_text);
				}
			} else {
				msgg(MPLAYER, "$line\n");
			}
			while ( Gtk2->events_pending() ) { Gtk2->main_iteration() };
		}
		$/ = "\n";
		return if ($canceled == 1);
		waitpid $menc_id, 0;
	}
	$menc_id = undef;
	$processing = 0;
	&update_controls;
	my ($dvd_name) = &disc_name;
	my $status = '$status="'.msg('Job: $dvd_name finished...').'"';
	eval($status);
	&status($status);
	&eject if ($config->{'eject_after'} == 1);
	&poweroff if ($config->{'shutdown_after'} == 1);
}

sub cancel {
	return 1 if (!$menc_id);
	my $confirm = Gtk2::MessageDialog->new($app_window, 
			[qw/modal destroy-with-parent/], 'question', 'none', msg('Are you sure you want to stop the convert process?'));
	$confirm->add_buttons('er-no', 'no', 'er-yes', 'yes');
	if (lstat $config->{'lemonrip_icon'}) { 
		$confirm->set_icon_from_file($config->{'lemonrip_icon'});
	} else {
		$confirm->set_icon_name('gtk-cdrom');
	}
	$confirm->set_title(msg("Question"));
	if ($confirm->run eq 'yes') {
		$confirm->destroy;
		if (defined($menc_id)) {
			mplayer_kill($menc_id);
			$canceled = 1;
			$processing = 0;
			waitpid $menc_id, 0;
			$menc_id = undef;
		}
		&update_controls;
		&status(msg('Job was canceled...'));
		return 1;
	} else {
		$confirm->destroy;
		return 0;		
	}
}

sub app_quit {
	Gtk2->main_quit if (&cancel == 1);
	close LOGFILE;
	return 1;
}

sub title_settings {
	my $row = &selected_row;

	my $stream = &get_list_value($row, 0);
	$cmb_language->get_model->clear;
	$cmb_language->append_text(msg('<none>'));
	my $value_id = $stream->{'setting'}->{'audio_id'};
	my $c = 1;
	my $value = 0;
	my $language;
	my $id;
	if (defined($stream->{'stream'}->{'audio'})) {
		foreach my $id (sort keys %{$stream->{'stream'}->{'audio'}}) {
			$value = $c if $id == $value_id;
			$language = lang_desc($stream->{'stream'}->{'audio'}, $id);
			$cmb_language->append_text($language);
			$c++;
		}
	}
	$cmb_language->set('active', $value);

	$value = 0;
	$c = 1;	
	$value_id = $stream->{'setting'}->{'subtitle_id'};
	$cmb_subtitles->get_model->clear;
	$cmb_subtitles->append_text(msg('<none>'));
	if (defined($stream->{'stream'}->{'subtitle'})) {
		foreach $id (sort keys %{$stream->{'stream'}->{'subtitle'}}) {
			$value = $c if $id == $value_id;
			$language = lang_desc($stream->{'stream'}->{'subtitle'}, $id);
			$cmb_subtitles->append_text($language);
			$c++;
		}
	}
	$cmb_subtitles->set('active', $value);

	$value = $stream->{'setting'}->{'profile_id'};
	$cmb_profiles->set('active', $value);
	
	$win_settings->show_all; 
}

sub title_preview {
	my $stream = get_list_value(selected_row, 0);
	my $crop_w;
	my $crop_h;
	my $crop_l;
	my $crop_t;
	my $xres;
	my $yres;
	($crop_w, $crop_h, $crop_l, $crop_t, $xres, $yres) = get_output_size($stream);
	my $uri = mplayer_get_uri($stream);

	my $cmd = mplayer_get_cmd("$uri -aspect $stream->{'stream'}->{'video'}->{'aspect'} -vf pullup,softskip,crop=$crop_w:$crop_h:$crop_l:$crop_t,scale=$xres:$yres", 0);
	msgg(INFO, "MPLAYER PREVIEW CMD: $cmd\n");
	system($cmd);
}

################################DVD monitoring################################
my $timeout_id;

sub dvd_monitor_activated {
	return 1 if ($processing == 1); #it is just hack until the proper solution of copy on disk before trancode...:)
	my $mounted = &dvd_mounted;
	if ($dvd_inserted == $mounted) {
		return 1;
	}
	$dvd_inserted = $mounted;
	if ($dvd_inserted == 1) {
		&disc_refresh;
		return 1;
	} else {
		&dvd_removed;
		return 1;
	}
}

sub dvd_removed {
	&status(msg('DVD removed...'));
	if (defined($menc_id)) {
		mplayer_kill($menc_id);
		$canceled = 1;
		waitpid $menc_id, 0;
		$menc_id = undef;
		$processing = 0;
	};
	&update_controls;
	$title_model->clear;
}

sub dvd_monitor_start {
	$timeout_id = Glib::Timeout->add(1000, \&dvd_monitor_activated, \$timeout_id) if (!$timeout_id);
}

sub dvd_monitor_stop {
	Glib::Source->remove($timeout_id) if ($timeout_id);
	$timeout_id = undef;
}

sub dvd_mounted {
	my $mount = `mount`;
	my $mounted = 0;
	foreach my $line ($mount) {
			$mounted++ if ($line =~/$config->{'dvd_device'}/);
			$mount_point = $1 if ($line =~/$config->{'dvd_device'}.*on[^\/]*(.*)[ \t]type/i);
	}
	return ($mounted > 0 ? 1 : 0);
}

$SIG{INT} = sub {
		if (defined($menc_id)) {
			mplayer_kill($menc_id);
			waitpid $menc_id, 0;
			$menc_id = undef;
		}
		msgg(INFO, "Lemonrip interupted\n");
		app_quit;
		return 1;
	};

$app_window->show_all;
&dvd_monitor_start;
&update_controls;
Gtk2->main;

1;
