#!/usr/bin/perl

use Tk;
use Tk::ErrorDialog;
use Tk::DialogBox;
use Tk::Clipboard;
use File::Basename;

$mw = MainWindow->new;
$mw -> title ("GuitarTeX");

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

$t -> bind ( "<Key>", [\&check_key, Ev('k')] );

$menu_frame = $mw -> Frame -> pack ( -side => 'top', -fill => 'x');

$menu_file = $menu_frame -> Menubutton (-text => "File",
	-menuitems => [
		['command' => "New", -command => \&menu_file_new],
		['command' => "Open...", -command => \&menu_file_open],
		"-",
		['command' => "Save", -command => \&menu_file_save],
		['command' => "Save as...", -command => \&menu_file_saveas],
		"-",
		[cascade => "Export", -menuitems => [
			['command' => "LaTeX", -command => \&export_latex],
			['command' => "Postscript", -command => \&export_postscript],
			['command' => "PDF", -command => \&export_pdf],
			],
		],
		"-",
		['command' => "Quit", -command => \&menu_file_quit],
	]
)->pack (-side => 'left', -anchor => 'w');


$menu_edit = $menu_frame -> Menubutton (-text => "Edit",
	-menuitems => [
		['command' => "Paste from Clipboard", -command => \&menu_edit_paste],
		"-",
		['command' => "Insert file...", -command => \&menu_edit_insert],
		['command' => "crd -> chopro", -command => \&menu_edit_crd2chopro, -accelerator => "F9"],
		"-",
		['command' => "Cut: use ctrl-x", -state => 'disabled'],
		['command' => "Copy: use ctrl-c", -state => 'disabled'],
		['command' => "Paste: use ctrl-v", -state => 'disabled'],
	]
)->pack (-side => 'left', -anchor => 'w');


$menu_chords = $menu_frame -> Menubutton (-text => "Directives",
	-menuitems => [
		['command' => "Start Chorus", -command =>sub{$t->insert("insert linestart","{soc}\n")}],
 		['command' => "End Chorus", -command =>sub{$t->insert("insert linestart","{eoc}\n")}],
  		"-",
		['command' => "Start Bridge", -command => sub{$t->insert("insert linestart","{sob}\n")}],
		['command' => "End Bridge", -command => sub{$t->insert("insert linestart","{eob}\n")}],
		"-",
		['command' => "Start Tablature", -command => sub{$t->insert("insert linestart","{sot}\n")}],
		['command' => "End Tablature", -command => sub{$t->insert("insert linestart","{eot}\n")}],
		"-",
		['command' => "Start Instrumental", -command => sub{$t->insert("insert linestart","{soi}\n")}],
		['command' => "End Instrumental", -command => sub{$t->insert("insert linestart","{eoi}\n")}],
		"-",
		['command' => "GuitarTab", -command => sub{$t->insert("insert linestart","{guitartab:}\n")}],
		['command' => "BassTab", -command => sub{$t->insert("insert linestart","{basstab:}\n")}],
		"-",
		['command' => "Title", -command => sub{
				$t->insert("insert linestart","{t:");
				$t->insert("insert lineend","}\n");
			}],
		['command' => "Subtitle", -command => sub{
				$t->insert("insert linestart","{st:");
				$t->insert("insert lineend","}\n");
			}],
		['command' => "New Page", -command => sub{$t->insert("insert linestart","{np}\n")}],
		['command' => "Comment", -command => sub{
				$t->insert("insert linestart","{c:");
				$t->insert("insert lineend","}\n");
			}],
		['command' => "Margin Par", -command => sub{
				$t->insert("insert linestart","{m:");
				$t->insert("insert lineend","}\n");
			}],
		['command' => "Second Voice", -command => sub{
				$t->insert("insert linestart","{2:");
				$t->insert("insert lineend","}\n");
			}],
	]
)->pack (-side => 'left', -anchor => 'w');

$menu_chords = $menu_frame -> Menubutton (-text => "Songbook",
	-menuitems => [
		['command' => "Document class book", -command => sub{$t->insert("insert","{document_class:book}\n")}],
		['command' => "Book title", -command => sub{
				$t->insert("insert linestart","{book_title:");
				$t->insert("insert lineend","}\n");
			}],
		['command' => "Book author", -command => sub{
				$t->insert("insert linestart","{book_author:");
				$t->insert("insert lineend","}\n");
			}],
		['command' => "Book date", -command => sub{
				$t->insert("insert linestart","{book_date:");
				$t->insert("insert lineend","}\n");
			}],
		['command' => "Chapter", -command => sub{
				$t->insert("insert linestart","{chapter:");
				$t->insert("insert lineend","}\n");
			}],
		['command' => "Include", -command => sub{
				$t->insert("insert linestart","{include:");
				$t->insert("insert lineend","}\n");
			}],
		['command' => "Even", -command => sub{$t->insert("insert linestart","{even}\n")}],
	]
)->pack (-side => 'left', -anchor => 'w');

$menu_colors = $menu_frame -> Menubutton (-text => "Colors",
	-menuitems => [
		['command' => "Chorus",	-command => \&colors_chorus],
		['command' => "Bridge", -command => \&colors_bridge],
		['command' => "Tablature", -command => \&colors_tab],
		['command' => "Instrumental", -command => \&colors_instr],
		['command' => "Second Voice", -command => \&colors_second],
		['command' => "Background second Voice", -command => \&colors_second_back],
	]
)->pack (-side => 'left', -anchor => 'w');


