#!/usr/bin/perl

########################################################################
# This program is free software; you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation; either version 2 of the License, or    #
# (at your option) any later version.                                  #
#                                                                      #
# This program is distributed in the hope that it will be useful,      #
# but WITHOUT ANY WARRANTY; without even the implied warranty of       #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the         #
# GNU General Public License for more details at http://www.gnu.org    #
########################################################################

#use diagnostics;

$VERSION = 0.1;
$srtrepair_gui_ver = '0.1';

#use POSIX;
use locale;
use Env;
use Tk;
#use Tk::ErrorDialog;
require Tk::LabFrame;
require Tk::NoteBook;
require Tk::DialogBox;
require Tk::Dialog;
require Tk::ProgressBar;
require Tk::Entry;

use encoding 'cp1250';
use open ':encoding(cp1250)';


$recode_parm = 2;
#def $recode_parm - character set code page of SRT subtitles: 1..ISO-2 2..Windows1250 3..ISO-1

$txt_sub_file = "";
$srt_subtitles = "subtitles";

$work_dir = "";

#*******************************************************************
# GUI   W I D G E T S    D E F I N I T I O N S
#*******************************************************************


#============================== PGM subtitles generation Window ==============================================

$mw = MainWindow -> new();
$main_win_title = "srtrepair GUI for Windows, version $srtrepair_gui_ver";

$mw -> title($main_win_title);

$mw_main_frame1 = $mw -> Frame() -> pack( -side => 'top', -expand => 'y', -fill => 'x' );

$mw_frame1 = $mw_main_frame1 -> Frame() -> pack( -side => 'left', -anchor => 'nw' );

$mw_frame1_1 = $mw_frame1 -> LabFrame( -label => 'Subtitles repair', -labelside => 'acrosstop' ) -> pack( -anchor => 'nw', -fill => 'x', -expand => 'y' );

$srtrepair_parm1 = 2; #1..check only 2..repair
$srtrepair_parm2 = 1; #renumber subtitles
$srtrepair_parm3 = 1; #skip empty
$srtrepair_parm4 = 1; #check wording/grammar
$srtrepair_parm5 = 1; #1..Czech 2..English

$srtrepair_widget1_1 = $mw_frame1_1 -> Radiobutton( -variable => \$srtrepair_parm1,
						-text => 'Check only',
						-value => 1,
						) -> pack( -anchor => 'w' );

$srtrepair_widget1_2 = $mw_frame1_1 -> Radiobutton( -variable => \$srtrepair_parm1,
						-text => 'Repair',
						-value => 2,
						) -> pack( -anchor => 'w' );

$mw_frame1_1 -> Checkbutton( -text => 'Renumber subtitles',
			    	-variable => \$srtrepair_parm2
			      ) -> pack( -anchor => 'w' );

$mw_frame1_1 -> Checkbutton( -text => 'Skip empty subtitles',
			    	-variable => \$srtrepair_parm3
			      ) -> pack( -anchor => 'w' );

$mw_frame1_1 -> Checkbutton( -text => 'Check wording',
			    	-variable => \$srtrepair_parm4
			      ) -> pack( -side => 'left', -anchor => 'nw' );

$mw_frame1_1_1 = $mw_frame1_1 -> Frame() -> pack ( -side => 'right', -anchor => 'e' );


$srtrepair_widget2_1 = $mw_frame1_1_1 -> Radiobutton( -variable => \$srtrepair_parm5,
						-text => 'Czech',
						-value => 1,
						) -> pack( -anchor => 'w' );

$srtrepair_widget2_2 = $mw_frame1_1_1 -> Radiobutton( -variable => \$srtrepair_parm5,
						-text => 'English',
						-value => 2,
						) -> pack( -anchor => 'w' );

$srtrepair_btn1 = $mw_frame1_1_1 -> Button( -text => 'Run repair',
	    				      -command => sub { &run_srtrepair(1); }
					     ) -> pack( -side => 'right' );




$mw_frame1_2 = $mw_frame1 -> LabFrame( -label => 'Subtitles timing manipulation', -labelside => 'acrosstop' ) -> pack( -anchor => 'nw', -fill => 'x', -expand => 'y' );

$mw_frame1_2_1 = $mw_frame1_2 -> LabFrame( -label => 'Time shift', -labelside => 'acrosstop' ) -> pack( -anchor => 'nw' );

$mw_frame1_2_1_1 = $mw_frame1_2_1 -> Frame() -> pack( -anchor => 'w' );

$srtrepair_parm6 = 3; #1..shift forward 2..shift backward 3..none

$srtrepair_widget3_1 = $mw_frame1_2_1_1 -> Radiobutton( -variable => \$srtrepair_parm6,
						-text => 'Forward',
						-value => 1,
						) -> pack( -side => 'left' );

