#!/usr/bin/perl

use Tk;
use Tk::ErrorDialog;
use Tk::DialogBox;
use Tk::Clipboard;
use Tk::Balloon;
use File::Basename;
use Getopt::Std;
#use FindBin;

$libpath="/usr/local/lib/guitartex";

# load configuration file
$home=$ENV{"HOME"};
do "$home/.guitartexrc" or die "cannot load guitartex.conf";

# load subroutines
foreach $file (
	"sub_gui.pl",			#perl/tk gui, synatax highlighting, check for f-keys
	"sub_menu_file.pl",		#file menu
	"sub_menu_edit.pl",		#edit menu
	"sub_menu_colors.pl",		#colors menu
	"sub_menu_transpose.pl",	#transpose menu
	"sub_menu_help.pl",		#help menu
	){
	unless ($return = do "$libpath/$file") { warn "parsing $file failed: $@" if $@ }
}

#load language file
do "$libpath/language/$language.pl" or die "cannot load file language/$language.pl\n";

gui();

#--------------------------------------------------------------------------------
# subroutine gui
#
# setup the graphical user interface
#--------------------------------------------------------------------------------
sub gui {
	#create main window
	$mw = MainWindow->new;
	$mw -> title ("GuitarTeX");

	#create editor in $t
	$t = $mw -> Scrolled ( "Text", -background => 'white',
		-relief => 'flat', -wrap => 'none',
		-scrollbars => 'se', -exportselection => '0' );

	#call subroutine check_key if any key is pressed (to handle F5, F6 ...)
	$t -> bind ( "<Key>", [\&check_key, Ev('k')] );

	#create a frame for the menu bar
	$menu_frame = $mw -> Frame -> pack ( -side => 'top', -fill => 'x');

	#create the file menu
	$menu_file = $menu_frame -> Menubutton (-textvariable => \$name_menu_file,
		-menuitems => [
			['command' => $name_menu_new, -command => \&menu_file_new],
			['command' => $name_menu_open, -command => \&menu_file_open],
			"-",
			['command' => $name_menu_save, -command => \&menu_file_save],
			['command' => $name_menu_saveas, -command => \&menu_file_saveas],
			"-",
			[cascade => $name_menu_export, -menuitems => [
				['command' => $name_menu_latex, -command => \&export_latex],
				['command' => $name_menu_postscript, -command => \&export_postscript],
				['command' => $name_menu_pdf, -command => \&export_pdf],
				],
			],
			"-",
			['command' => $name_menu_quit, -command => \&menu_file_quit],
		]
	)->pack (-side => 'left', -anchor => 'w');

	#create the edit menu
	$menu_edit = $menu_frame -> Menubutton (-textvariable => \$name_menu_edit,
		-menuitems => [
			['command' => $name_menu_paste1, -command => \&menu_edit_paste],
			"-",
			['command' => $name_menu_insert, -command => \&menu_edit_insert],
			['command' => $name_menu_crd, -command => \&menu_edit_crd2chopro, -accelerator => "F9"],
			"-",
			['command' => $name_menu_cut, -state => 'disabled'],
			['command' => $name_menu_copy, -state => 'disabled'],
			['command' => $name_menu_paste2, -state => 'disabled'],
		]
	)->pack (-side => 'left', -anchor => 'w');

	#create the directives menu
	$menu_directives = $menu_frame -> Menubutton (-textvariable => \$name_menu_directives,
		-menuitems => [
			['command' => $name_menu_startchorus, -command =>sub{$t->insert("insert linestart","{soc}\n", 'directive')}],
			['command' => $name_menu_endchorus, -command =>sub{$t->insert("insert linestart","{eoc}\n", 'directive')}],
			"-",
			['command' => $name_menu_startbridge, -command => sub{$t->insert("insert linestart","{sob}\n", 'directive')}],
			['command' => $name_menu_endbridge, -command => sub{$t->insert("insert linestart","{eob}\n", 'directive')}],
			"-",
			['command' => $name_menu_starttab, -command => sub{$t->insert("insert linestart","{sot}\n", 'directive')}],
			['command' => $name_menu_endtab, -command => sub{$t->insert("insert linestart","{eot}\n", 'directive')}],
			"-",
			['command' => $name_menu_startinstr, -command => sub{$t->insert("insert linestart","{soi}\n", 'directive')}],
			['command' => $name_menu_endinstr, -command => sub{$t->insert("insert linestart","{eoi}\n", 'directive')}],
			"-",
			['command' => $name_menu_guitartab, -command => sub{$t->insert("insert linestart","{guitartab:}\n", 'directive')}],
			['command' => $name_menu_basstab, -command => sub{$t->insert("insert linestart","{basstab:}\n", 'directive')}],
			"-",
			['command' => $name_menu_title, -command => sub{$t->insert("insert linestart","{t:", 'directive'); $t->insert("insert lineend","}\n", 'directive');}],
			['command' => $name_menu_subtitle, -command => sub{$t->insert("insert linestart","{st:", 'directive'); $t->insert("insert lineend","}\n", 'directive');}],
			['command' => $name_menu_newpage, -command => sub{$t->insert("insert linestart","{np}\n", 'directive')}],
			['command' => $name_menu_comment, -command => sub{$t->insert("insert linestart","{c:", 'directive'); $t->insert("insert lineend","}\n", 'directive');}],
			['command' => $name_menu_margin, -command => sub{$t->insert("insert linestart","{m:", 'directive'); $t->insert("insert lineend","}\n", 'directive');}],
			['command' => $name_menu_second, -command => sub{$t->insert("insert linestart","{2:", 'directive'); $t->insert("insert lineend","}\n", 'directive');}],
		]
	)->pack (-side => 'left', -anchor => 'w');

	#create the songbook menu
	$menu_songbook = $menu_frame -> Menubutton (-textvariable => \$name_menu_songbook,
		-menuitems => [
			['command' => $name_menu_book, -command => sub{$t->insert("insert","{document_class:book}\n", 'directive')}],
			['command' => $name_menu_booktitle, -command => sub{ $t->insert("insert linestart","{book_title:", 'directive'); $t->insert("insert lineend","}\n", 'directive');}],
			['command' => $name_menu_bookauthor, -command => sub{ $t->insert("insert linestart","{book_author:", 'directive'); $t->insert("insert lineend","}\n", 'directive');}],
			['command' => $name_menu_bookdate, -command => sub{ $t->insert("insert linestart","{book_date:", 'directive'); $t->insert("insert lineend","}\n", 'directive');}],
			['command' => $name_menu_chapter, -command => sub{ $t->insert("insert linestart","{chapter:", 'directive'); $t->insert("insert lineend","}\n", 'directive');}],
			['command' => $name_menu_include, -command => sub{ $t->insert("insert linestart","{include:", 'directive'); $t->insert("insert lineend","}\n", 'directive');}],
			['command' => $name_menu_even, -command => sub{$t->insert("insert linestart","{even}\n", 'directive')}],
		]
	)->pack (-side => 'left', -anchor => 'w');

	#create the colors menu
	$menu_colors = $menu_frame -> Menubutton (-textvariable => \$name_menu_color,
		-menuitems => [
			['command' => $name_menu_colorchorus,	-command => \&colors_chorus],
			['command' => $name_menu_colorbridge, -command => \&colors_bridge],
			['command' => $name_menu_colortab, -command => \&colors_tab],
			['command' => $name_menu_colorinstr, -command => \&colors_instr],
			['command' => $name_menu_second, -command => \&colors_second],
			['command' => $name_menu_secondback, -command => \&colors_second_back],
		]
	)->pack (-side => 'left', -anchor => 'w');

	#create the transpose menu
	$menu_transpose = $menu_frame -> Menubutton (-textvariable => \$name_menu_transpose,
		-menuitems => [
			['command' => $name_menu_transup, -command => \&transpose_up, -accelerator => "F5"],
			['command' => $name_menu_transdown, -command => \&transpose_down, -accelerator => "F6"],
			"-",
			['command' => $name_menu_transsharp, -command => \&transpose_flat2sharp, -accelerator => "F7"],
			['command' => $name_menu_transflat, -command => \&transpose_sharp2flat, -accelerator => "F8"],
			"-",
			['command' => $name_menu_transgerman, -command => \&transpose_b2h],
			['command' => $name_menu_transinternational, -command => \&transpose_h2b],
		]
	)->pack (-side => 'left', -anchor => 'w');

	#create the help menu
	$menu_help = $menu_frame -> Menubutton (-textvariable => \$name_menu_help, -tearoff => '0', -menuitems => [
			['command' => $name_menu_help, -command => \&documentation],
			['command' => "$name_menu_about GuitarTeX", -command => \&about],
		]
	)->pack (-side => 'right');

	#create a frame for the icons
	$icon_frame0 = $mw -> Frame ( -relief => "flat", -borderwidth => 0 ) -> pack ( -side => 'top', -anchor => 'w' );
	# create file new icon
	$icon = $mw -> Photo ( -file => "$libpath/images/filenew.gif" );
	$icon_file_new = $icon_frame0 -> Button(-image => $icon, -relief=>'flat', -command => \&menu_file_new) -> pack(-side=>'left' );
	#create file open icon
	$icon = $mw -> Photo ( -file => "$libpath/images/fileopen.gif" );
	$icon_file_open = $icon_frame0 -> Button(-image => $icon, -relief=>'flat', -command => \&menu_file_open) ->pack(-side=>'left' );
	#create file save icon
	$icon = $mw -> Photo ( -file => "$libpath/images/filesave.gif" );
	$icon_file_save = $icon_frame0 -> Button(-image => $icon, -relief=>'flat', -command => \&menu_file_save) ->pack(-side=>'left' );
	#create export latex icon
	$icon = $mw -> Photo ( -file => "$libpath/images/tex.gif" );
	$icon_latex = $icon_frame0 -> Button(-image => $icon, -relief=>'flat', -command => \&export_latex) ->pack(-side=>'left' );
	#create export postscript icon
	$icon = $mw -> Photo ( -file => "$libpath/images/postscript.gif" );
	$icon_ps = $icon_frame0 -> Button(-image => $icon, -relief=>'flat', -command => \&export_postscript) ->pack(-side=>'left' );
	#create export pdf icon
	$icon = $mw -> Photo ( -file => "$libpath/images/pdf.gif" );
	$icon_pdf = $icon_frame0 -> Button(-image => $icon, -relief=>'flat', -command => \&export_pdf) ->pack(-side=>'left' );
	#create transpose up icon
	$icon = $mw -> Photo ( -file => "$libpath/images/up.gif" );
	$icon_transpose_up = $icon_frame0 -> Button(-image => $icon, -relief=>'flat', -command => \&transpose_up) ->pack(-side=>'left' );
	#create transpos down icon
	$icon = $mw -> Photo ( -file => "$libpath/images/down.gif" );
	$icon_transpose_down = $icon_frame0 -> Button(-image => $icon, -relief=>'flat', -command => \&transpose_down) ->pack(-side=>'left' );
	#create syntax highlighting icon
	if ( $highlight eq "yes" ) {
		$icon = $mw -> Photo ( -file => "$libpath/images/color.gif" );
		$icon_highlight = $icon_frame0 -> Button(-image => $icon, -relief=>'flat', -command => \&highlight) ->pack(-side=>'left' );
	}

	#create frame for chord icons
	$icon_frame1 = $mw -> Frame ( -relief => "flat", -borderwidth => 2 ) -> pack ( -side => 'top', -anchor => 'w' );
	#create a button for each key
	$icon_frame1 -> Label( -text=>$name_icon_chords, -width=>10 )->pack ( -side => 'left' );
	$icon_chord_c  = $icon_frame1 -> Button( -text=>"C",  -command=>sub{$t->insert("insert","[C]", 'chord')} )->pack(-side=>'left');
	$icon_chord_c2 = $icon_frame1 -> Button( -text=>"C#", -command=>sub{$t->insert("insert","[C#]",'chord')} )->pack(-side=>'left');
	$icon_chord_d  = $icon_frame1 -> Button( -text=>"D",  -command=>sub{$t->insert("insert","[D]", 'chord')} )->pack(-side=>'left');
	$icon_chord_d2 = $icon_frame1 -> Button( -text=>"D#", -command=>sub{$t->insert("insert","[D#]",'chord')} )->pack(-side=>'left');
	$icon_chord_e  = $icon_frame1 -> Button( -text=>"E",  -command=>sub{$t->insert("insert","[E]", 'chord')} )->pack(-side=>'left');
	$icon_chord_f  = $icon_frame1 -> Button( -text=>"F",  -command=>sub{$t->insert("insert","[F]", 'chord')} )->pack(-side=>'left');
	$icon_chord_f2 = $icon_frame1 -> Button( -text=>"F#", -command=>sub{$t->insert("insert","[F#]",'chord')} )->pack(-side=>'left');
	$icon_chord_g  = $icon_frame1 -> Button( -text=>"G",  -command=>sub{$t->insert("insert","[G]", 'chord')} )->pack(-side=>'left');
	$icon_chord_g2 = $icon_frame1 -> Button( -text=>"G#", -command=>sub{$t->insert("insert","[G#]",'chord')} )->pack(-side=>'left');
	$icon_chord_a  = $icon_frame1 -> Button( -text=>"A",  -command=>sub{$t->insert("insert","[A]", 'chord')} )->pack(-side=>'left');
	$icon_chord_bb = $icon_frame1 -> Button( -text=>"Bb", -command=>sub{$t->insert("insert","[Bb]",'chord')} )->pack(-side=>'left');
	$icon_chord_b  = $icon_frame1 -> Button( -text=>$name_note_B,  -command=>sub{$t->insert("insert","[B]", 'chord')} )->pack(-side=>'left');

	#create frame for tablature icons
	$tab_frame = $mw -> Frame ( -relief => "groove", -borderwidth => 0 ) -> pack ( -side => 'top', -anchor => 'w' );
	$tab_frame -> Label( -text => $name_icon_tab, -width=>10 )->pack ( -side => 'left' );
	#create button for guitar tablature
	$icon_guitartab = $tab_frame -> Button( -text=>$name_icon_guitar, -command => sub{$t->insert("insert linestart","{guitartab:}\n")}) -> pack ( -side => 'left' );
	#create button for bass tablature
	$icon_basstab   = $tab_frame -> Button( -text=>$name_icon_bass, -command => sub{$t->insert("insert linestart","{basstab:}\n")}) -> pack ( -side => 'left' );
	#create entry field for fret number
	$tab_frame -> Label( -text=>$name_icon_fret )->pack ( -side => 'left' );
	$icon_fret      = $tab_frame -> Entry( -width=>3, -relief=>'sunken', -background=>'white', -textvariable=>\$tab)->pack ( -side => 'left' );
	#create a button for each string
	$tab_frame -> Label( -text=>$name_icon_string )->pack ( -side => 'left' );
	$icon_string_E  = $tab_frame -> Button( -text=>"E", -command=>sub{$t->insert("insert","[1;$tab]");$tab=""}) -> pack ( -side => 'left' );
	$icon_string_A  = $tab_frame -> Button( -text=>"A", -command=>sub{$t->insert("insert","[2;$tab]");$tab=""}) -> pack ( -side => 'left' );
	$icon_string_D  = $tab_frame -> Button( -text=>"D", -command=>sub{$t->insert("insert","[3;$tab]");$tab=""}) -> pack ( -side => 'left' );
	$icon_string_G  = $tab_frame -> Button( -text=>"G", -command=>sub{$t->insert("insert","[4;$tab]");$tab=""}) -> pack ( -side => 'left' );
	$icon_string_B  = $tab_frame -> Button( -text=>$name_note_B, -command=>sub{$t->insert("insert","[5;$tab]");$tab=""}) -> pack ( -side => 'left' );
	$icon_string_e  = $tab_frame -> Button( -text=>"e", -command=>sub{$t->insert("insert","[6;$tab]");$tab=""}) -> pack ( -side => 'left' );

	#create status bar and connect it to $info
	$status_bar = $mw->Label(-textvariable => \$info) -> pack( -side => 'bottom', -anchor => 'w');

	#show the editor and give it the cursor focus
	$t -> pack( -fill => 'both', -expand => 1);
	$t ->focus();

	#define tags for syntax highlighting
	if ( $highlight eq "yes" ) {
		$t -> tagConfigure ('directive', -foreground => $highlight_directive_foreground, -background => $highlight_directive_background );
		$t -> tagConfigure ('comment',   -foreground => $highlight_comment_foreground,   -background => $highlight_comment_background );
		$t -> tagConfigure ('chord',     -foreground => $highlight_chord_foreground,     -background => $highlight_chord_background );
	}

	#attach tool tip balloons to icons
	if ( $tool_tips eq "yes" ){
		$balloon = $mw -> Balloon (-statusbar => $status_bar );
		$balloon -> attach ( $icon_file_new, -balloonmsg => $balloon_new );
		$balloon -> attach ( $icon_file_open, -balloonmsg => $balloon_open );
		$balloon -> attach ( $icon_file_save, -balloonmsg => $balloon_save );
		$balloon -> attach ( $icon_latex, -balloonmsg => $balloon_latex );
		$balloon -> attach ( $icon_ps, -balloonmsg => $balloon_ps );
		$balloon -> attach ( $icon_pdf, -balloonmsg => $balloon_pdf );
		$balloon -> attach ( $icon_transpose_up, -balloonmsg => $balloon_transpose_up );
		$balloon -> attach ( $icon_transpose_down, -balloonmsg => $balloon_transpose_down );
		$balloon -> attach ( $icon_chord_c, -balloonmsg => $balloon_chord );
		$balloon -> attach ( $icon_chord_c2, -balloonmsg => $balloon_chord );
		$balloon -> attach ( $icon_chord_d, -balloonmsg => $balloon_chord );
		$balloon -> attach ( $icon_chord_d2, -balloonmsg => $balloon_chord );
		$balloon -> attach ( $icon_chord_e, -balloonmsg => $balloon_chord );
		$balloon -> attach ( $icon_chord_f, -balloonmsg => $balloon_chord );
		$balloon -> attach ( $icon_chord_f2, -balloonmsg => $balloon_chord );
		$balloon -> attach ( $icon_chord_g, -balloonmsg => $balloon_chord );
		$balloon -> attach ( $icon_chord_g2, -balloonmsg => $balloon_chord );
		$balloon -> attach ( $icon_chord_a, -balloonmsg => $balloon_chord );
		$balloon -> attach ( $icon_chord_bb, -balloonmsg => $balloon_chord );
		$balloon -> attach ( $icon_chord_b, -balloonmsg => $balloon_chord );
		$balloon -> attach ( $icon_guitartab, -balloonmsg => $balloon_guitartab );
		$balloon -> attach ( $icon_basstab, -balloonmsg => $balloon_basstab );
		$balloon -> attach ( $icon_fret, -balloonmsg => $balloon_fret );
		$balloon -> attach ( $icon_string_E, -balloonmsg => $balloon_fret );
		$balloon -> attach ( $icon_string_A, -balloonmsg => $balloon_fret );
		$balloon -> attach ( $icon_string_D, -balloonmsg => $balloon_fret );
		$balloon -> attach ( $icon_string_G, -balloonmsg => $balloon_fret );
		$balloon -> attach ( $icon_string_B, -balloonmsg => $balloon_fret );
		$balloon -> attach ( $icon_string_e, -balloonmsg => $balloon_fret );
		if ( $highlight eq "yes" ) {$balloon -> attach ( $icon_highlight, -balloonmsg => $balloon_highlight )};
	}

	#start the graphical user interface
	MainLoop;
}