$menu_transpose = $menu_frame -> Menubutton (-text => "Transpose",
	-menuitems => [
		['command' => "Up", -command => \&transpose_up, -accelerator => "F5"],
		['command' => "Down", -command => \&transpose_down, -accelerator => "F6"],
		"-",
		['command' => "b -> #", -command => \&transpose_flat2sharp, -accelerator => "F7"],
		['command' => "# -> b", -command => \&transpose_sharp2flat, -accelerator => "F8"],
		"-",
		['command' => "B -> H", -command => \&transpose_b2h],
		['command' => "H -> B", -command => \&transpose_h2b],
	]
)->pack (-side => 'left', -anchor => 'w');

$menu_help = $menu_frame -> Menubutton (-text => "Help", -tearoff => '0', -menuitems => [
		['command' => "About GuitarTeX", -command => \&about],
	]
)->pack (-side => 'right');


$icon_frame0 = $mw -> Frame ( -relief => "flat", -borderwidth => 0 ) -> pack ( -side => 'top', -anchor => 'w' );

$icon_frame0a = $icon_frame0 -> Frame ( -relief => "groove", -borderwidth => 2 ) -> pack ( -side => 'left');
$icon = $mw -> Photo ( -file => "/filenew.gif" );
$icon_frame0a -> Button(-image => $icon, -relief=>'flat', -command => \&menu_file_new) -> pack(-side=>'left' );
$icon = $mw -> Photo ( -file => "/fileopen.gif" );
$icon_frame0a -> Button(-image => $icon, -relief=>'flat', -command => \&menu_file_open) ->pack(-side=>'left' );
$icon = $mw -> Photo ( -file => "/filesave.gif" );
$icon_frame0a -> Button(-image => $icon, -relief=>'flat', -command => \&menu_file_save) ->pack(-side=>'left' );

#$icon_frame0b = $icon_frame0 -> Frame ( -relief => "groove", -borderwidth => 2 ) -> pack ( -side => 'left');
#$icon = $mw -> Photo ( -file => "/editcut.gif" );
#$icon_frame0b -> Button(-image => $icon, -relief=>'flat', -command => \&menu_edit_cut) ->pack(-side=>'left' );
#$icon = $mw -> Photo ( -file => "/editcopy.gif" );
#$icon_frame0b -> Button(-image => $icon, -relief=>'flat', -command => \&menu_edit_copy) ->pack(-side=>'left' );
#$icon = $mw -> Photo ( -file => "/editpaste.gif" );
#$icon_frame0b -> Button(-image => $icon, -relief=>'flat', -command => \&menu_edit_paste) ->pack(-side=>'left' );

$icon_frame0c = $icon_frame0 -> Frame ( -relief => "groove", -borderwidth => 2 ) -> pack ( -side => 'left');
$icon = $mw -> Photo ( -file => "/tex.gif" );
$icon_frame0c -> Button(-image => $icon, -relief=>'flat', -command => \&export_latex) ->pack(-side=>'left' );
$icon = $mw -> Photo ( -file => "/postscript.gif" );
$icon_frame0c -> Button(-image => $icon, -relief=>'flat', -command => \&export_postscript) ->pack(-side=>'left' );
$icon = $mw -> Photo ( -file => "/pdf.gif" );
$icon_frame0c -> Button(-image => $icon, -relief=>'flat', -command => \&export_pdf) ->pack(-side=>'left' );

$icon_frame0d = $icon_frame0 -> Frame ( -relief => "groove", -borderwidth => 2 ) -> pack ( -side => 'left');
$icon = $mw -> Photo ( -file => "/up.gif" );
$icon_frame0d -> Button(-image => $icon, -relief=>'flat', -command => \&transpose_up) ->pack(-side=>'left' );
$icon = $mw -> Photo ( -file => "/down.gif" );
$icon_frame0d -> Button(-image => $icon, -relief=>'flat', -command => \&transpose_down) ->pack(-side=>'left' );


$icon_frame1 = $mw -> Frame ( -relief => "flat", -borderwidth => 2 ) -> pack ( -side => 'top', -anchor => 'w' );
$icon_frame1 -> Label( -text=>'Chords:', -width=>10 )->pack ( -side => 'left' );
$icon_frame1 -> Button( -text=>"C",  -command=>sub{$t->insert("insert","[C]", 'chord')} )->pack(-side=>'left');
$icon_frame1 -> Button( -text=>"C#", -command=>sub{$t->insert("insert","[C#]",'chord')} )->pack(-side=>'left');
$icon_frame1 -> Button( -text=>"D",  -command=>sub{$t->insert("insert","[D]", 'chord')} )->pack(-side=>'left');
$icon_frame1 -> Button( -text=>"D#", -command=>sub{$t->insert("insert","[D#]",'chord')} )->pack(-side=>'left');
$icon_frame1 -> Button( -text=>"E",  -command=>sub{$t->insert("insert","[E]", 'chord')} )->pack(-side=>'left');
$icon_frame1 -> Button( -text=>"F",  -command=>sub{$t->insert("insert","[F]", 'chord')} )->pack(-side=>'left');
$icon_frame1 -> Button( -text=>"F#", -command=>sub{$t->insert("insert","[F#]",'chord')} )->pack(-side=>'left');
$icon_frame1 -> Button( -text=>"G",  -command=>sub{$t->insert("insert","[G]", 'chord')} )->pack(-side=>'left');
$icon_frame1 -> Button( -text=>"G#", -command=>sub{$t->insert("insert","[G#]",'chord')} )->pack(-side=>'left');
$icon_frame1 -> Button( -text=>"A",  -command=>sub{$t->insert("insert","[A]", 'chord')} )->pack(-side=>'left');
$icon_frame1 -> Button( -text=>"Bb", -command=>sub{$t->insert("insert","[Bb]",'chord')} )->pack(-side=>'left');
$icon_frame1 -> Button( -text=>"B",  -command=>sub{$t->insert("insert","[B]", 'chord')} )->pack(-side=>'left');