$srtrepair_widget3_2 = $mw_frame1_2_1_1 -> Radiobutton( -variable => \$srtrepair_parm6,
						-text => 'Backward',
						-value => 2,
						) -> pack( -side => 'left' );

$srtrepair_widget3_3 = $mw_frame1_2_1_1 -> Radiobutton( -variable => \$srtrepair_parm6,
						-text => 'None',
						-value => 3,
						) -> pack( -side => 'left' );

$mw_frame1_2_1_2 = $mw_frame1_2_1 -> Frame() -> pack( -anchor => 'w' );

$shift_h = 0;
$shift_m = 0;
$shift_s = 0;

&NumEntry($mw_frame1_2_1_2,-textvariable=>\$shift_h,-width=>2,-minvalue=>0,-maxvalue=>9) -> pack( -side => 'left' );
$mw_frame1_2_1_2_l1 = $mw_frame1_2_1_2 -> Label( -text => "h " ) -> pack( -side => 'left' );
&NumEntry($mw_frame1_2_1_2,-textvariable=>\$shift_m,-width=>2,-minvalue=>0,-maxvalue=>59) -> pack( -side => 'left' );
$mw_frame1_2_1_2_l2 = $mw_frame1_2_1_2 -> Label( -text => "m " ) -> pack( -side => 'left' );
&NumEntry($mw_frame1_2_1_2,-textvariable=>\$shift_s,-width=>6,-minvalue=>0,-maxvalue=>59) -> pack( -side => 'left' );
$mw_frame1_2_1_2_l3 = $mw_frame1_2_1_2 -> Label( -text => "s " ) -> pack( -side => 'left' );

$srtrepair_parm7 = 0; #force shift

$mw_frame1_2_1 -> Checkbutton( -text => 'Force shift',
			    	-variable => \$srtrepair_parm7
			      ) -> pack( -anchor => 'w' );

$mw_frame1_2_1 -> Checkbutton( -text => 'Renumber subtitles',
			    	-variable => \$srtrepair_parm9
			      ) -> pack( -anchor => 'w' );




$mw_frame1_2_2 = $mw_frame1_2 -> LabFrame( -label => 'Speed shift', -labelside => 'acrosstop' ) -> pack( -anchor => 'nw', -fill => 'x' );

$mw_frame1_2_2_1 = $mw_frame1_2_2 -> Frame() -> pack( -anchor => 'w' );

$srtrepair_parm8 = 3; #1..speed forward 2..speed backward 3..none

$srtrepair_widget4_1 = $mw_frame1_2_2_1 -> Radiobutton( -variable => \$srtrepair_parm8,
						-text => 'Shorten',
						-value => 1,
						) -> pack( -side => 'left' );

$srtrepair_widget4_2 = $mw_frame1_2_2_1 -> Radiobutton( -variable => \$srtrepair_parm8,
						-text => 'Stretch',
						-value => 2,
						) -> pack( -side => 'left' );

$srtrepair_widget4_3 = $mw_frame1_2_2_1 -> Radiobutton( -variable => \$srtrepair_parm8,
						-text => 'None',
						-value => 3,
						) -> pack( -side => 'left' );

$enter_shift_speed = $mw_frame1_2_2 -> Entry( -width => 10 ) -> pack( -side => 'left' );
$enter_shift_speed -> insert('0', '0.000');
$mw_frame1_2_2_l1 = $mw_frame1_2_2 -> Label( -text => " sec/sec" ) -> pack( -side => 'left' );

$srtrepair_btn2 = $mw_frame1_2 -> Button( -text => 'Run time/speed shift',
	    				      -command => sub { &run_srtrepair(2); }
					     ) -> pack( -side => 'right' );

$mw_frame1_3 = $mw_frame1 -> LabFrame( -label => 'Subtitles export/import', -labelside => 'acrosstop' ) -> pack( -anchor => 'nw', -fill => 'x' );

$srtrepair_fps = 25;
$enter_fps = $mw_frame1_3 -> Entry( -width => 6 ) -> pack( -side => 'left' );
$enter_fps -> insert('0', '25.000');
$mw_frame1_3_l1 = $mw_frame1_3 -> Label( -text => 'FPS  ' ) -> pack( -side => 'left' );

$srtrepair_btn3 = $mw_frame1_3 -> Button( -text => 'Export',
	    				      -command => sub { &run_srtrepair(3); }
					     ) -> pack( -side => 'left' );

$srtrepair_btn4 = $mw_frame1_3 -> Button( -text => 'Import',
	    				      -command => sub { &run_srtrepair(4); }
					     ) -> pack( -side => 'right' );




$mw_frame1_0 = $mw_frame1 -> LabFrame( -label => 'Charset (recode required)', -labelside => 'acrosstop' ) -> pack( -anchor => 'nw', -fill => 'x', -expand => 'y' );