#--------------------------------------------------------------------------------
# subroutine check_key
#
# is called by the editor on every key stroke to check for function keys
#--------------------------------------------------------------------------------
sub check_key {
	$taste = $_[1];
	if ( $taste == 71 ) { transpose_up(); }			# F5
	if ( $taste == 72 ) { transpose_down(); }		# F6
	if ( $taste == 73 ) { transpose_flat2sharp(); }		# F7
	if ( $taste == 74 ) { transpose_sharp2flat(); }		# F8
	if ( $taste == 75 ) { menu_edit_crd2chopro(); }		# F9
}

#--------------------------------------------------------------------------------
# subroutine highlight
#
# parses the text in the editor to highlight chords and directives
# define the colors in guitartex.conf
#--------------------------------------------------------------------------------
sub highlight {
	if ( $highlight eq "yes" ) {
		$text = $t->get("1.0", "end");		#store text from the editor in variabel $text
		$t->delete("1.0","end");		#delete text in the editor
		@lines = split (/\n/, $text);		#split the text into an array of lines
		foreach $line (@lines) {
			if ( $line=~/^{/ ) {		#if the line starts with '{' it is a directive
				$t -> insert ( "end", "$line\n", 'directive' );	#insert line with directive colors
			}elsif ( $line=~/^#/ ) {	#if the line starts with '#' it is a comment
				$t -> insert ( "end", $line, 'comment' );
			}elsif ( $line=~/\[.*\]/ ){			#if the line contains chords
				@words = split (/\[/, $line);		#split the line at every chord
				foreach $word (@words) {
					@words2 = split (/\]/, $word);	#split chord and lyrics
					if ( $word =~ /\]/ ) {		#if there was a chord insert it with chord color
						$t -> insert ( "end", '[' . $words2[0] . ']', 'chord' );
					}else{				#else insert the lyrics
						$t -> insert ( "end", $words2[0] );
					}
					$t -> insert ( "end", $words2[1] );
				}
			}else{	#a lyrics line without comment, directive or chord
				$t -> insert ( "end", $line );
			} #if-elsif-else
			if ( $line!~/^{/ ) {			#if the line is not a directive
				$t -> insert ( "end", "\n" );	#append newline character
			}
		} # foreach
	} #if
}


#--------------------------------------------------------------------------------
# subroutine menu_file_new
#
# asks user to save the currend document
# shows dialog to choose template and opens template
#--------------------------------------------------------------------------------
sub menu_file_new {
	$info = "$name_menu_file $name_menu_new";		#status bar
	ask_save();						#ask if user wants to save current document
	$t->delete ("1.0", "end");				#delete current document
								#define dialog box for choosing template
	$dialog = $mw -> DialogBox ( -title => "$name_menu_new ...", -buttons => [ $name_ok ]);
	$list = $dialog->add( "Listbox" )->pack();
	$list -> insert ('end', @name_template );
	$info = $dialog->Show;					#show dialog box
	$info = $list->curselection();				#get index number of selected template
	open ( FILE, "templates/$name_template[$info]" );	#open template file
	while ( <FILE> ){ $t->insert("end", $_) }		#read template file into text variable
	close (FILE);						#close template file
	highlight();						#do syntax highlighting
	$t ->focus();						#give the cursor focus to the editor
	$filename = "";						#reset file name
}

#--------------------------------------------------------------------------------
# subroutine menu_file_open
#
# asks user to save the currend document
# shows dialog to choose file and opens file
#--------------------------------------------------------------------------------
sub menu_file_open {
	$info = "$name_menu_file $name_menu_open";		#status bar
	ask_save();						#ask if user wants to save current document
	$filename = $mw->getOpenFile ( -filetypes =>		#file dialog box
		[
			[$name_guitartex_files,	['.gtx']],
			[$name_chordpro_files,	['.chopro','.pro']],
			[$name_text_files,		['.txt', '.text']],
			[$name_all_files,        '*',             ],
		],
		-title => $name_menu_open );
	$info = $filename;					#status bar
	$t->delete("1.0","end");				#delete old text
	open ( FILE, "$filename" );				#open file
	while ( <FILE> ){ $t->insert("end", $_) }		#read file into text variable
	close (FILE);						#close file
	highlight();						#do syntax highlighting
	$t ->focus();						#give the cursor focus to the editor
}

#--------------------------------------------------------------------------------
# subroutine ask_save
#
# asks user to save the currend document
#--------------------------------------------------------------------------------
sub ask_save{
	if ( $filename eq "" ) { return }			#do nothing if file name is not defined
	$dialog = $mw->Dialog(					#define dialog box
		-buttons => [$name_yes,$name_no],
		-title => $name_menu_save,
		-text => $name_ask_save,
		);
	$info = $dialog -> Show;				#show dialog box
	if ( $info eq $name_yes ) { menu_file_save() }		#if answer is 'yes' save current document
}

#--------------------------------------------------------------------------------
# subroutine menu_file_save
#
# save current document
#--------------------------------------------------------------------------------
sub menu_file_save {
	$info = "$name_menu_file $name_menu_save";		#status bar
	if ( $filename ){					#if file name is defined, save document
		open ( FILE, ">$filename" ) or die "cannot open file $filename\n";
		$text = $t->get("1.0", "end");
		chomp $text;
		print FILE $text;
		close (FILE);
		$info = $filename;
	}else{							#else show 'save as...' dialog box
		menu_file_saveas();
	}
}

#--------------------------------------------------------------------------------
# subroutine menu_file_saveas
#
# save current document with a new name
#--------------------------------------------------------------------------------
sub menu_file_saveas {
	$info = "$name_menu_file $name_menu_saveas";		#status bar
	$filename = $mw->getSaveFile ( -filetypes =>		#define and show dialog box
		[
			[$name_guitartex_files,	['.gtx']],
			[$name_chordpro_files,	['.chopro','.pro']],
			[$name_text_files,		['.txt', '.text']],
			[$name_all_files,        '*',             ],
		],
		-title => $name_menu_saveas );
	$info = $filename;					#status bar
	menu_file_save();					#save file with given name
}


#--------------------------------------------------------------------------------
# subroutine menu_file_quit
#
# exit the program
#--------------------------------------------------------------------------------
sub menu_file_quit {
	ask_save();						#ask if user wants to save current document
	exit;							#quit
}

#--------------------------------------------------------------------------------
# subroutine export_latex
#
# export the current document in LaTeX format
#--------------------------------------------------------------------------------
sub export_latex{
	menu_file_save();
	($name, $dir, $ext) = fileparse ($filename, '\..*');
	chdir $dir;
	system ( "gtx2tex $name$ext" );
	if ( $text_viewer ne "" ) {system ( "$text_viewer \"$name.tex\" &" )}
	$info = $name_tex_ready;
}

#--------------------------------------------------------------------------------
# subroutine export_postscript
#
# export the current document in postscript format
#--------------------------------------------------------------------------------
sub export_postscript{
	menu_file_save();
	($name, $dir, $ext) = fileparse ($filename, '\..*');
	chdir $dir;
	system ( "gtx2tex --output=ps $name$ext" );
	if ( $ps_viewer ne "" ) {system ( "$ps_viewer \"$name.ps\" &" )}
	$info = $name_ps_ready;
}

#--------------------------------------------------------------------------------
# subroutine export_pdf
#
# export the current document in pdf format
#--------------------------------------------------------------------------------
sub export_pdf{
	menu_file_save();
	($name, $dir, $ext) = fileparse ($filename, '\..*');
	chdir $dir;
	system ( "gtx2tex --output=pdf $name$ext" );
	if ( $pdf_viewer ne "" ) {system ( "$pdf_viewer \"$name.pdf\" &" )}
	$info = $name_pdf_ready;
}


#--------------------------------------------------------------------------------
# subroutine menu_edit_paste
#
# insert text from clipboard
#--------------------------------------------------------------------------------
sub menu_edit_paste {
	$info = $name_menu_paste1;
	$text = $mw -> SelectionGet();
	$t -> insert("insert", $text )
}

#--------------------------------------------------------------------------------
# subroutine menu_edit_insert
#
# insert text from a file
#--------------------------------------------------------------------------------
sub menu_edit_insert {
	$info = "$name_menu_edit $name_menu_insert";			#status bar
	$insert_filename = $mw->getOpenFile ( -filetypes =>		#open file dialog
		[
			[$name_guitartex_files,	['.gtx']],
			[$name_chordpro_files,	['.chopro','.pro']],
			[$name_text_files,		['.txt', '.text']],
			[$name_all_files,        '*',             ],
		],
		-title => $name_menu_insert,
		-initialdir => "/home/" );
	$info = $insert_filename;					#status bar
	open ( FILE, "$insert_filename" );				#open chosen file
	while ( <FILE> ){ $t->insert("insert", $_); }			#insert chosen file
	close (FILE);							#close file
}

#--------------------------------------------------------------------------------
# subroutine menu_editcrd2chopro
#
# convert lines from crd to chordpro format
#--------------------------------------------------------------------------------
sub menu_edit_crd2chopro {
	$info = "$name_menu_edit $name_menu_crd";				#status bar
	$chord = $t -> get ("insert linestart", "insert lineend" );		#save the current line in variable $chord
	$t -> delete ( "insert linestart", "insert lineend + 1 char" );		#delete the current line
	$lyric = $t -> get ("insert linestart", "insert lineend" );		#save the next line in variable $lyric
	$t -> delete ( "insert linestart", "insert lineend" );			#delete the lyric line

	if ( length($lyric) < length ($chord) ) {				#adjust the length of chord and lyric
		$lyric .= " " x ( length ($chord) - length ($lyric) +1 );	#line by adding spaces to the
		$chord .= " ";							#shorter line
	}else{
		$chord .= " " x ( length ($lyric) - length ($chord) +1 );
		$lyric .= " ";
	}

	$chopro="";								#initialize variable for the resulting line
	for ( $i=0; $i<length($lyric); $i++ ){					#look at each character in chord line
		if ( substr ($chord, $i, 1) eq " " ){				#if it is a space character
			$chopro .= substr ($lyric, $i, 1);				#save the lyrics character beneath it in the chordpro line
		}else{								#else
			$chopro .= "[";							#start chord symbol with '['
			$chordlen = 0;							#initialize length of the chord
			while ( substr ($chord, $i+$chordlen, 1) ne " " ){		#while chord length
				$chopro .= substr ($chord, $i+$chordlen, 1);		#add chord
				$chordlen++;						#increment chord length
			}
                        $chopro .= "]";							#finish chord symbol with ']'
			for ( $j = 0; $j <= $chordlen; $j++ ){
				$chopro .= substr ($lyric, $i+$j, 1);			#fill in lyrics
			}
			$i = $i + $chordlen;						#correct pointer
		}
	}
	chop $chopro;
	$t -> insert ("insert", $chopro);					#insert new chordpro line
	$t -> delete ("insert");
	$t -> insert ("insert", "\n");

}


#--------------------------------------------------------------------------------
# subroutine calc_color
#
# convert the result of color dialog into LaTeX color format
#--------------------------------------------------------------------------------
sub calc_color{
	$red = int(hex(substr($info,1,4))/655.35)/100;
	$green = int(hex(substr($info,5,4))/655.35)/100;
	$blue = int(hex(substr($info,9,4))/655.35)/100;
	$info = "red $red, green $green, blue $blue";
}

#--------------------------------------------------------------------------------
# subroutine color_chorus
#
# search the document for a chorus color directive
# if it exists, change the chosen color value
# if it doesn't exist, add a new chorus color directive with the chosen color value
#--------------------------------------------------------------------------------
sub colors_chorus{
	$info = $mw -> chooseColor(-title=>$name_menu_colorchorus);	#get a color value from dialog box
	calc_color();							#convert color value into LaTeX format
	if ( $t -> search ( "{color_chorus:", "1.0" ) ) {		#if color directive already exists
		$text = $t->get("1.0", "end");					#save the text in variable $text
		$text =~ s/(\{color_chorus:)(.*)(\})/\1$red,$green,$blue\3/;	#replace color directive with new value
		chomp $text;
		$t->delete("1.0","end");					#delete old text
		$t->insert('end', $text);					#restore text from variable $text
	}else{								#else
		$t -> insert ("end", "\n{color_chorus:$red,$green,$blue}");	#insert a new color directive
	}
}

#--------------------------------------------------------------------------------
# subroutines color_bridge, color_tab ...
#
# the following subroutines work like the color_chorus subroutine
# look there for comments
#--------------------------------------------------------------------------------
sub colors_bridge{
	$info = $mw -> chooseColor(-title=>$name_menu_colorbridge);
	calc_color();
	if ( $t -> search ( "{color_bridge:", "1.0" ) ) {
		$text = $t->get("1.0", "end");
		$text =~ s/(\{color_bridge:)(.*)(\})/\1$red,$green,$blue\3/;
		chomp $text;
		$t->delete("1.0","end");
		$t->insert('end', $text);
	}else{
		$t -> insert ("end", "\n{color_bridge:$red,$green,$blue}");
	}
}

sub colors_tab{
	$info = $mw -> chooseColor(-title=>$name_menu_colortab);
	calc_color();
	if ( $t -> search ( "{color_tab:", "1.0" ) ) {
		$text = $t->get("1.0", "end");
		$text =~ s/(\{color_tab:)(.*)(\})/\1$red,$green,$blue\3/;
		chomp $text;
		$t->delete("1.0","end");
		$t->insert('end', $text);
	}else{
		$t -> insert ("end", "\n{color_tab:$red,$green,$blue}");
	}
}

sub colors_instr{
	$info = $mw -> chooseColor(-title=>$name_menu_colorinstr);
	calc_color();
	if ( $t -> search ( "{color_instr:", "1.0" ) ) {
		$text = $t->get("1.0", "end");
		$text =~ s/(\{color_instr:)(.*)(\})/\1$red,$green,$blue\3/;
		chomp $text;
		$t->delete("1.0","end");
		$t->insert('end', $text);
	}else{
		$t -> insert ("end", "\n{color_instr:$red,$green,$blue}");
	}
}

sub colors_second{
	$info = $mw -> chooseColor(-title=>$name_menu_second);
	calc_color();
	if ( $t -> search ( "{color_second:", "1.0" ) ) {
		$text = $t->get("1.0", "end");
		$text =~ s/(\{color_second:)(.*)(\})/\1$red,$green,$blue\3/;
		chomp $text;
		$t->delete("1.0","end");
		$t->insert('end', $text);
	}else{
		$t -> insert ("end", "\n{color_second:$red,$green,$blue}");
	}
}

sub colors_second_back{
	$info = $mw -> chooseColor(-title=>$name_menu_secondback);
	calc_color();
	if ( $t -> search ( "{color_second_back:", "1.0" ) ) {
		$text = $t->get("1.0", "end");
		$text =~ s/(\{color_second_back:)(.*)(\})/\1$red,$green,$blue\3/;
		chomp $text;
		$t->delete("1.0","end");
		$t->insert('end', $text);
	}else{
		$t -> insert ("end", "\n{color_second_back:$red,$green,$blue}");
	}
}


#--------------------------------------------------------------------------------
# subroutine transpose_up
#
# transpose one half tone up
#--------------------------------------------------------------------------------
sub transpose_up{
	$text = $t->get("1.0", "end");	#save text in variable $text
	$t->delete("1.0","end");	#delete text
	#exchange chord names
	$text =~ s/\[A#/[*B/g;		$text =~ s/\[Ab/[*A/g;		$text =~ s/\[A/[*A#/g;		$text =~ s/\[Bb/[*B/g;
	$text =~ s/\[(B|H)/[*C/g;	$text =~ s/\[C#/[*D/g;		$text =~ s/\[Cb/[*C/g;		$text =~ s/\[C/[*C#/g;
	$text =~ s/\[D#/[*E/g;		$text =~ s/\[Db/[*D/g;		$text =~ s/\[D/[*D#/g;		$text =~ s/\[E#/[*F#/g;
	$text =~ s/\[Eb/[*E/g;		$text =~ s/\[E/[*F/g;		$text =~ s/\[F#/[*G/g;		$text =~ s/\[Fb/[*F/g;
	$text =~ s/\[F/[*F#/g;		$text =~ s/\[G#/[*A/g;		$text =~ s/\[Gb/[*G/g;		$text =~ s/\[G/[*G#/g;
	$text =~ s/\[\*/[/g;		$text =~ s/\/A#/\/*B/g;		$text =~ s/\/Ab/\/*A/g;		$text =~ s/\/A/\/*A#/g;
	$text =~ s/\/Bb/\/*B/g;		$text =~ s/\/(B|H)/\/*C/g;	$text =~ s/\/C#/\/*D/g;		$text =~ s/\/Cb/\/*C/g;
	$text =~ s/\/C/\/*C#/g;		$text =~ s/\/D#/\/*E/g;		$text =~ s/\/Db/\/*D/g;		$text =~ s/\/D/\/*D#/g;
	$text =~ s/\/E#/\/*F#/g;	$text =~ s/\/Eb/\/*E/g;		$text =~ s/\/E/\/*F/g;		$text =~ s/\/F#/\/*G/g;
	$text =~ s/\/Fb/\/*F/g;		$text =~ s/\/F/\/*F#/g;		$text =~ s/\/G#/\/*A/g;		$text =~ s/\/Gb/\/*G/g;
	$text =~ s/\/G/\/*G#/g;		$text =~ s/\/\*/\//g;
	chomp $text;
	$t->insert('end', $text);	#restore text from variable $text
	highlight();			#do syntax highlighting
}

#--------------------------------------------------------------------------------
# subroutine transpose_up
#
# transpose one half tone down
#--------------------------------------------------------------------------------
sub transpose_down{
	$text = $t->get("1.0", "end");	#save text in variable $text
	$t->delete("1.0","end");	#delete text
	#exchange chord names
	$text =~ s/\[A#/[*A/g;		$text =~ s/\[Ab/[*G/g;		$text =~ s/\[A/[*G#/g;		$text =~ s/\[Bb/[*A/g;
	$text =~ s/\[(B|H)/[*A#/g;	$text =~ s/\[C#/[*C/g;		$text =~ s/\[Cb/[*A#/g;		$text =~ s/\[C/[*B/g;
	$text =~ s/\[D#/[*D/g;		$text =~ s/\[Db/[*C/g;		$text =~ s/\[D/[*C#/g;		$text =~ s/\[E#/[*E/g;
	$text =~ s/\[Eb/[*D/g;		$text =~ s/\[E/[*D#/g;		$text =~ s/\[F#/[*F/g;		$text =~ s/\[Fb/[*D#/g;
	$text =~ s/\[F/[*E/g;		$text =~ s/\[G#/[*G/g;		$text =~ s/\[Gb/[*F/g;		$text =~ s/\[G/[*F#/g;
	$text =~ s/\[\*/[/g;
	$text =~ s/\/A#/\/*A/g;		$text =~ s/\/Ab/\/*G/g;		$text =~ s/\/A/\/*G#/g;		$text =~ s/\/Bb/\/*A/g;
	$text =~ s/\/(B|H)/\/*A#/g;	$text =~ s/\/C#/\/*C/g;		$text =~ s/\/Cb/\/*A#/g;	$text =~ s/\/C/\/*B/g;
	$text =~ s/\/D#/\/*D/g;		$text =~ s/\/Db/\/*C/g;		$text =~ s/\/D/\/*C#/g;		$text =~ s/\/E#/\/*E/g;
	$text =~ s/\/Eb/\/*D/g;		$text =~ s/\/E/\/*D#/g;		$text =~ s/\/F#/\/*F/g;		$text =~ s/\/Fb/\/*D#/g;
	$text =~ s/\/F/\/*E/g;		$text =~ s/\/G#/\/*G/g;		$text =~ s/\/Gb/\/*F/g;		$text =~ s/\/G/\/*F#/g;
	$text =~ s/\/\*/\//g;
	chomp $text;

	$t->insert('end', $text);	#restore text from variable $text
	highlight();			#do syntax highlighting
}

#--------------------------------------------------------------------------------
# subroutine transpose_flat2sharp
#
# convert flat notes into sharp notes, e.g. Db -> C#
#--------------------------------------------------------------------------------
sub transpose_flat2sharp{
	$text = $t->get("1.0", "end");	#save text in variable $text
	$t->delete("1.0","end");	#delete text
	#exchange chord names
	$text =~ s/\[Ab/[G#/g;		$text =~ s/\[Bb/[A#/g;		$text =~ s/\[Cb/[B/g;		$text =~ s/\[Db/[C#/g;
	$text =~ s/\[Eb/[D#/g;		$text =~ s/\[Fb/[E/g;		$text =~ s/\[Gb/[F#/g;		$text =~ s/\/Ab/\/G#/g;
	$text =~ s/\/Bb/\/A#/g;		$text =~ s/\/Cb/\/B/g;		$text =~ s/\/Db/\/C#/g;		$text =~ s/\/Eb/\/D#/g;
	$text =~ s/\/Fb/\/E/g;		$text =~ s/\/Gb/\/F#/g;
	chomp $text;
	$t->insert('end', $text);	#restore text from variable $text
	highlight();			#do syntax highlighting
}

#--------------------------------------------------------------------------------
# subroutine transpose_sharp2flat
#
# convert sharp notes into flat notes, e.g. D# -> Eb
#--------------------------------------------------------------------------------
sub transpose_sharp2flat{
	$text = $t->get("1.0", "end");	#save text in variable $text
	$t->delete("1.0","end");	#delete text
	#exchange chord names
	$text =~ s/\[A#/[Bb/g;		$text =~ s/\[(B#|H#)/[C/g;	$text =~ s/\[C#/[Db/g;		$text =~ s/\[D#/[Eb/g;
	$text =~ s/\[E#/[F/g;		$text =~ s/\[F#/[Gb/g;		$text =~ s/\[G#/[Ab/g;		$text =~ s/\/A#/\/Bb/g;
	$text =~ s/\/(B#|H#)/\/C/g;	$text =~ s/\/C#/\/Db/g;		$text =~ s/\/D#/\/Eb/g;		$text =~ s/\/E#/\/F/g;
	$text =~ s/\/F#/\/Gb/g;		$text =~ s/\/G#/\/Ab/g;
	chomp $text;
	$t->insert('end', $text);	#restore text from variable $text
	highlight();			#do syntax highlighting
}

#--------------------------------------------------------------------------------
# subroutine transpose_b2h
#
# convert international notation B into german notation H
#--------------------------------------------------------------------------------
sub transpose_b2h{
	$text = $t->get("1.0", "end");	#save text in variable $text
	$t->delete("1.0","end");	#delete text
	#exchange chord names
	$text =~ s/\[Bb/[*Bb/g;		$text =~ s/\[B/[H/g;		$text =~ s/\[\*/[/g;
	$text =~ s/\/Bb/\/*Bb/g;	$text =~ s/\/B/\/H/g;		$text =~ s/\/\*/\//g;
	chomp $text;
	$t->insert('end', $text);	#restore text from variable $text
	highlight();			#do syntax highlighting
}

#--------------------------------------------------------------------------------
# subroutine transpose_b2h
#
# convert  german notation H into international notation B
#--------------------------------------------------------------------------------
sub transpose_h2b{
	$text = $t->get("1.0", "end");	#save text in variable $text
	$t->delete("1.0","end");	#delete text
	#exchange chord names
	$text =~ s/\[H/[B/g;		$text =~ s/\/H/\/B/g;
	chomp $text;
	$t->insert('end', $text);	#restore text from variable $text
	highlight();			#do syntax highlighting
}


#--------------------------------------------------------------------------------
# subroutine about
#
# some information
#--------------------------------------------------------------------------------

sub about{
	$mw -> messageBox ( -type => "OK", -title => $name_menu_help, -message => $message_about );
}