$tab_frame = $mw -> Frame ( -relief => "groove", -borderwidth => 0 )
	-> pack ( -side => 'top', -anchor => 'w' );

$tab_frame -> Label( -text=>'Tablature:', -width=>10 )->pack ( -side => 'left' );
$tab_frame -> Button( -text=>"Guitar", -command => sub{$t->insert("insert linestart","{guitartab:}\n")}) -> pack ( -side => 'left' );
$tab_frame -> Button( -text=>"Bass", -command => sub{$t->insert("insert linestart","{basstab:}\n")}) -> pack ( -side => 'left' );
$tab_frame -> Label( -text=>' Fret:' )->pack ( -side => 'left' );
$tab_frame -> Entry( -width=>3, -relief=>'sunken', -background=>'white', -textvariable=>\$tab)->pack ( -side => 'left' );
$tab_frame -> Label( -text=>' String:' )->pack ( -side => 'left' );
$tab_frame -> Button( -text=>"E", -command=>sub{$t->insert("insert","[1;$tab]");$tab=""}) -> pack ( -side => 'left' );
$tab_frame -> Button( -text=>"A", -command=>sub{$t->insert("insert","[2;$tab]");$tab=""}) -> pack ( -side => 'left' );
$tab_frame -> Button( -text=>"D", -command=>sub{$t->insert("insert","[3;$tab]");$tab=""}) -> pack ( -side => 'left' );
$tab_frame -> Button( -text=>"G", -command=>sub{$t->insert("insert","[4;$tab]");$tab=""}) -> pack ( -side => 'left' );
$tab_frame -> Button( -text=>"B", -command=>sub{$t->insert("insert","[5;$tab]");$tab=""}) -> pack ( -side => 'left' );
$tab_frame -> Button( -text=>"e", -command=>sub{$t->insert("insert","[6;$tab]");$tab=""}) -> pack ( -side => 'left' );


$mw->Label(-textvariable => \$info) -> pack( -side => 'bottom', -anchor => 'w');

$t -> pack( -fill => 'both', -expand => 1);
$t ->focus();

MainLoop;

sub check_key {
	$taste = $_[1];
	if ( $taste == 71 ) { transpose_up(); }
	if ( $taste == 72 ) { transpose_down(); }
	if ( $taste == 73 ) { transpose_flat2sharp(); }
	if ( $taste == 74 ) { transpose_sharp2flat(); }
	if ( $taste == 75 ) { menu_edit_crd2chopro(); }
}

sub menu_file_new {
	$info = "File New";
	ask_save();
	$filename = "";
	$t->delete ("1.0", "end");
}

sub menu_file_open {
	$info = "File Open";
	ask_save();
	$filename = $mw->getOpenFile ( -filetypes =>
		[
			['GuitarTeX Files',	['.gtx']],
			['ChordPro Files',	['.chopro','.pro']],
			['Text Files',		['.txt', '.text']],
			['All Files',        '*',             ],
		],
		-title => "Open File" );
	$info = $filename;
	$t->delete("1.0","end");		# ursprnglichen Text lschen

	open ( FILE, "$filename" );
	while ( <FILE> ){ $t->insert("end", $_); }
	close (FILE);
	$t ->focus();
}

sub ask_save{
	if ( $filename eq "" ) { return }
	$info = "ask_save";
	$dialog = $mw->Dialog(
		-buttons => ["yes","no"],
		-title => "Save File",
		-text => "Do you want to save\nthe current document?",
		);
	$info = $dialog -> Show;
	if ( $info eq "yes" ) { menu_file_save() }
}

sub menu_file_save {
	$info = "File Save";
	if ( $filename ){ save() } else { menu_file_saveas() }
}

sub menu_file_saveas {
	$info = "File Save as";
	$filename = $mw->getSaveFile ( -filetypes =>
		[
			['GuitarTeX Files',	['.gtx']],
			['ChordPro Files',	['.chopro','.pro']],
			['Text Files',		['.txt', '.text']],
			['All Files',        '*',             ],
		],
		-title => "Save File" );
	$info = $filename;
	save();
}

sub save {
	open ( FILE, ">$filename" ) or die "cannot open file $filename\n";
	$text = $t->get("1.0", "end");
	chomp $text;
	print FILE $text;
	close (FILE);
	$info = "saved as " . $filename;
}

sub menu_file_quit {
	$info = "File Quit";
	ask_save();
	exit;
}

sub menu_edit_cut {
	menu_edit_copy();
	$info = "Edit Cut";
	menu_edit_copy();
#	$t -> delete( "sel.first", "sel.last" );
}

sub menu_edit_copy {
	$info = "Edit Copy";
#	$text = $t -> get( "sel.first", "sel.last" );
#	$t -> clipboardClear();
#	$t -> clipboardAppend ( -type => "STRING", -format => "STRING", $text );
 $mw -> messageBox ( -message => "not yet implemented", -type => "OK" );
}

sub menu_edit_paste {
	$info = "Edit Paste";
	$text = $mw -> SelectionGet();
	$t -> insert("insert", $text )
}