$srtrepair_widget0_1 = $mw_frame1_0 -> Radiobutton( -variable => \$recode_parm,
						-text => 'ISO-8859-1',
						-value => 3,
						) -> pack( -anchor => 'w' );

$srtrepair_widget0_1 = $mw_frame1_0 -> Radiobutton( -variable => \$recode_parm,
						-text => 'ISO-8859-2',
						-value => 1,
						) -> pack( -anchor => 'w' );

$srtrepair_widget0_2 = $mw_frame1_0 -> Radiobutton( -variable => \$recode_parm,
						-text => 'Windows 1250',
						-value => 2,
						) -> pack( -anchor => 'w' );



$mw_frame2 = $mw_main_frame1 -> LabFrame( -label => 'SRT subtitles', -labelside => 'acrosstop' ) -> pack( -side => 'right', -expand => 'y', -fill => 'both' );

$srt_sub_edit = $mw_frame2 -> Scrolled('Text', -width => 50, -scrollbars => 'e' ) -> pack( -fill => 'both', -expand => 'y' );

$srtrepair_log_label = $mw_frame2 -> Label( -text => 'srtrepair log:' ) -> pack( -anchor => 'w' );
$srtrepair_log = $mw_frame2 -> Scrolled('Text', -width => 50, -height => 10, -scrollbars => 'e' ) -> pack( -fill => 'x' );


$mw_main_frame2 = $mw -> Frame() -> pack( -side => 'bottom', -anchor => 'w' );


$load_txt_subs_btn = $mw_main_frame2 -> Button( -text => 'Load TXT subtitles',
	    				      -command => sub { &load_txt_subs; }
					     ) -> pack( -side => 'left' );

$save_txt_subs_btn = $mw_main_frame2 -> Button( -text => 'Save TXT subtitles',
	    				      -command => sub { &save_txt_subs; }
					     ) -> pack( -side => 'left' );

$saveas_txt_subs_btn = $mw_main_frame2 -> Button( -text => 'Save TXT subtitles as...',
	    				      -command => sub { &saveas_txt_subs; }
					     ) -> pack( -side => 'left' );

$load_timing_btn =  $mw_main_frame2 -> Button( -text => 'Load subtitles timing from...',
	    				      -command => sub {  &run_srtrepair(5); }
					     ) -> pack( -side => 'right' );


#----------------------------------------------------------



#*******************************************************************
# E N D   OF   GUI   F O R M S   D E F I N I T I O N S
#*******************************************************************


#/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
#\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
#/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
#\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/


#*******************************************************************
# HERE STARTS THE MAIN CODE
#*******************************************************************



MainLoop();


print "here the code continues in non-Tk end-part\n";

print "Enjoy the subtitles ;-)\n";

#*******************************************************************
# HERE ENDS THE MAIN CODE
#*******************************************************************





#*******************************************************************
# P R O C E D U R E S   S E C T I O N
#*******************************************************************




#======================================================================================
sub temp_save {
    my ( $output_text );

    $output_text = $srt_sub_edit -> get('0.0','end');

    &save_text_subtitles($output_text,"$srt_subtitles.srtrepair.tmp");

}
#-------------------------------------------------------------------------------


#======================================================================================
sub run_srtrepair {
    my( $function ) = @_;
    my( $sub_sub_file );
    my( $import_sub_file );
    my( $temp_srt_file );
    my( $srtrepair_parms );
    my( @srtrepair_err );
    my( $subtitles );
    my $some_error = 0;

    print "srtrepair called for function $function\n";

    &temp_save;
    $temp_srt_file = "subtitles.srtrepair.tmp";
    $subtitles = $srt_sub_edit -> get('0.0','end');

    if ( length($subtitles)>30 or $function==4 ) {

    $srtrepair_log -> delete( '0.0', 'end' ); 

######	check or repair subtitles
        if ( $function == 1 ) {

#   	    &temp_save;
    	    $srtrepair_parms = "";

    	    if ( $srtrepair_parm1 == 1 ) {
	
		$call_status = system("srtrepair.pl -c \"$temp_srt_file\" > \"srtrepair_log.tmp\"");
		print "srtrepair.pl -c \"$temp_srt_file\" > \"srtrepair_log.tmp\"\n";

		if ( $call_status != 0 ) {

        	    $answer = $mw -> messageBox( -title => 'srtrepair GUI warning',
	                                     -message => "Error occured while calling srtrepair. See console for error message.",
		                             -type => 'OK',
                                             -icon => 'warning'
                                    	    );

		} else {
	    
		    open ( SRTREPAIR_LOG, "srtrepair_log.tmp" );

		    $srtrepair_log -> delete( '0.0', 'end' ); 

		    while ( chomp($row=<SRTREPAIR_LOG>) ) {

			if ( $row =~ /-/ or $row =~ /!/ ) {

			    @srtrepair_err = split( /\.+/ , $row );

			    foreach $row ( @srtrepair_err ) {
				if ( $row ne "" ) {
				    $some_error = 1;
				    if ( index($row,"-")>0 ) {
					$srtrepair_log -> insert( 'end', "Timing problem between subtitles $row\n" );
				    } elsif ( index($row,"!")>0 ) {
					$srtrepair_log -> insert( 'end', "Duration problem in subtitle $row\n" );
				    } else {
					$srtrepair_log -> insert( 'end', "Some problem at $row\n" );
				    }

				}

			    }

			}

		    }

		    if ( $some_error == 0 ) { $srtrepair_log -> insert( 'end', "No timing problem found.\n" ); }

		    close(SRTREPAIR_LOG);

		}

	    } elsif ( $srtrepair_parm1 == 2 ) {

		$srtrepair_parms = "-r ";

		if ( $srtrepair_parm2 == 1 ) { $srtrepair_parms .= "-n "; } 
		if ( $srtrepair_parm3 == 1 ) { $srtrepair_parms .= "-e "; } 
		if ( $srtrepair_parm4 == 1 ) {
		    $srtrepair_parms .= "-g ";
		    if ( $srtrepair_parm5 == 1 ) { $srtrepair_parms .= "1 "; }
		    if ( $srtrepair_parm5 == 2 ) { $srtrepair_parms .= "2 "; }
		}

		print "srtrepair.pl $srtrepair_parms -o \"$temp_srt_file.repaired.tmp\" \"$temp_srt_file\" > \"srtrepair_log.tmp\"\n";
		$call_status = system("srtrepair.pl $srtrepair_parms -o \"$temp_srt_file.repaired.tmp\" \"$temp_srt_file\" > \"srtrepair_log.tmp\"");

		if ( $call_status != 0 ) {

        	    $answer = $mw -> messageBox( -title => 'srtrepair GUI warning',
	                                     -message => "Error occured while calling srtrepair. See console for error message.",
		                             -type => 'OK',
                                             -icon => 'warning'
                                    	    );

		} else {

		    open ( REPAIRED, "$temp_srt_file.repaired.tmp" );

		    $srt_sub_edit -> delete( '0.0', 'end' ); 

	    	    while ( chomp($row=<REPAIRED>) ) {
			$srt_sub_edit -> insert( 'end', "$row\n" );
		    }

		    close(REPAIRED);

		    open ( SRTREPAIR_LOG, "srtrepair_log.tmp" );

		    $srtrepair_log -> delete( '0.0', 'end' ); 

		    while ( chomp($row=<SRTREPAIR_LOG>) ) {

			if ( $row =~ /-/ or $row =~ /!/ ) {

			    @srtrepair_err = split( /\.+/ , $row );
			    foreach $row ( @srtrepair_err ) {
				if ( $row ne "" ) {
				    $some_error = 1;
				    $srtrepair_log -> insert( 'end', "Unrepaired timing problem at $row\n" );
				}

			    }

			}

		    }

		    close(SRTREPAIR_LOG);

		    if ( $some_error == 0 ) { $srtrepair_log -> insert( 'end', "No timing problem left.\n" ); }

		}

	        if ( -f "$temp_srt_file.repaired.tmp" ) { unlink("$temp_srt_file.repaired.tmp"); }

	    }

	}

######	time/speed shift
	if ( $function == 2 and ( $srtrepair_parm6 != 3 or $srtrepair_parm8 != 3 ) ) {

	    $srtrepair_parms = "";
	    if ( $srtrepair_parm6 == 1 ) { $srtrepair_parms .= "-s "; }  #shift forward
	    if ( $srtrepair_parm6 == 2 ) { $srtrepair_parms .= "-s -"; } #shift backward
	    if ( $srtrepair_parm6 == 1 or $srtrepair_parm6 == 2 ) {
		$srtrepair_parms .= $shift_h.":".$shift_m.":".$shift_s;
	    }
	    if ( $srtrepair_parm7 == 1 ) { $srtrepair_parms .= " -f"; }  #force time shift
	    if ( $srtrepair_parm8 == 1 ) { $srtrepair_parms .= " -m -"; }  #slow down
	    if ( $srtrepair_parm8 == 2 ) { $srtrepair_parms .= " -m "; }  #speed up
	    if ( $srtrepair_parm8 == 1 or $srtrepair_parm8 == 2 ) {
		$srtrepair_parms .= $enter_shift_speed -> get();
	    }
	    if ( $srtrepair_parm9 == 1 ) { $srtrepair_parms .= " -n"; }  #force time shift

	    print "srtrepair.pl $srtrepair_parms -o \"$temp_srt_file.shifted.tmp\" \"$temp_srt_file\" > \"srtrepair_log.tmp\"\n";
	    $call_status = system("srtrepair.pl $srtrepair_parms -o \"$temp_srt_file.shifted.tmp\" \"$temp_srt_file\" > \"srtrepair_log.tmp\"");

	    if ( $call_status != 0 ) {

		    open ( SRTREPAIR_LOG, "srtrepair_log.tmp" );
		    chomp($row=<SRTREPAIR_LOG>);
		    close(SRTREPAIR_LOG);
		    if ( $row =~ /!!!/ ) {

        		$answer = $mw -> messageBox( -title => 'srtrepair GUI warning',
	                                     -message => "Chosen shift would cause negative timing. Use Force option to override this warning.",
		                             -type => 'OK',
                                             -icon => 'warning'
                                    	    );

		    } else {

        		$answer = $mw -> messageBox( -title => 'srtrepair GUI warning',
	                                     -message => "Error occured while calling srtrepair. See console for error message.",
		                             -type => 'OK',
                                             -icon => 'warning'
                                    	    );

		    }

	    } else {

		open ( SHIFTED, "$temp_srt_file.shifted.tmp" );

		$srt_sub_edit -> delete( '0.0', 'end' ); 

	    	while ( chomp($row=<SHIFTED>) ) {
		    $srt_sub_edit -> insert( 'end', "$row\n" );
		}

    		close(SHIFTED);

		open ( SRTREPAIR_LOG, "srtrepair_log.tmp" );
		chomp($row=<SRTREPAIR_LOG>);
		close(SRTREPAIR_LOG);
		if ( $row =~ /first_part/ ) {

        	    $answer = $mw -> messageBox( -title => 'srtrepair GUI notification',
	                                     -message => "File *.first_part containing potentialy negative subtitles have been created.",
		                             -type => 'OK',
                                             -icon => 'warning'
                                    	    );

		}

	    }

	    if ( -f "$temp_srt_file.shifted.tmp" ) { unlink("$temp_srt_file.shifted.tmp"); }

	}

######	export into SUB
	if ( $function == 3 ) {

	    if ( $txt_sub_file ne "" ) { ($sub_sub_file) = $txt_sub_file =~ /.*\/(.*)\.srt/; }
	    else { ($sub_sub_file) = $srt_sub_file =~ /.*\/(.*)\.srt/; }
	    $sub_sub_file .= ".sub";

    	    $sub_sub_file = $mw -> getSaveFile( -title => 'Save subtitles in SUB format',
					  -defaultextension => '.sub',
					  -filetypes => [ ['SUB subtitles files',['.sub']],
							  ['All Files','*']
							],
					  -initialfile => $sub_sub_file,
					  -initialdir => $srt_sub_folder
				        );

	    if ( $sub_sub_file ne "" ) {

    		$output_text = $srt_sub_edit -> get('0.0','end');

		&save_text_subtitles($output_text,"$sub_sub_file.srtrepair.tmp");

		print"srtrepair.pl -t $srtrepair_fps -o \"$sub_sub_file\" \"$sub_sub_file.srtrepair.tmp\"";
		$call_status = system("srtrepair.pl -t $srtrepair_fps -o \"$sub_sub_file\" \"$sub_sub_file.srtrepair.tmp\"");

		if ( $call_status != 0 ) {

        	    $answer = $mw -> messageBox( -title => 'srtrepair GUI warning',
	                                     -message => "Error occured while calling srtrepair. See console for error message.",
		                             -type => 'OK',
                                             -icon => 'warning'
                                    	    );

		} else {
	    
		    if ( $recode_parm != 2 ) {

			if ( $recode_parm == 1 ) {
    			    print"recode cp1250..iso-8859-2 \"$sub_sub_file\"\n";
			    $call_status = system( "recode cp1250..iso-8859-2 \"$sub_sub_file\"" );
			} elsif ( $recode_parm == 3 ) {
    			    print"recode cp1250..iso-8859-1 \"$sub_sub_file\"\n";
			    $call_status = system( "recode cp1250..iso-8859-1 \"$sub_sub_file\"" );
			}

			if ( $call_status != 0 ) {

        		    $answer = $mw -> messageBox( -title => 'srtrepair GUI warning',
                                    		     -message => "Error while calling RECODE.EXE. See console for error message.",
                                    	             -type => 'OK',
                                    	             -icon => 'warning'
                                    		    );

			}

		    }

		}

		if ( -f "$sub_sub_file.srtrepair.tmp" ) { unlink("$sub_sub_file.srtrepair.tmp"); }

	    }

	}

######	import from SUB
	if ( $function == 4 ) {

	    $sub_sub_file = $mw -> getOpenFile( -title => 'Import SUB text subtitles file',
						-initialdir => $open_dir,
						-filetypes => [ 
								[ 'SUB subtitles files','.sub' ],
								[ 'All Files','*' ],
						    	      ]
						);

	    $import_sub_file = $sub_sub_file;

	    if ( $sub_sub_file ne "" ) {

		if ( $recode_parm != 2 ) {

		    $import_sub_file .= ".srtrepair.tmp";

		    if ( $recode_parm == 1 ) {
    			print"recode iso-8859-2..cp1250 < \"$sub_sub_file\" > \"$import_sub_file\"\n";
			$call_status = system( "recode iso-8859-2..cp1250 < \"$sub_sub_file\" > \"$import_sub_file\"" );
		    } elsif ( $recode_parm == 3 ) {
    			print"recode iso-8859-1..cp1250 < \"$sub_sub_file\" > \"$import_sub_file\"\n";
			$call_status = system( "recode iso-8859-1..cp1250 < \"$sub_sub_file\" > \"$import_sub_file\"" );
		    }


		    if ( $call_status != 0 ) {

        	    $answer = $mw -> messageBox( -title => 'srtrepair GUI warning',
                            		     -message => "Error while calling RECODE.EXE. See console for error message.",
                            	             -type => 'OK',
                            	             -icon => 'warning'
                            		    );

		    }

		}

		print"srtrepair.pl -i $srtrepair_fps -o \"$import_sub_file.srtrepair.tmp2\" \"$sub_sub_file\"\n";
		$call_status = system("srtrepair.pl -i $srtrepair_fps -o \"$import_sub_file.srtrepair.tmp2\" \"$import_sub_file\"");

		if ( $call_status != 0 ) {

        	    $answer = $mw -> messageBox( -title => 'srtrepair GUI warning',
	                                     -message => "Error occured while calling srtrepair. See console for error message.",
		                             -type => 'OK',
                                             -icon => 'warning'
                                    	    );

		} else {

		    open( SUB_SUBS,"$import_sub_file.srtrepair.tmp2" );

		    $srt_sub_edit -> delete( '0.0', 'end' ); 

	    	    while ( chomp($row=<SUB_SUBS>) ) {
			$srt_sub_edit -> insert( 'end', "$row\n" );
		    }

		    close(SUB_SUBS);

		}

		if ( -f "$import_sub_file.srtrepair.tmp2" ) { unlink("$import_sub_file.srtrepair.tmp2"); }
		if ( -f "$sub_sub_file.srtrepair.tmp" ) { unlink("$sub_sub_file.srtrepair.tmp"); }

	    }

	}

######	import timing from external file, option -l
	if ( $function == 5 ) {

	    $import_sub_file = $mw -> getOpenFile( -title => 'Import timing from SRT file...',
						-initialdir => $open_dir,
						-filetypes => [ 
								[ 'SRT subtitles files',[ '.srt','.srtx' ] ],
								[ 'All Files','*' ],
						    	      ]
						);

	    if ( $import_sub_file ne "" ) {

		if ( $recode_parm != 2 ) {

		    if ( $recode_parm == 1 ) {
    			print"recode iso-8859-2..cp1250 < \"$import_sub_file\" > \"timing.CP1250.tmp\"\n";
			$call_status = system( "recode iso-8859-2..cp1250 < \"$import_sub_file\" > \"timing.CP1250.tmp\"" );
		    } elsif ( $recode_parm == 3 ) {
    			print"recode iso-8859-1..cp1250 < \"$import_sub_file\" > \"timing.CP1250.tmp\"";
			$call_status = system( "recode iso-8859-1..cp1250 < \"$import_sub_file\" > \"timing.CP1250.tmp\"" );
		    }


		    if ( $call_status == 0 ) {

			$import_sub_file = "timing.CP1250.tmp";

		    } else {

        		$answer = $mw -> messageBox( -title => 'srtrepair GUI warning',
                            		     -message => "Error while calling RECODE.EXE. See console for error message.",
                            	             -type => 'OK',
                            	             -icon => 'warning'
                            		    );

		    }

		}

		print"srtrepair.pl -o \"timing_imported.tmp\" -l \"$import_sub_file\" \"$temp_srt_file\"\n";
		$call_status = system("srtrepair.pl -o \"timing_imported.tmp\" -l \"$import_sub_file\" \"$temp_srt_file\"");

		if ( $call_status != 0 ) {

        	    $answer = $mw -> messageBox( -title => 'srtrepair GUI warning',
	                                     -message => "Error occured while calling srtrepair. See console for error message.",
		                             -type => 'OK',
                                             -icon => 'warning'
                                    	    );

		} else {

		    open( SUB_SUBS,"timing_imported.tmp" );

		    $srt_sub_edit -> delete( '0.0', 'end' ); 

	    	    while ( chomp($row=<SUB_SUBS>) ) {
			$srt_sub_edit -> insert( 'end', "$row\n" );
		    }

		    close(SUB_SUBS);

		}

	        if ( -f "timing_imported.tmp") { unlink("timing_imported.tmp"); };
    		if ( -f "timing.CP1250.tmp") { unlink("timing.CP1250.tmp"); };

	    }

	}

    } else {

        $answer = $mw -> messageBox( -title => 'srtrepair GUI warning',
	                             -message => "Nothing to pass to srtrepair.",
		                     -type => 'OK',
                                     -icon => 'warning'
                                    );
	print"Nothing to pass to srtrepair.\n";

    }

    if ( -f "subtitles.srtrepair.tmp") { unlink("subtitles.srtrepair.tmp"); };
    if ( -f "srtrepair_log.tmp") { unlink("srtrepair_log.tmp"); };

}
#-------------------------------------------------------------------------------