sub menu_edit_insert {
	$info = "Edit Insert file";
	$insert_filename = $mw->getOpenFile ( -filetypes =>
		[
			['GuitarTeX Files',	['.gtx']],
			['ChordPro Files',	['.chopro','.pro']],
			['Text Files',		['.txt', '.text']],
			['All Files',        '*',             ],
		],
		-title => "Insert File" );
	$info = $insert_filename;
	open ( FILE, "$insert_filename" );
	while ( <FILE> ){ $t->insert("insert", $_); }
	close (FILE);
}
sub menu_edit_crd2chopro {
	$info = "Edit crd->chopro";
	$chord = $t -> get ("insert linestart", "insert lineend" );
	$t -> delete ( "insert linestart", "insert lineend + 1 char" );
	$lyric = $t -> get ("insert linestart", "insert lineend" );
	$t -> delete ( "insert linestart", "insert lineend" );
	# Lngen der Text und Akkordzeile anpassen
	if ( length($lyric) < length ($chord) ) {
		$lyric .= " " x ( length ($chord) - length ($lyric) +1 );
		$chord .= " ";
	}else{
		$chord .= " " x ( length ($lyric) - length ($chord) +1 );
		$lyric .= " ";
	}

	$chopro="";
	for ( $i=0; $i<length($lyric); $i++ ){
		if ( substr ($chord, $i, 1) eq " " ){
			$chopro .= substr ($lyric, $i, 1);
		}else{
			$chopro .= "[";
			$chordlen = 0;
			while ( substr ($chord, $i+$chordlen, 1) ne " " ){
				$chopro .= substr ($chord, $i+$chordlen, 1);
				$chordlen++;
			}
                        $chopro .= "]";
			for ( $j = 0; $j <= $chordlen; $j++ ){
				$chopro .= substr ($lyric, $i+$j, 1);
			}
			$i = $i + $chordlen;
		}
	}
	chop $chopro;
	$t -> insert ("insert", $chopro);
	$t -> delete ("insert");
	$t -> insert ("insert", "\n");

}

sub transpose_up{
	$info = "Transpose up";
	$text = $t->get("1.0", "end");	# Text in Variable zwischenspeichern
	$t->delete("1.0","end");	# ursprnglichen Text lschen

	$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);		# Variable zurckschreiben
}

sub transpose_down{
	$info = "Transpose down";
	$text = $t->get("1.0", "end");	# Text in Variable zwischenspeichern
	$t->delete("1.0","end");		# ursprnglichen Text lschen

	$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);		# Variable zurckschreiben
}

sub transpose_flat2sharp{
	$info = "Transpose flat to sharp";
	$text = $t->get("1.0", "end");	# Text in Variable zwischenspeichern
	$t->delete("1.0","end");		# ursprnglichen Text lschen

	$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);		# Variable zurckschreiben
}

sub transpose_sharp2flat{
	$info = "Transpose sharp to flat";
	$text = $t->get("1.0", "end");	# Text in Variable zwischenspeichern
	$t->delete("1.0","end");		# ursprnglichen Text lschen

	$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);		# Variable zurckschreiben
}

sub transpose_b2h{
	$info = "Transpose B to H";
	$text = $t->get("1.0", "end");	# Text in Variable zwischenspeichern
	$t->delete("1.0","end");		# ursprnglichen Text lschen

	$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);		# Variable zurckschreiben
}

sub transpose_h2b{
	$info = "Transpose H to B";
	$text = $t->get("1.0", "end");	# Text in Variable zwischenspeichern
	$t->delete("1.0","end");		# ursprnglichen Text lschen

	$text =~ s/\[H/[B/g;
	$text =~ s/\/H/\/B/g;
	chomp $text;

	$t->insert('end', $text);		# Variable zurckschreiben
}

sub export_latex{
	$info = "Export Latex";
	$output = "latex";
	menu_file_save();
	guitartex();
	$info = "TeX file $outfilename.tex ready";
}

sub export_postscript{
	$info = "Export Postscript";
	$output = "ps";
	menu_file_save();
	guitartex();
	$info = "Postscript file $outfilename.ps ready";
}

sub export_pdf{
	$info = "Export PDF";
	$output = "pdf";
	menu_file_save();
	guitartex();
	$info = "PDF file ready";
}

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";
}

sub colors_chorus{
	$info = "Colors chorus";
	$info = $mw -> chooseColor(-title=>"Chorus Color");
	calc_color();
	if ( $t -> search ( "{color_chorus:", "1.0" ) ) {
		$text = $t->get("1.0", "end");		# Text in Variable zwischenspeichern
		$text =~ s/(\{color_chorus:)(.*)(\})/\1$red,$green,$blue\3/;
		chomp $text;
		$t->delete("1.0","end");		# ursprnglichen Text lschen
		$t->insert('end', $text);		# Variable zurckschreiben
	}else{
		$t -> insert ("end", "\n{color_chorus:$red,$green,$blue}");
	}
}

sub colors_bridge{
	$info = "Colors bridge";
	$info = $mw -> chooseColor(-title=>"Bridge Color");
	calc_color();
	if ( $t -> search ( "{color_bridge:", "1.0" ) ) {
		$text = $t->get("1.0", "end");	# Text in Variable zwischenspeichern
		$text =~ s/(\{color_bridge:)(.*)(\})/\1$red,$green,$blue\3/;
		chomp $text;
		$t->delete("1.0","end");		# ursprnglichen Text lschen
		$t->insert('end', $text);		# Variable zurckschreiben
	}else{
		$t -> insert ("end", "\n{color_bridge:$red,$green,$blue}");
	}
}

sub colors_tab{
	$info = "Colors tablature";
	$info = $mw -> chooseColor(-title=>"Tablature Color");
	calc_color();
	if ( $t -> search ( "{color_tab:", "1.0" ) ) {
		$text = $t->get("1.0", "end");	# Text in Variable zwischenspeichern
		$text =~ s/(\{color_tab:)(.*)(\})/\1$red,$green,$blue\3/;
		chomp $text;
		$t->delete("1.0","end");		# ursprnglichen Text lschen
		$t->insert('end', $text);		# Variable zurckschreiben
	}else{
		$t -> insert ("end", "\n{color_tab:$red,$green,$blue}");
	}
}

sub colors_instr{
	$info = "Colors instrumental";
	$info = $mw -> chooseColor(-title=>"Instrumental Color");
	calc_color();
	if ( $t -> search ( "{color_instr:", "1.0" ) ) {
		$text = $t->get("1.0", "end");	# Text in Variable zwischenspeichern
		$text =~ s/(\{color_instr:)(.*)(\})/\1$red,$green,$blue\3/;
		chomp $text;
		$t->delete("1.0","end");		# ursprnglichen Text lschen
		$t->insert('end', $text);		# Variable zurckschreiben
	}else{
		$t -> insert ("end", "\n{color_instr:$red,$green,$blue}");
	}
}

sub colors_second{
	$info = "Colors second voice";
	$info = $mw -> chooseColor(-title=>"Second Voice Color");
	calc_color();
	if ( $t -> search ( "{color_second:", "1.0" ) ) {
		$text = $t->get("1.0", "end");	# Text in Variable zwischenspeichern
		$text =~ s/(\{color_second:)(.*)(\})/\1$red,$green,$blue\3/;
		chomp $text;
		$t->delete("1.0","end");		# ursprnglichen Text lschen
		$t->insert('end', $text);		# Variable zurckschreiben
	}else{
		$t -> insert ("end", "\n{color_second:$red,$green,$blue}");
	}
}

sub colors_second_back{
	$info = "Colors second voice background";
	$info = $mw -> chooseColor(-title=>"Second Voice Background Color");
	calc_color();
	if ( $t -> search ( "{color_second_back:", "1.0" ) ) {
		$text = $t->get("1.0", "end");	# Text in Variable zwischenspeichern
		$text =~ s/(\{color_second_back:)(.*)(\})/\1$red,$green,$blue\3/;
		chomp $text;
		$t->delete("1.0","end");		# ursprnglichen Text lschen
		$t->insert('end', $text);		# Variable zurckschreiben
	}else{
		$t -> insert ("end", "\n{color_second_back:$red,$green,$blue}");
	}
}

sub about{
	$info = "about";
	$mw -> messageBox ( -type => "OK", -title => "Help",
		-message => "In case of problems\nsee doc.pdf :-)
or contact the author\nat jmiltz\@web.de" );
}

sub latex2ps {
        $info = "processing $outfilename, please wait ...";
        # Leerzeichen im Dateinamen in Unterstriche ndern
        $outfilename2 = $outfilename;
        $outfilename2 =~ s/\s/\_/g;
        system ( "mv -f \"$outfilename.tex\" $outfilename2.tex" );
        $outfilename = $outfilename2;
        print "$outfilename\n";

        if( system ( "latex --interaction batchmode $outfilename" ) ) {
                show_latex_errors();
        }else{
                print ".....guitartex message: 1st latex run ok\n";
                if ( $document_class eq "book" ) { # weiterer Durchlauf bei Dokumentklasse book
                        if ( ! system ( "makeindex $outfilename.idx" ) ) { print "\n.....guitartex message: makeindex ok\n" }
                        if ( ! system ( "latex $outfilename" ) ) { print ".....guitartex message: 2nd latex run ok\n" }
                }
                if ( ! system ( "dvips $outfilename" ) ) { print ".....guitartex message: dvips ok\n" }
                if ( ! system ( "rm -f $outfilename.tex" ) ) { print ".....guitartex message: delete tex file ok\n" }
                if ( ! system ( "mv -f $outfilename.ps $dirname" ) ) { print ".....guitartex message: move output to original directory ok\n" }
                if ( ! system ( "rm -f *.aux *.toc *.dvi $dirname/*.tmp" ) ) { print ".....guitartex message: delete temporary files ok\n" }
        }
}

sub show_latex_errors{
        print ".....guitartex message: 1st latex run failed, see $dirname/$outfilename.log for details\n";
        $error_log = "";
        open ( FILE, "$outfilename.log" );
	while ( <FILE> ){
                if ( /^!/ ) {
                        $error_log .= $_ .= <FILE>;
                        $error_log .= "\n";
                }
        }
	close (FILE);
        $error_log .= "\nfor more details see\n$outfilename.log";
        $dialog = $mw->Dialog( -buttons => ["close"], -title => "LaTeX error(s)", -text => "$error_log" ) -> Show;
}

sub guitartex{

	$vers_numbers = "no";
	$outfilename = basename($filename);
	$dirname = dirname($filename);
	$outfilename =~ s/\.(.*?)$//;	# Suffix entfernen

        # Dateien ffnen
        open ( CHORDPRO, "$filename" ) || die "cannot open input file";
        open ( TEX, ">$outfilename.tex" ) || die "cannot open output file";

        define_var_latex(); # Variablen definieren

        # LaTeX-Header ausgeben
        latex_header();

        # Eingabedatei zeilenweise bearbeiten
        while ( <CHORDPRO> ) {
                # Zeichen fr Zeilenende abschneiden
                chomp;
                # wenn am Anfang der Zeile { steht, handelt es sich um eine Direktive
                if ( /^{/ ){ directive(); next; }
                # Leerzeile
                if ( /^$/ ){ print TEX "$empty_line\n"; next; }
                # wenn am Anfang der Zeile % oder # steht, handelt es sich um einen Kommentar
                if ( /^[%#]/ ){	next; }
                # wenn am Anfang der Zeile \ steht, handelt es sich um ein Latex-Kommando
                if ( /\\/ ){ print TEX "$_\n"; next; }
                # innerhalb einer Tabulatur
                if ( $env eq "tab" ) {
                        print TEX "\\footnotesize \\verb!$_! \\normalsize \\newline\n"; next;
                }
                crdpro();
        }
        # LaTeX-Footer ausgeben
        latex_footer();

        if ( $output eq "latex" ) {
                system ( "rm -f *.aux *.log *.toc *.dvi" );
                system ( "mv -f $outfilename.tex $dirname" );
        }

        if ( $output eq "ps" ) { latex2ps() }

        if ( $output eq "pdf" ) {
                latex2ps();
                system ( "ps2pdf $dirname/$outfilename.ps $dirname/$outfilename.pdf" );
#		system ( "mv -f $outfilename.pdf $dirname" );
		system ( "rm -f $dirname/$outfilename.ps" );
        }

}

sub crdpro { # Bearbeitung der Zeile aus der Eingabedatei

	s/(\^)(.*?)(\])/\\\(^{\2}\\\)\]/g;	# Ziffern hochstellen
	s/\s/$space/g; 				# alle Leerzeichen durch feste Leerzeichen ersetzen
	s/\[/\\chord{/g;			# linke Klammer ersetzen
	s/\]/}/g;				# rechte Klammer ersetzen
	s/#/$sharp/g; 				# Vorzeichen "#" ersetzen
	s/\{Ab/{A$flat/g;                       # Vorzeichen "b" ersetzen
	s/\{Bb/{B$flat/g;
	s/\{Cb/{C$flat/g;
	s/\{Db/{D$flat/g;
	s/\{Eb/{E$flat/g;
	s/\{Fb/{F$flat/g;
	s/\{Gb/{G$flat/g;
	print TEX "$_\\\\\n";
}

sub directive{
	if 	( /{soc}|{start_of_chorus}/ ) 	{ $env = "chorus"; print TEX "$chorus_begin";
	}elsif	( /{eoc}|{end_of_chorus/ ) 	{ $env = "normal"; print TEX "$chorus_end";
	}elsif	( /{sob}|{start_of_bridge}/ ) 	{ $env = "bridge"; print TEX "$bridge_begin";
	}elsif	( /{eob}|{end_of_bridge/ ) 	{ $env = "normal"; print TEX "$bridge_end";
	}elsif	( /{soi}|{start_of_instr}/ ) {
		$env = "instr";
		print TEX "$instr_begin";
	}elsif ( /{eoi}|{end_of_instr/ ) {
		$env = "normal";
		print TEX "$instr_end";
	}elsif ( /{sot}|{start_of_tab}/ ) {
		$env = "tab";
		print TEX "$tab_begin";
	}elsif ( /{eot}|{end_of_tab/ ) {
		$env = "normal";
		print TEX "$tab_end";
	}elsif ( /{np}/ ) {
		print TEX "$new_page";
	}elsif ( /{even}/ ) {
		print TEX "\\ifthenelse{\\isodd{\\thepage}}{}{\\newpage ~}";
	}elsif ( /{title:|{t:/ ) {
		s/({.*:)(.+)(})/\2/;
		if ( $document_class eq "book" ){
			print TEX "$define";
		}
		print TEX "%\n%----- New Song -----\n";
		print TEX "\\newpage\\addcontentsline{toc}{section}{$_}\n";
		print TEX "\\begin{center} \\section*{$_}\\end{center}\n";
		print TEX "\\setcounter{verscnt}{0}\n%\n";
		$define="";
		print TEX "\\index{$_}";
		$song_title = $_;
	}elsif ( /{subtitle:|{st:/ ) {
		s/({.*:)(.+)(})/\2/;
		print TEX "\\index{$_!$song_title}";
		print TEX "\\begin{center}$_\\end{center}\n";
	}elsif ( /{margin:|{m:/ ) {
		s/({.*:)(.+)(})/\2/;
		print TEX "\\marginpar{$_}\n";
	}elsif ( /{comment:|{c:/ ) {
		s/({.*:)(.+)(})/\2/;
		print TEX "\\textit{$_}\\\\\n";
	}elsif ( /{second:|{2:/ ) {
		s/({.*:)(.+)(})/\2/;
		s/\s/$space/g;	#Leerzeichen durch feste Leerzeichen ersetzen
		print TEX "\\colorbox{second_back}{\\textcolor{second_text}{$_}}\\\\\n";
	}elsif ( /{chapter:/ ) {
		s/({.*:)(.+)(})/\2/;
		if ( $document_class eq "book" ) {
			print TEX "$define";
			$define = "";
			print TEX "\n\\chapter{$_} \\fancyhead[CO]{$_}\n\n"
		};
	}elsif ( /{define/ ) {
		s/\{//;
		s/\}//;
		s/define//;
		s/://;
		s/base-fret//;
		s/frets//;
		s/[Xx]/-1/g;
		s/- /-1/g;
                s/-$/-1/g;
#                print "$_\n";
		@def = split(" ",$_);
		@def[0] =~ s/#/\\#/g;
		$define .= "\\mbox{\\begin{picture}(20,18)\\special{\"0 0 moveto ";
		$define .= "($def[0]) $def[2] $def[3] $def[4] $def[5] $def[6] $def[7] $def[1]";
		$define .= " 0 dots}\\end{picture}}\n";
	}elsif ( /{guitartab:/ ) {
		print TEX "\\guitartab\n";
		newtab();
	}elsif ( /{basstab:/ ) {
		print TEX "\\basstab\n";
		newtab();
	}

}

sub newtab {
	if ( /{guitartab:/ ) { $guitartab="yes" } else { $guitartab ="no" };
	s/({.*:)(.+)(})/\2/;
	s/\]\[/\]~~~\[/g;       #fill in fixed spaces between notes
	s/\_/~~~/g;             #fill in extra space
	s/\s/~/g;               #replace spaces with fixed spaced
	s/\]&\[/\]\[/g;         #chord
	s/\[1;/\[2.5ex;/g;
	s/\[2;/\[4.5ex;/g;
	s/\[3;/\[6.5ex;/g;
	s/\[4;/\[8.5ex;/g;
	s/\[5;/\[10.5ex;/g;
	s/\[6;/\[12.5ex;/g;
	if ( $guitartab eq "yes") {
		s/\|/~~~\[3.7ex;\|\][5.7ex;\|\][7.7ex;\|\][9.7ex;\|\][11.3ex;\|\]~~~/g;
	}else{
		s/\|/~~~\[3.7ex;\|\][5.7ex;\|\][7.3ex;\|\]~~~/g;
	}
	s/\[/\\tabs{/g;
	s/\]/\}/g;
	s/;/\}\{/g;
	print TEX "$_\n\n";
}

sub define_var_latex {

	$env = "normal";

	$cols_start = "\\halign{#\\hfil" ;
	$cols_new_col = "&#\\hfil" ;
	$cols_end = "\\cr";

	$chords_start = "\\chordsize" ;
	$chords_new_col = "&\\chordsize " ;
	$chords_end = "\\cr";

	$lyrics_start = "\\text" ;
	$lyrics_new_col = "&\\text " ;
	$lyrics_end = "\\cr}\n";

	$space = "~";
	$empty_line = "~\\\\";
	$new_page = "\\newpage\n";
	$sharp = "\$\\sharp\$";
	$flat = "\$\\flat\$";

	$chorus_begin = "\\begin{chorus}\n";
	$chorus_end = "\\end{chorus}\n";
	$bridge_begin = "\\begin{bridge}\n";
	$bridge_end = "\\end{bridge}\n";
	$instr_begin = "\\begin{instr}\n";
	$instr_end = "\\end{instr}\n";
	$tab_begin = "\\begin{tab}\n";
	$tab_end = "\\end{tab}\n";

	$define = "";

}

sub latex_header {

# Default-Werte
$document_class = "article";
$font_size = "11";
$color_chorus = "1,0,0";
$color_bridge = "0,0,1";
$color_instr = ".3,.3,.3";
$color_tab = ".3,.3,.3";
$color_second = "1,1,1";
$color_second_back = ".7,.7,.7";

# Dokument-Einstellungen lesen
while ( <CHORDPRO> ){
	if ( /^{/ ) {	# nur Zeilen mit Direktiven bearbeiten
		chomp;
		if ( /{book_title:/ ) {
			s/({.*:)(.+)(})/\2/;
			$title = $_ ;
		}elsif ( /{book_author:/ ) {
			s/({.*:)(.+)(})/\2/;
			$author = $_ ;
		}elsif ( /{book_date:/ ) {
			s/({.*:)(.+)(})/\2/;
			$date = $_ ;
		}elsif ( /{document_class:/ ) {
			s/({.*:)(.+)(})/\2/;
			$document_class = $_ ;
#			print "Document_class: $document_class\n";
			if ( $document_class ne "book" && $document_class ne "article" ) {
				die "parameter of directive document_class must be \"book\" or \"article\"\n";
			}
		}elsif ( /{font_size:/ ) {
			s/({.*:)(.+)(})/\2/;
			$font_size = $_ ;
		}elsif ( /{color_chorus:/ ) {
			s/({.*:)(.+)(})/\2/;
			$color_chorus = $_ ;
		}elsif ( /{color_bridge:/ ) {
			s/({.*:)(.+)(})/\2/;
			$color_bridge = $_ ;
		}elsif ( /{color_instr:/ ) {
			s/({.*:)(.+)(})/\2/;
			$color_instr = $_ ;
		}elsif ( /{color_tab:/ ) {
			s/({.*:)(.+)(})/\2/;
			$color_tab = $_ ;
		}elsif ( /{color_second:/ ) {
			s/({.*:)(.+)(})/\2/;
			$color_second = $_ ;
		}elsif ( /{color_second_back:/ ) {
			s/({.*:)(.+)(})/\2/;
			$color_second_back = $_ ;
		}
	}
}

seek ( CHORDPRO, 0, 0 );	# Leseposition wieder auf Dateianfang zurcksetzen

# Includes auflsen
open ( TMP, ">$dirname/$outfilename.tmp" ) || die "cannot open output file";
while ( <CHORDPRO> ){
	if ( /{include:/ ) {	# nur Zeilen mit Include-Direktive bearbeiten
		s/({.*:)(.+)(})/\2/;
		print TMP "#$_\n#\n";
		open ( INSERT, "$dirname/$_" ) || die "cannot open file to insert: $_";
		while ( <INSERT> ){
			print TMP;
		}
	}else{
		print TMP;
	}
        close (FILE);
}
close ( CHORDPRO );
close ( TMP );


# Temporre Datei ffnen
open ( CHORDPRO, "$dirname/$outfilename.tmp" ) || die "cannot open input file";

print TEX "
\\documentclass[german, a4paper, "."$font_size"."pt]{$document_class}
\\usepackage{a4}
\\usepackage{babel}
\\usepackage[T1]{fontenc}
\\usepackage[latin1]{inputenc}
\\usepackage{color}
\\usepackage{graphicx}
\\usepackage{ifthen}
%
";

if ( $document_class eq "book" ){
print TEX "
\\title{$title}
\\author{$author}
\\date{$date}
\\usepackage{makeidx}
\\makeindex
\\usepackage{fancyhdr}
\\pagestyle{fancy}
\\addtolength{\\topmargin}{-1.0 cm}
\\textheight = 25 cm"
}else{
print TEX "
\\pagestyle{empty}
\\setlength{\\textheight}{27cm}
\\addtolength{\\topmargin}{-3cm}
"};

print TEX "
\\reversemarginpar
%\\headsep = 5 mm
%
%------definition of font colors-----------
\\definecolor{chorus}{rgb}{$color_chorus}
\\definecolor{bridge}{rgb}{$color_bridge}
\\definecolor{instr}{rgb}{$color_instr}
\\definecolor{tab}{rgb}{$color_tab}
\\definecolor{second_text}{rgb}{$color_second}
\\definecolor{second_back}{rgb}{$color_second_back}
%
%------definition of environments-------
\\newenvironment{chorus}{\\color{chorus}}{\\normalcolor}
\\newenvironment{bridge}{\\color{bridge}}{\\normalcolor}
\\newenvironment{instr}{\\color{instr}}{\\normalcolor}
\\newenvironment{tab}{\\color{tab}}{\\normalcolor}
%
%------counter for line numbers------
\\newcounter{verscnt}[section]
\\newcommand{\\vers}{\\stepcounter{verscnt}%
\\makebox[0.5cm][r]{\\scriptsize\\theverscnt\\normalsize}%
\\makebox[0.5cm]{}}
%
\\newcommand{\\text}{\\normalsize}
\\newcommand{\\chordsize}{\\footnotesize}
\\setlength{\\parindent}{0pt}

%------PostScript-Header fr die Chord-Songs------
\\special{header=chord-common.ps}

\\sloppy
\\setlength{\\unitlength}{1mm}
\\newcommand{\\chord}[1]{\\raisebox{-0.8ex}{\\makebox[0pt][l]{\\vbox{\\vss\\hbox{\\scriptsize\\bf#1}\\vss\\hbox{\\vbox{\\rule{0pt}{0.5ex}}}}}}}

\\newcommand{\\guitartab}{%
\\makebox[0cm][l]{\\raisebox{12.5ex}{\\footnotesize{e}}}%
\\makebox[0cm][l]{\\raisebox{10.5ex}{\\footnotesize{B}}}%
\\makebox[0cm][l]{\\raisebox{8.5ex}{\\footnotesize{G}}}%
\\makebox[0cm][l]{\\raisebox{6.5ex}{\\footnotesize{D}}}%
\\makebox[0cm][l]{\\raisebox{4.5ex}{\\footnotesize{A}}}%
\\makebox[0cm][l]{\\raisebox{2.5ex}{\\footnotesize{E}}}%
~~
\\makebox[0cm][l]{\\raisebox{13ex}{\\line(1,0){130}}}%
\\makebox[0cm][l]{\\raisebox{11ex}{\\line(1,0){130}}}%
\\makebox[0cm][l]{\\raisebox{9ex}{\\line(1,0){130}}}%
\\makebox[0cm][l]{\\raisebox{7ex}{\\line(1,0){130}}}%
\\makebox[0cm][l]{\\raisebox{5ex}{\\line(1,0){130}}}%
\\makebox[0cm][l]{\\raisebox{3ex}{\\line(1,0){130}}}%
~}

\\newcommand{\\basstab}{%
\\makebox[0cm][l]{\\raisebox{8.5ex}{\\footnotesize{G}}}%
\\makebox[0cm][l]{\\raisebox{6.5ex}{\\footnotesize{D}}}%
\\makebox[0cm][l]{\\raisebox{4.5ex}{\\footnotesize{A}}}%
\\makebox[0cm][l]{\\raisebox{2.5ex}{\\footnotesize{E}}}%
~~
\\makebox[0cm][l]{\\raisebox{9ex}{\\line(1,0){130}}}%
\\makebox[0cm][l]{\\raisebox{7ex}{\\line(1,0){130}}}%
\\makebox[0cm][l]{\\raisebox{5ex}{\\line(1,0){130}}}%
\\makebox[0cm][l]{\\raisebox{3ex}{\\line(1,0){130}}}%
~}

\\newcommand{\\tabs}[2]{\\makebox[0cm][l]{\\raisebox{#1}{#2}}}

%------start of document-----------
\\begin{document}
";

if ( $document_class eq "book" ){
print TEX "
\\fancyhead
\\fancyfoot
\\frontmatter
\\maketitle
\\tableofcontents
\\mainmatter
\\fancyhead[CE]{$title}
\\fancyhead[LE,RO]{\\thepage}
"};

print TEX "%\n%\n";
}

sub latex_footer {
	print TEX "$define\n";
	if ( $document_class eq "book") {
		print TEX "\\backmatter";
		print TEX "\\printindex\n";
	}
	print TEX "\\end{document}\n";
	close ( TEX );
}