#======================================================================================
sub saveas_txt_subs {
my ( $txt_sub_file_old );

    $txt_sub_file_old = $txt_sub_file;

    ($srt_sub_file) = $txt_sub_file =~ /.*\\([^\\].*)/;

    $txt_sub_file = $mw -> getSaveFile( -title => 'Save SRT(TXT) subtitles as',
					  -defaultextension => '.srt',
					  -filetypes => [ ['SRT subtitles files',['.srt','.srtx']],
							  ['All Files','*']
							],
					  -initialfile => $srt_sub_file,
					  -initialdir => $srt_sub_folder
				        );

    if ( $txt_sub_file ne "" ) {

	print "Saving subtitles in saveas_txt_subs procedure\n";
	&save_txt_subs;

    } else { $txt_sub_file = $txt_sub_file_old; }

}
#----------------------------------------------------------------------------------------------------------


#======================================================================================
sub save_txt_subs {

    print "$txt_sub_file\n";

    if ( $txt_sub_file ne "" ) {

        $output_text = $srt_sub_edit -> get('0.0','end');

	&save_text_subtitles($output_text,$txt_sub_file);

	if ( $recode_parm != 2 ) {
    
	    if ( $recode_parm == 1 ) {
    		print"recode cp1250..iso-8859-2 \"$txt_sub_file\"\n";
		$call_status = system( "recode cp1250..iso-8859-2 \"$txt_sub_file\"" );
	    } elsif ( $recode_parm == 3 ) {
    		print"recode cp1250..iso-8859-1 \"$txt_sub_file\"\n";
		$call_status = system( "recode cp1250..iso-8859-1 \"$txt_sub_file\"" );
	    }
	
	    if ( $call_status != 0 ) {

        	$answer = $mw -> messageBox( -title => 'srtrepair GUI warning',
                                    	     -message => "Error while calling RECODE.EXE. See console for error message.",
                                    	     -type => 'OK',
                                    	     -icon => 'warning'
                                      );

	    }

	}

    } else {

	&saveas_txt_subs;
	
    }

}
#----------------------------------------------------------------------------------------------------------


#===============================================================================
sub save_subtitles {

	$output_text = $txt_sub_view -> get('0.0','end');

	&save_text_subtitles($output_text,$txt_sub_file);

}
#-------------------------------------------------------------------------------


#===============================================================================
# saves subtitles and ensure to be in ISO-2 encoded
sub save_text_subtitles {
my ($save_this,$file) = @_;

	open(OUTPUT, ">$file");
	print OUTPUT "$save_this";
	close(OUTPUT);


#  IF WRITING DIRECTLY TO CP-1250 THEN NO NEED OF UTF8 TO CP1250 CONVERSION

#	# RECODE.EXE -port from Linux- can't handle UTF-8 + CR-LF encoded text, so two recode steps must be done
#
#  	$call_status = system("recode cr-lf..cr \"$file\"");
#
#	if ( $call_status != 0 ) {
#
#        	$answer = $mw -> messageBox( -title => 'srtrepair-gui warning',
#                                    	     -message => "Error while calling RECODE.EXE. See console for error message.\nThe subtitles maybe left in UTF-8 CR-LF.",
#                                    	     -type => 'OK',
#                                    	     -icon => 'warning'
#                                           );
#
#	} else {
#
#	    $call_status = system("recode UTF-8..cp1250 \"$file\"");
#  	    $call_status = system("recode cr..cr-lf \"$file\"");
#
#	    if ( $call_status != 0 ) {
#
#        	$answer = $mw -> messageBox( -title => 'srtrepair-gui warning',
#                                    	     -message => "Error while calling RECODE.EXE. See console for error message.\nThe subtitles maybe left in CR only or UTF-8 CR only.",
#                                    	     -type => 'OK',
#                                    	     -icon => 'warning'
#                                           );
#
#
#	    }
#
#	}


}
#-------------------------------------------------------------------------------





#======================================================================================
sub load_txt_subs {
my ( $txt_sub_file_old, $txt_sub_file2 );

    $txt_sub_file_old = $txt_sub_file;

    $txt_sub_file = $mw -> getOpenFile( -title => 'Open SRT text subtitles file',
					  -filetypes => [ 
							  ['SRT subtitles files',['.srt','.srtx']],
							  [ 'All Files','*' ]
						        ]
					);

    if ( $txt_sub_file ne "" ) {

	if ( $recode_parm != 2 ) {
    
	    $txt_sub_file2 = $txt_sub_file.".CP1250.tmp";

	    if ( $recode_parm == 1 ) {
    		print"recode iso-8859-2..cp1250 < \"$txt_sub_file\" > \"$txt_sub_file2\"\n";
		$call_status = system( "recode iso-8859-2..cp1250 < \"$txt_sub_file\" > \"$txt_sub_file2\"" );
	    } elsif ( $recode_parm == 3 ) {
    		print"recode iso-8859-1..cp1250 < \"$txt_sub_file\" > \"$txt_sub_file2\"\n";
		$call_status = system( "recode iso-8859-1..cp1250 < \"$txt_sub_file\" > \"$txt_sub_file2\"" );
	    }
	    
	    if ( $call_status != 0 ) {

       		$answer = $mw -> messageBox( -title => 'srtrepair GUI warning',
                                        -message => "RECODE.EXE not found or wrong encoding selected. See console for error message.\nOpening subtitles in default encoding.",
                                        -type => 'OK',
                                        -icon => 'warning'
                                      );

		#recode did not found or suceeded so open the original file without recoding
	    	open ( SRT_SUBS, $txt_sub_file );


	    } else {

		open ( SRT_SUBS, "$txt_sub_file2" );

	    }



	} else {

	    open ( SRT_SUBS, $txt_sub_file );

	}


	$srt_sub_edit -> delete( '0.0', 'end' ); 
	$srtrepair_log -> delete( '0.0', 'end' ); 

	while ( chomp($row=<SRT_SUBS>) ) {

	    $srt_sub_edit -> insert( 'end', "$row\n" );

	}

	close(SRT_SUBS);

    }

    if ( $txt_sub_file eq "" ) { $txt_sub_file = $txt_sub_file_old; }

    if ( -f "$txt_sub_file2" ) { unlink "$txt_sub_file2"; };

}
#----------------------------------------------------------------------------------------------------------


#======================================================================================
# This code is not mine - copied from vptk_w.pl by XXX and slightly modified:
# Additionaly that code is partially copied from original NumEntry
# Reason: the original widget does not support -textvariable (sic!)
# Problems: No strict syntax control, No FireButton functionality

sub NumEntry {

my ($parent,%par)=@_;
my $numentry;
my $minvalue=delete $par{'-minvalue'};
my $maxvalue=delete $par{'-maxvalue'};

    unless($def_bitmaps) {
	my $bits = pack("b8"x5,
			"........",
			"...11...",
			"..1111..",
			".111111.",
			"........"
			);

	$mw->DefineBitmap('INCBITMAP' => 8,5, $bits);

        # And of course, decrement is the reverse of increment :-)
        $mw->DefineBitmap('DECBITMAP' => 8,5, scalar reverse $bits);
	$def_bitmaps=1;
    }

    my $result=$parent->Frame();

    if ( $par{'-width'} > 0 ) {

	$numentry=$result->Entry(%par)->pack(-anchor=>'w', -side=>'left');
        $numentry->bind('<Up>',
	    [\&inc_num_controlled,$par{'-textvariable'},1,$minvalue,$maxvalue]);
        $numentry->bind('<Down>',
	    [\&inc_num_controlled,$par{'-textvariable'},-1,$minvalue,$maxvalue]);

    }

    $result->Button(-bitmap=>'INCBITMAP',-cursor=>'left_ptr',-command=>
	[\&inc_num_controlled,$par{'-textvariable'},1,$minvalue,$maxvalue])
	->pack(-anchor=>'nw', -side=>'top');
    $result->Button(-bitmap=>'DECBITMAP',-cursor=>'left_ptr',-command=>
	[\&inc_num_controlled,$par{'-textvariable'},-1,$minvalue,$maxvalue])
        ->pack(-anchor=>'nw', -side=>'top');
      return $result;

}

sub inc_num_controlled {

    shift if ref($_[0]) ne 'SCALAR';
    my ($ptr,$inc,$minvalue,$maxvalue)=@_;

    my $value=$$ptr+$inc;
    $$ptr=$value;
    $$ptr=$minvalue if length $minvalue && $value<$minvalue;
    $$ptr=$maxvalue if length $maxvalue && $value>$maxvalue;

}
#-----------------------------------------------------------------------------------------------

