#!/usr/bin/perl -w

my $VERSION = '0.7.0';

use strict;
# use the ToolKit
use Tk;
use Tk::Text;
use Tk::FileSelect;
use Tk::DialogBox;
use Pod::Text;
use File::Basename;
use Getopt::Long;

# Global vars defined here

my ($circle_frame, $delta, $fontlistbox, $fontentry, $scale, $text_frame);
my ($fmw, $fgw, $fff, $crw, $caw, $spw, $psfile, $viewer, $converter, $number_of_background);
my ($begin_from_bottom, $x_scale, $y_scale, $scale_x, $scale_y, $shift_x, $shift_y);
my (@textfield_frame, @circle_text_frame, @textfield_entry, @entry, @text);
my (@font, @fontsize, @begin_from_left, @eps_file_entry, @eps_filename, @eps_file_label);
my ($tickmarks, $print_circle_boundaries, $number_of_labels, $which_field, $pidsav);
my ($graphics_file, $radius_inner, $radius_outer, $starting_angle);
my (@ct_clear, @tf_clear);
my ($graphics_directory, $Bounding_X, $Bounding_Y, $x_origin, $y_origin, $debug);
my (@shift_eps_x, @shift_eps_y, @scale_eps_x, @scale_eps_y, @fontfamily, @fontnames);
my (@color_rgb, @rgb, @ps_color, @tk_color, @circle_radius, @label_active);

my @configurationfile;
my $fontpath;
my %fonthash;
my ($label_fn, $label_id);

# Global parameters to be changed if needed

# The variables we want to be saved in the configuration file

my @SaveVariables = qw(delta begin_from_bottom viewer converter
		    radius_inner tickmarks
		    print_circle_boundaries
		    begin_from_left[0] begin_from_left[1]
		    number_of_labels debug
		    circle_radius[0][0] circle_radius[0][1]
		    circle_radius[0][2] circle_radius[0][3]
		    circle_radius[1][0] circle_radius[1][1]
		    circle_radius[1][2] circle_radius[1][3]
		    x_scale y_scale
		   );

my @LabelVariables = qw( text[0][0] text[0][1] text[0][2] text[0][3]
		     text[0][4] text[0][5] text[0][6] text[0][7]
		     text[1][0] text[1][1] text[1][2] text[1][3]
		     text[1][4] text[1][5] text[1][6] text[1][7]
		     fontfamily[0][0] fontfamily[0][1] fontfamily[0][2] fontfamily[0][3]
		     fontfamily[0][4] fontfamily[0][5] fontfamily[0][6] fontfamily[0][7]
		     fontfamily[1][0] fontfamily[1][1] fontfamily[1][2] fontfamily[1][3]
		     fontfamily[1][4] fontfamily[1][5] fontfamily[1][6] fontfamily[1][7]
		     fontsize[0][0] fontsize[0][1] fontsize[0][2] fontsize[0][3]
		     fontsize[0][4] fontsize[0][5] fontsize[0][6] fontsize[0][7]
		     fontsize[1][0] fontsize[1][1] fontsize[1][2] fontsize[1][3]
		     fontsize[1][4] fontsize[1][5] fontsize[1][6] fontsize[1][7]
		     color_rgb[0][0][0] color_rgb[0][0][1] color_rgb[0][0][2]
		     color_rgb[0][1][0] color_rgb[0][1][1] color_rgb[0][1][2]
		     color_rgb[0][2][0] color_rgb[0][2][1] color_rgb[0][2][2]
		     color_rgb[0][3][0] color_rgb[0][3][1] color_rgb[0][3][2]
		     color_rgb[0][4][0] color_rgb[0][4][1] color_rgb[0][4][2]
		     color_rgb[0][5][0] color_rgb[0][5][1] color_rgb[0][5][2]
		     color_rgb[0][6][0] color_rgb[0][6][1] color_rgb[0][6][2]
		     color_rgb[0][7][0] color_rgb[0][7][1] color_rgb[0][7][2]
		     color_rgb[0][9][0] color_rgb[0][9][1] color_rgb[0][9][2]
		     color_rgb[1][0][0] color_rgb[1][0][1] color_rgb[1][0][2]
		     color_rgb[1][1][0] color_rgb[1][1][1] color_rgb[1][1][2]
		     color_rgb[1][2][0] color_rgb[1][2][1] color_rgb[1][2][2]
		     color_rgb[1][3][0] color_rgb[1][3][1] color_rgb[1][3][2]
		     color_rgb[1][4][0] color_rgb[1][4][1] color_rgb[1][4][2]
		     color_rgb[1][5][0] color_rgb[1][5][1] color_rgb[1][5][2]
		     color_rgb[1][6][0] color_rgb[1][6][1] color_rgb[1][6][2]
		     color_rgb[1][7][0] color_rgb[1][7][1] color_rgb[1][7][2]
		     color_rgb[1][9][0] color_rgb[1][9][1] color_rgb[1][9][2]
		     shift_x shift_y scale_x scale_y starting_angle
             label_active[0] label_active[1]
		     eps_file_label[0] eps_file_label[1]
		     eps_filename[0] eps_filename[1]);

my @FormVariables = qw(delta begin_from_bottom number_of_labels
		    circle_radius[0][0] circle_radius[0][1]
		    circle_radius[0][2] circle_radius[0][3]
		    circle_radius[1][0] circle_radius[1][1]
		    circle_radius[1][2] circle_radius[1][3]
            radius_inner begin_from_left[0] begin_from_left[1]);

my $pi = 3.14159;
my $home = $ENV{'HOME'};

$configurationfile[0] = "/etc/cd-circleprint.conf";
$configurationfile[1] = $home."/\.cd-circleprint.conf";

# read the command-line for any options

my $params;

GetOptions (
      'config=s' =>  \$params->{'conf_file'},
      'version'  =>  \$params->{'version'},
      'debug+'   =>  \$debug,
      ) ;

if ($params->{'version'}) {
  print ("cd-circleprint $VERSION\n");
  print ("http://sourceforge.net/projects/cd-circle-print/\n");
  exit 0;
}
      
if ($params->{'conf_file'}) {
  $configurationfile[2] = $params->{'conf_file'};
}

# Build a list of available fonts and their Postscript names

my $tmppath = qx'xset q | awk "/Font Path:/ { i=1 ; next } i==1 { print \$0 ; i=0 }"';
while (defined ($tmppath)) {
  ($fontpath, $tmppath) = split /,/, $tmppath, 2;
  last if ($fontpath =~ /Type1/);
}
my $fontdir = $fontpath . "/fonts.dir";
open (FONTD, "<$fontdir") ||
    die "Can't Open font dir file: $!";
my $strg = <FONTD>;
$strg = <FONTD>; # skip the count record
while (defined($strg)) {
  my ($ffa, $ffb, $ffc, $ffd);
  ($ffa, $ffb, $ffc) = split /-/, $strg;
  $ffa =~ s/pfb/afm/;
  my $fontfn = $fontpath . "/" . $ffa;
  my $flag = 0;
  unless (open (FONTA, "<$fontfn"))
      {print "Sorry, there is no corresponding afm file\n"; $flag = 1;}
  if ($flag == 0) {
    $strg = <FONTA>;
    while (defined($strg)) {
      chomp $strg;
      ($ffb, $ffd) = split / /, $strg, 2;
      last if ($ffb =~ /^FontName/);
      $strg = <FONTA>;
    }
    close (FONTA);
    $fonthash{$ffd} = $ffc;
  }
  $strg = <FONTD>;
}
close (FONTD);

# set the system defaults

defaults();
default_attributes();
default_text();
default_colors();

read_configuration();

propogate_colors();

# then we need the main-window
my $mw = MainWindow -> new;
$mw -> title("cd-circleprint");
# Something which some window managers seem to need
$mw -> geometry("+0+0");

# some key-bindings
# We want to exit the program with Ctrl-q
$mw -> bind("<Control-q>", [sub {&clean_exit}]);
$mw -> bind("<Control-l>", [sub {&print_label}]);
$mw -> bind("<Control-p>", [sub {&preview}]);
$mw -> bind("<Control-s>", [sub {&write_configuration}]);

# Now we want a frame at the top of the window for the menus
my $menu_frame = $mw -> Frame(-relief => 'raised', -bd => 2) -> pack(-side => 'top',
								  -fill => 'both',
								  -anchor => 'n');

$menu_frame -> Menubutton(-text => "File",
                          -underline => 0, -tearoff => 0,
			  -menuitems => [
					 ['command' => "New",
					  -command => \&new_label,
					  -underline => 0],
					 ['command' => "Open",
					  -command => \&open_label,
					  -underline => 0],
					 ['command' => "Save",
					  -command => \&save_label,
					  -underline => 0],
					 ['command' => "Save As",
					  -command => \&save_as,
					  -underline => 5],
					 "-",
					 ['command' => "Load Form Data",
					  -command => \&read_form_data,
					  -underline => 0],
					 ['command' => "Save Form Data",
					  -command => \&write_form_data,
					  -underline => 10],
					 "-",
					 ['command' => "Save Image",
					 -command => \&save_ps_file,
					  -underline => 5],
					 "-",
					 ['command' => "Preview",
					  -command => \&preview,
					  -underline => 0],
					 "-",
					 ['command' => "Exit",
					  -command => sub{&clean_exit;},
					  -underline => 1]
				       ]) -> pack(-side => 'left');

$menu_frame -> Menubutton(-text => "Format",
					      -underline => 3, -tearoff => 0,
			  -menuitems => [
                     ['command' => "Fonts and Colours",
			          -command => \&get_fontattributes,
			          -underline => 0],
                     ['command' => "Angle",
			          -command => \&get_starting_angle,
			          -underline => 0],
                     ['command' => "Radii",
			          -command => \&set_circle_radius,
			          -underline => 3],
                     ['command' => "Page Deformation",
			          -command => \&set_page_scaling,
			          -underline => 0],
                     ['command' => "Positions",
			          -command => \&set_positions,
			          -underline => 0],
					 "-",
                     ['checkbutton' => "Top label",
				      -variable => \$label_active[1],
			          -command => \&select_labels,
                      -underline => 0],
                     ['checkbutton' => "Bottom label",
				      -variable => \$label_active[0],
			          -command => \&select_labels,
                      -underline => 0],
					 "-",
                     ['checkbutton' => "Tick Marks",
				      -variable => \$tickmarks,
                      -underline => 0],
                     ['checkbutton' => "Circle Boundaries",
				      -variable => \$print_circle_boundaries,
                      -underline => 0],
					 "-",
                     ['command' => "Graphics",
			          -command => \&get_graphics,
			          -underline => 0]
				       ]) -> pack(-side => 'left');

$menu_frame -> Menubutton(-text => "Options",
					      -underline => 0, -tearoff => 0,
			  -menuitems => [
                     ['command' => "Previewer",
			          -command => \&get_previewer,
			          -underline => 0],
                     ['command' => "Graphics converter",
			          -command => \&get_converter,
			          -underline => 0],
					 "-",
                     ['command' => "Load options",
			          -command => \&read_configuration,
			          -underline => 0],
                     ['command' => "Save options",
			          -command => \&write_configuration,
			          -underline => 0]
				       ]) -> pack(-side => 'left');

$menu_frame -> Menubutton(-text => "Help",
				          -underline => 0, -tearoff => 0,
			  -menuitems => [
                     ['command' => "Help",
		              -command => \&help_window,
		              -underline => 0],
                     ['command' => "About",
		              -command => \&about_window,
		              -underline => 0]
				       ]) -> pack(-side => 'left');

#$menu_frame -> Button(-text => "label", -command => \&print_label) -> pack(-side => 'left');
$menu_frame -> Button(-text => "Preview", -command => \&preview) -> pack(-side => 'left');

# Test for Canvas don't use it
#$menu_frame -> Button(-text => "CANVAS", -command => \&create_canvas) -> pack(-side => 'left');

#
# Now we create two frames for the text-entry widgets
#

$circle_frame = $mw -> Frame(-label => "Circles",
			     -borderwidth => 4,
			     -relief => 'groove') -> pack(-side => 'top',
			                                  -expand => 1,
							  -fill => 'both');

$text_frame = $mw -> Frame(-label => "Textfields",
			   -borderwidth => 4,
			   -relief => 'groove') -> pack(-side => 'bottom',
			                                -expand => 1,
							-fill => 'both');

# First two frames for the circles

$circle_text_frame[0] = $circle_frame -> Frame(-label => "Bottom label",
			                       -borderwidth => 2,
			                       -relief => 'groove') -> pack(-side => 'left',
					                                    -fill => 'both',
			                                                    -expand => 1);
$circle_text_frame[1] = $circle_frame -> Frame(-label => "Top label",
			                       -borderwidth => 2,
			                       -relief => 'groove') -> pack(-side => 'left',
					                                    -fill => 'both',
			                                                    -expand => 1);

# Then two for the textfields

$textfield_frame[0] = $text_frame -> Frame(-label => "Bottom label",
			                   -borderwidth => 2,
			                   -relief => 'groove') -> pack(-side => 'left',
					                                -fill => 'both',
			                                                -expand => 1);
$textfield_frame[1] = $text_frame -> Frame(-label => "Top label",
			                   -borderwidth => 2,
			                   -relief => 'groove') -> pack(-side => 'left',
					                                -fill => 'both',
			                                                -expand => 1);


# Now create the widgets for the text

for ( my $j=0; $j < $number_of_labels; $j++) {
  for (my $i=0; $i < 4; $i++ ) {
    $textfield_entry[$j][$i] = $textfield_frame[$j] -> Entry(-textvariable => \$text[$j][$i+4])
                                                    -> pack( -ipadx => 10, -ipady => 10 );

    $entry[$j][$i] = $circle_text_frame[$j] -> Entry(-textvariable => \$text[$j][$i])
                                            -> pack( -ipadx => 10, -ipady => 10 );

    $font[$j][$i] = $entry[$j][$i] -> fontCreate();
    $font[$j][$i+4] = $textfield_entry[$j][$i] -> fontCreate();

    configure_font($j, $i);
    configure_font($j, $i+4);
  }
}

$ct_clear[0] = $circle_text_frame[0] -> Button(-text => "clear",
				-command => sub{clear_circle_text (0)} ) -> pack();
$ct_clear[1] = $circle_text_frame[1] -> Button(-text => "clear",
				-command => sub{clear_circle_text (1)} ) -> pack();

$tf_clear[0] = $textfield_frame[0] -> Button(-text => "clear",
				-command => sub{clear_textfields (0)} ) -> pack();
$tf_clear[1] = $textfield_frame[1] -> Button(-text => "clear",
				-command => sub{clear_textfields (1)} ) -> pack();

# Was a Label filename specified?

if (defined $ARGV[0]) {
  $label_fn = $ARGV[0];
  read_label();
  reconfigure_fonts();
}

update_display();

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

MainLoop;

clean_exit();

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

sub clean_exit {

  if ($pidsav != 0 ) {
    `kill -USR1 $pidsav`;
  }

  exit;

}
#######################
# Very incomplete :-(
#
#sub create_canvas {
# First we need a new Window to show the objects

# my $canvas;

# my $cmw = $mw->Toplevel();

#  $cmw -> title("Move oobjects of the labels");
#  $canvas = $cmw -> Scrolled('Canvas')->pack(  );

# The inner circle
#my $inner_crcle = $canvas->createOval(10,10,100,100, -extent => 360);


#}

#######################
sub add_font_from_entry {

  $fontlistbox -> insert('end', $fontentry -> get() );
  push(@fontnames,$fontentry -> get());
}

#######################
sub reconfigure_fonts {

  for ( my $j=0; $j < $number_of_labels; $j++) {
    for (my $i=0; $i < 4; $i++ ) {
      configure_font($j, $i);
      configure_font($j, $i+4);
    }
  }
}

#######################
sub open_label {

  my $OLref;
  my $olfile;
  my $home = $ENV{'HOME'};

  $OLref = $mw -> FileSelect(-directory => $home, -title => 'Open',
                             -filter => '[^.]*', -acceptlabel => 'Ok');
  $olfile = $OLref -> Show;

  if ((defined $olfile) && ($olfile ne "")) {
    $label_fn = $olfile;
    read_label();
    reconfigure_fonts();
    update_display();
  }
}

#######################
sub new_label {

  clear_circle_text(0);
  clear_circle_text(1);
  clear_textfields(0);
  clear_textfields(1);
  default_colors();
  default_attributes();
  propogate_colors();
  update_display();

# and also the filename so we don't accidentally overwrite something

  undef $label_fn;
}

#######################
sub clear_circle_text {
  my $j = shift;

  for (my $i=0; $i < 4; $i++ ) {
    $text[$j][$i] = "";
    $entry[$j][$i] -> configure(-text);
  }
}

#######################
sub clear_textfields {
  my $j = shift;

  for (my $i=0; $i < 4; $i++ ) {
    $text[$j][$i+4] = "";
    $textfield_entry[$j][$i] -> configure(-text);
  }
}
#######################
sub configure_font {

  my ($ffamily, $fweight, $fslant);
  my $j = shift;
  my $i = shift;

  $ffamily = $fonthash{$fontfamily[$j][$i]};
  $fweight = "normal";
  $fslant = "roman";

  if (($fontfamily[$j][$i] =~ /bold/i) ||
      ($fontfamily[$j][$i] =~ /dark/i)) {
    $fweight = "bold";
  }

  if (($fontfamily[$j][$i] =~ /italic/i) ||
      ($fontfamily[$j][$i] =~ /oblique/i)) {
    $fslant = "italic";
  }

  if ($i < 4) {
    $entry[$j][$i] -> fontConfigure($font[$j][$i],
					       -size => $fontsize[$j][$i],
                           -weight => $fweight,
                           -slant => $fslant,
					       -family => $ffamily);

    $entry[$j][$i] -> configure(-font => $font[$j][$i]);
  }
  else {
    $textfield_entry[$j][$i-4] -> fontConfigure($font[$j][$i],
					       -size => $fontsize[$j][$i],
                           -weight => $fweight,
                           -slant => $fslant,
					       -family => $ffamily);

    $textfield_entry[$j][$i-4] -> configure(-font => $font[$j][$i]);
  }
}

#######################
sub propogate_colors {

my $color;

  $color = "#";
  for (my $l = 0; $l < $number_of_labels; $l++) {
    for (my $w = 0; $w <= $number_of_background; $w++) {
      $ps_color[$l][$w] = " " . $color_rgb[$l][$w][0] / 255  
                              ." " .$color_rgb[$l][$w][1] / 255 ." ".$color_rgb[$l][$w][2] / 255 ;
      $color = "#";
      for (my $i=0; $i < 3; $i++) {
        $color .= sprintf("%02x",$color_rgb[$l][$w][$i]);
      }
      $tk_color[$l][$w] = $color;
    }
  }
}

#######################
sub default_colors {

#set everything to Black

  for (my $l = 0; $l < $number_of_labels; $l++) {
    for ($which_field = 0; $which_field <= $number_of_background; $which_field++) {
      $ps_color[$l][$which_field] = " 0 0 0 ";
      for (my $j=0; $j<3; $j++) {
        $color_rgb[$l][$which_field][$j] = 0;
      }
      $tk_color[$l][$which_field] = "#000000";
    }
  }

# Now the background in white

  $which_field =  $number_of_background;
  for (my $l = 0; $l < $number_of_labels; $l++) {
    $ps_color[$l][$which_field] = " 1 1 1 ";
    for (my $j=0; $j<3; $j++) {
      $color_rgb[$l][$which_field][$j] = 255;
    }
    $tk_color[$l][$number_of_background] = "#ffffff";
  }

  $which_field = 0;
  $rgb[0] = $rgb[1] = $rgb[2] =0;
}

#######################
sub defaults {

  # Name of the resulting PS-file
  $psfile = "/tmp/cd-circleprint.ps";

  # Number of labels on a sheet (very incomplete use of this variable)
  $number_of_labels = 2;

  # All labels active
  $label_active[0] = 1;
  $label_active[1] = 1;

  # A variable to define the backround which is treated as an additional circle or textfield
  $number_of_background = 9;

  # which previewer
  check_viewer("gv");
  $pidsav = 0;

  # which converter
  $converter = "convert";

  # debug level
  $debug = 0;

  # defaults for the circles in mm
  $radius_outer = 60;
  $radius_inner = 21;

  $starting_angle = 0;

  # defaults for the radii of the text circles
  $circle_radius[0][0] = $circle_radius[1][0] = $radius_outer - 10;
  $circle_radius[0][1] = $circle_radius[1][1] = $radius_outer - 19;
  $circle_radius[0][2] = $circle_radius[1][2] = $radius_outer - 19;
  $circle_radius[0][3] = $circle_radius[1][3] = $radius_outer - 10;

  # yes, we want the the circle boundaries
  $print_circle_boundaries = 1;

  # Yes we want tickmarks as defaults
  $tickmarks = 1; 
  
  # defaults for the distance pageborder circles
  # distance between the circles
  $delta = 20;
  # distance from the bottom of the page
  $begin_from_bottom = 10;

  # distance from the left side of the page
  for (my $l = 0; $l < $number_of_labels; $l++ ) {
    $begin_from_left[$l] = 40;
  }

  $x_origin = $begin_from_left[0] + $radius_outer;
  $y_origin = $begin_from_bottom + $radius_outer;

  $x_scale = 1;
  $y_scale = 1;

  $scale_x = 1;
  $scale_y = 1;

  $shift_y = 0;
  $shift_x = 0;

  $label_id = 0;

  $graphics_directory = "/usr/share/cd-circleprint/";
  for ( my $i=0; $i < $number_of_labels; $i++) {
    $shift_eps_x[$i] = 0;
    $shift_eps_y[$i] = 0;
    $scale_eps_x[$i] = 1;
    $scale_eps_y[$i] = 1;
    $eps_file_label[$i] = 0;
    $eps_filename[$i] = "";
  }
}

#######################
sub check_viewer {

  my $fn = $_[0];

  if (-x $fn) {
    $viewer = $fn;
    return;
  }
  
  for my $dir (split /:/, $ENV{PATH}) {
    my $file = "$dir/$fn";
    if ( -x $file) {
      $viewer = $file;
      last;
    }
  }

  return;
}

########################
sub default_attributes {
  # fontsizes
  @fontsize = ( [qw (32 18 18 32 16 16 16 16) ], [qw (32 18 18 32 16 16 16 16)]);

  my $ctr = 0;
  foreach my $ffc (sort keys %fonthash) {
    $fontnames[$ctr] = $ffc;
    $ctr++;
  }

  for (my $j=0; $j < $number_of_labels; $j++ ) {
    for (my $i=0; $i < 8; $i++ ) {
      $fontfamily[$j][$i] = $fontnames[0];
    }
  }
}

########################
sub default_text {

  # The entries for the circle text

  $text[0][0] = "CD-Circleprint";
  $text[0][1] = "";
  $text[0][2] = "";
  $text[0][3] = "";

  $text[1][0] = "www.debian.org";
  $text[1][1] = "GNU/Linux GNU/Hurd";
  $text[1][2] = "";
  $text[1][3] = "The FREE distribution";

  # The entries for the straight text
  
  $text[0][4] = "$VERSION";
  $text[0][5] = " ";
  $text[0][6] = " ";
  $text[0][7] = " ";

  $text[1][4] = " ";
  $text[1][5] = " ";
  $text[1][6] = " ";
  $text[1][7] = " ";
}

#####################
sub modify_color {

#
# capture the new colour in all 3 formats that we need
#

  my $color = "#";
  
  for (my $i=0; $i < 3; $i++) {
    $color_rgb[$label_id][$which_field][$i] = $rgb[$i];
    $color .= sprintf("%02x",$rgb[$i]);
  }

  $tk_color[$label_id][$which_field] = $color;

  $ps_color[$label_id][$which_field] = " " . $rgb[0] / 255  ." " .$rgb[1] / 255 ." ".$rgb[2] / 255 ;

# make the color selector window follow the chosen color

  $fff -> configure(-background => $tk_color[$label_id][$which_field]);
  
  update_display();
}

########################
sub update_display {

  my ($i, $j);

# first do all the text fields

  for ($j = 0; $j < $number_of_labels; $j++) {
    for ($i = 0; $i < 4; $i++) {
      $entry[$j][$i] -> configure(-foreground => $tk_color[$j][$i]);
      $textfield_entry[$j][$i] -> configure(-foreground => $tk_color[$j][$i+4]);
      if ($label_active[$j]) {
        $entry[$j][$i] -> configure(-state => 'normal');
        $textfield_entry[$j][$i] -> configure(-state => 'normal');
      } else {
        $entry[$j][$i] -> configure(-state => 'disabled');
        $textfield_entry[$j][$i] -> configure(-state => 'disabled');
      }
    }
  }

#
# Then the backgrounds
#
  for ($j = 0; $j < $number_of_labels; $j++) {
    for ( $i=0; $i < 4; $i++) {
      $entry[$j][$i] -> configure(-background => $tk_color[$j][$number_of_background]);
      $textfield_entry[$j][$i] -> configure(-background => $tk_color[$j][$number_of_background]);
    }
  }
}

########################
sub set_selectors {

  if ( $which_field < $number_of_background) {
#   set the fontsize
    $scale = $fontsize[$label_id][$which_field];

#   display the right entry in the fontlistbox
    foreach (0 .. $#fontnames ) {
      if ( $fontnames[$_] eq $fontfamily[$label_id][$which_field]) {
	$fontlistbox -> selectionClear(0, "end");
	$fontlistbox -> selectionSet($_);
	$fontlistbox -> see($_);
      }
    }
  }
# set the colours
  $rgb[0] = $color_rgb[$label_id][$which_field][0];
  $rgb[1] = $color_rgb[$label_id][$which_field][1];
  $rgb[2] = $color_rgb[$label_id][$which_field][2];

# and the colour selector background
  $fff -> configure(-background => $tk_color[$label_id][$which_field]);
}

########################
sub display_graphics_file_attributes {
  my $i;
  for ( $i = 0; $i < $number_of_labels ;$i++) {
    if ( $eps_file_label[$i]) {

      $shift_x = $shift_eps_x[$i];
      $shift_y = $shift_eps_y[$i];
      $scale_x = $scale_eps_x[$i];
      $scale_y = $scale_eps_y[$i];
    }
  }
}
########################
sub help_window {

# Very very ugly , but the pod Module can only handle STDOUT or Filehandle

  my $parser = Pod::Text->new;
  my $tmp_file_name = "/tmp/cd-circle_print.man.1";
  $parser->parse_from_file ($0, $tmp_file_name);

  my $help_dialog = $mw->DialogBox(-title => 'Help', -buttons => ['OK'], -default_button => 'OK');
  my $text = $help_dialog -> Scrolled("Text", -scrollbars => 'oe') -> pack;

  open (TMP_FILE,"<$tmp_file_name") or (return());
  while ( <TMP_FILE>) {
    $text -> insert('end',$_);
  }
  close (TMP_FILE);
# We should delete the tmp-file

# fix needed to get around locking waitVariable() call, which is never unblocked when the dialog is destroyed.
  $help_dialog->OnDestroy(sub { $help_dialog->{'selected_button'} = $help_dialog->{'selected_button'} });

  $help_dialog->Show();
}

########################
sub about_window {

  my $about_box = $mw->DialogBox(-title => 'About', -buttons => ['OK'], -default_button => 'OK');

  my $text = $about_box -> Text() -> pack;

  $text -> insert('end', "cd-circleprint version: $VERSION\n\n");
  $text -> insert('end', "a simple perl script by Colin Tuckley <colintu\@users.sourceforge.net>\n");
  $text -> insert('end', "originally written by Matthias Kabel <matthias.kabel\@tyche.de>\n");
  $text -> insert('end', "The following people have sent patches which improved the program:\n\n" );
  $text -> insert('end', "* Dave Regan <regan\@ao.com>\n\n");
  $text -> insert('end', "cd-circleprint is published under the GNU public license\n");
  $text -> insert('end', "You should have this license in your distribution\n");
  $text -> insert('end', "If you don't, write to the Free Software Foundation, Inc., \n");
  $text -> insert('end', "51 Franklin St, Fifth Floor, Boston, MA  02110-1301, USA.\n\n");
  $text -> tagConfigure('red', -foreground => "#ff0000");
  $text -> insert('end',"May the source be with you", 'red');

# fix needed to get around locking waitVariable() call, which is never unblocked when the dialog is destroyed.
  $about_box->OnDestroy(sub { $about_box->{'selected_button'} = $about_box->{'selected_button'} });

  $about_box->Show();
}

########################
sub read_label {

  if (-f $label_fn) {
    if (-r $label_fn) {
      open (LABEL_FILE, "< $label_fn");
      while (<LABEL_FILE>) {
        next unless /(^\w+.*)\s+(.*$)/; # skip comments and empty lines
        $_ =~ /(\S*?)\s+(.*)/; #(\#.*$)/; #!!!!!!!!!!!!!
        evaluate_data ($1, $2, \@LabelVariables);
      }
      close (LABEL_FILE);
    }
  }
  set_graphics_attributes();
  propogate_colors();
}

########################
sub read_configuration {

# we start reading the different configuration files

  foreach my $i (@configurationfile) {
    if (-f $i) {
      if (-r $i) {
        open (CONF_FILE, "< $i");
        while (<CONF_FILE>) {
          next unless /(^\w+.*)\s+(.*$)/; # skip comments and empty lines
          $_ =~ /(\S*?)\s+(.*)/; #(\#.*$)/; #!!!!!!!!!!!!!
          evaluate_data ($1, $2, \@SaveVariables);
        }
        close (CONF_FILE);
      }
      else {
        print "Error: unable to open configuration file $i for reading\n";
      }
    }
  }
  set_graphics_attributes();
}

########################
sub evaluate_data {

# much improved by Dave Regan

  my $var = $_[0];
  my $value = $_[1];
  my $ref = $_[2];
  my %symtab = map { $_, $_} @$ref;

  if (defined($symtab{$var})) {
     my($eval) = qq|\$$var = "$value"|;
     eval $eval;
   }
}

########################
sub read_form_data {

my $FSref;
my $home = $ENV{'HOME'};

$FSref = $mw -> FileSelect(-directory => $home, -title => 'Read Form Data',
                           -filter => '[^.]*', -acceptlabel => 'Ok');
my $fdfile = $FSref -> Show;

  if ((defined $fdfile) && ($fdfile ne "")) {
    open (FD_FILE, "<$fdfile") || die ("Could not open $fdfile\n");
    while (<FD_FILE>) {
      next unless /(^\w+.*)\s+(.*$)/;
      $_ =~ /(\S*?)\s+(.*)/; #(\#.*$)/;
      evaluate_data ($1, $2, \@FormVariables);
    }
    close (FD_FILE);
  }
}

########################
sub preview {

  my $pid;
  
# first we want a new label
  print_label();

# next kill any previous viewer
  if ($pidsav != 0 ) {
    `kill -USR1 $pidsav`;
    $pidsav = 0;
  }

# check viewer is executable

  if ( -x $viewer) {

# then fork to the viewer

    if ($pid = fork) {
      $pidsav = $pid;   # we are the parent so save child pid
      return;
    }
    elsif (defined $pid) {
      exec $viewer, $psfile;
    }
  }
  
# if we get here then an error occured

my $warn => $mw->messageBox( -title => 'Error',
                             -message => 'Error attempting to start previewer',
			     -type => 'OK');

  return;
}

########################
sub print_circles {

    my $epsname;
    my $name;
    my $dir;
    my $ext;
    my $path;
    my $label_no;

  print PS_FILE "%%Page: 1 1\n\n"; # beginning of page

  print PS_FILE "gsave\n";

  for ($label_no = 0; $label_no < $number_of_labels; $label_no++) {

    print PS_FILE "$x_origin mm $y_origin mm translate \n"; # shift the origin of drawing

    # Set the clipping path
    print PS_FILE "gsave\n";
    print PS_FILE "0 0 $radius_outer mm 0 360 arc clip\n";

    if ($label_active[$label_no]) {

    # First we need the circles in the background color
    print PS_FILE "$ps_color[$label_no][$number_of_background] setrgbcolor\n";
    print PS_FILE "0 0 $radius_outer mm 0 360 arc\n";
    print PS_FILE "fill\n";
    print PS_FILE "newpath\n";

    # Then we print the graphics
    if (($eps_file_label[$label_no]) && ($eps_filename[$label_no] ne "")) {
	  # check wether it is an eps-file
	  $epsname =`file $eps_filename[$label_no]`;
	  if ($epsname =~ /EPS/) {
	    print_graphics($eps_filename[$label_no],$label_no);
	  }
	  else {
	    $epsname = $eps_filename[$label_no];
	    ($name,$dir,$ext) = fileparse($epsname);
	    $epsname = "/tmp/".$name.".eps";
	    system "$converter $eps_filename[$label_no] $epsname";
	    print_graphics($epsname, $label_no);
	  }
    }

    # After that we need the small inner circle in white
    print PS_FILE "1 1 1 setrgbcolor\n";
    print PS_FILE "0 0  $radius_inner mm 0 360 arc\n";
    print PS_FILE "fill\n";
    print PS_FILE "newpath\n";

    # Ok, now we go with the text
    # Outer upper circle or textfield
    print PS_FILE "/$fontfamily[$label_no][0] reencodeISO def\n";
    print PS_FILE "/$fontfamily[$label_no][0] findfont\n"; # The font we want
    print PS_FILE "$fontsize[$label_no][0] scalefont setfont\n"; # scaling the font
    print PS_FILE "$ps_color[$label_no][0] setrgbcolor \n";
    print PS_FILE "($text[$label_no][0])", " ", $fontsize[$label_no][0], " ", -$starting_angle +90, " ",
                    $circle_radius[$label_no][0], " mm OutsideCircletext\n";

    # Inner upper circle or textfield
    print PS_FILE "/$fontfamily[$label_no][1] reencodeISO def\n";
    print PS_FILE "/$fontfamily[$label_no][1] findfont\n";
    print PS_FILE "$fontsize[$label_no][1] scalefont setfont\n";
    print PS_FILE "$ps_color[$label_no][1] setrgbcolor \n";
    print PS_FILE "($text[$label_no][1])", " ", $fontsize[$label_no][1], " ", -$starting_angle +90, " ",
                    $circle_radius[$label_no][1], " mm OutsideCircletext\n";

    # Inner lower circle or textfield
    print PS_FILE "/$fontfamily[$label_no][2] reencodeISO def\n";
    print PS_FILE "/$fontfamily[$label_no][2] findfont\n";
    print PS_FILE " $fontsize[$label_no][2] scalefont setfont\n";
    print PS_FILE "$ps_color[$label_no][2] setrgbcolor \n";
    print PS_FILE "($text[$label_no][2])", " ", $fontsize[$label_no][2], " ", -$starting_angle -90, " ",
                    $circle_radius[$label_no][2], " mm  InsideCircletext\n";

    # Outer lower circle or textfield
    print PS_FILE "/$fontfamily[$label_no][3] reencodeISO def\n";
    print PS_FILE "/$fontfamily[$label_no][3] findfont\n";
    print PS_FILE " $fontsize[$label_no][3] scalefont setfont\n";
    print PS_FILE "$ps_color[$label_no][3] setrgbcolor \n";
    print PS_FILE "($text[$label_no][3])", " ", $fontsize[$label_no][3], " ", -$starting_angle -90, " ",
                    $circle_radius[$label_no][3], " mm InsideCircletext\n";

    if ($print_circle_boundaries) {
      print PS_FILE "0 0 0 setrgbcolor\n";
      print PS_FILE "0 0  $radius_inner mm  0 360 arc\n";
      print PS_FILE "stroke\n";
      print PS_FILE "newpath\n";

      print PS_FILE "0 0 $radius_outer  mm 0 360 arc\n";
      print PS_FILE "stroke\n";
      print PS_FILE "newpath\n";
    }
    }
    print PS_FILE "grestore\n";

    $x_origin  = -$begin_from_left[$label_no];
    $x_origin += $begin_from_left[$label_no +1] if($begin_from_left[$label_no +1]);
    $y_origin  = $delta + 2*$radius_outer;
  }
  print PS_FILE "grestore\n";
}


########################
sub print_graphics {

  my $file = shift;
  my $label_no = shift;

  get_bounding_box($file); # Very inefficient, I have to change it

  $shift_eps_x[$label_no] += $Bounding_X / 2.8346;
  $shift_eps_y[$label_no] += $Bounding_Y / 2.8346;

  $shift_eps_x[$label_no] *= $scale_eps_x[$label_no];
  $shift_eps_y[$label_no] *= $scale_eps_y[$label_no];

  print PS_FILE "gsave\n";

  print PS_FILE "$shift_eps_x[$label_no] mm $shift_eps_y[$label_no] mm translate\n";
  print PS_FILE "$scale_eps_x[$label_no] $scale_eps_y[$label_no] scale\n";

  open (EPS_FILE,"<$file");
  while ( <EPS_FILE>) {
# We should scan the graphics file for "Showpage"
    unless ($_ =~ /showpage/) {print PS_FILE $_ ;}
  }
  close (EPS_FILE);

  print PS_FILE "\n\n grestore\n\n";

  $shift_eps_x[$label_no] /= $scale_eps_x[$label_no];
  $shift_eps_y[$label_no] /= $scale_eps_y[$label_no];

  $shift_eps_x[$label_no] -= $Bounding_X / 2.8346;
  $shift_eps_y[$label_no] -= $Bounding_Y / 2.8346;
}

########################
sub print_label{

  open (PS_FILE, ">$psfile") || die ("Could not open $psfile\n");

  $x_origin = $begin_from_left[0] + $radius_outer;
  $y_origin = $begin_from_bottom + $radius_outer;

  print_page_header();
  print_prolog();

  print_page_deformation();

  print_circles();
  print_textfields();
  if($tickmarks) {print_ticks();}

# now print the closing lines
  print PS_FILE "showpage\n";
  print PS_FILE "%%Trailer\n";
  print PS_FILE "%%Pages: 1\n";
  print PS_FILE "%%EOF\n";

  close (PS_FILE);
}

########################
sub print_page_deformation {

  print PS_FILE "%We want a deformatiopn of the page\n\n";
  print PS_FILE "$x_scale $y_scale scale\n";
  print PS_FILE "%End of deformation\n\n";
}

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

sub print_page_header {

print PS_FILE <<'END_OF_HEADER'
%!PS - Adobe -1.0
%%Creator: cd - label.pl
%%Title: cdlabel
%%CreationDate: Mo, 1.2.2001
%%DocumentMedia: A4 595 842 0 () ()
%%Orientation: Portrait
%%Pages: (atend)
%%DocumentFonts: Times - Roman Helvetica
%%EndComments

END_OF_HEADER

}

########################
sub print_prolog {

  print PS_FILE << 'END_OF_PROLOG'

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Reencode the font to support international characters.
%% This is taken from cdlabelgen where it is taken
%%  from GNUPlot 3.7 /term/next.trm
%% Free Software is a great thing, you can look around and use the good things
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

/reencodeISO {
  dup dup findfont dup length dict begin
	 { 1 index /FID ne { def }{ pop pop } ifelse } forall
	 /Encoding ISOLatin1Encoding def
	 currentdict end definefont
} def
	 
/ISOLatin1Encoding [ 
/.notdef/.notdef/.notdef/.notdef/.notdef/.notdef/.notdef/.notdef 
/.notdef/.notdef/.notdef/.notdef/.notdef/.notdef/.notdef/.notdef 
/.notdef/.notdef/.notdef/.notdef/.notdef/.notdef/.notdef/.notdef 
/.notdef/.notdef/.notdef/.notdef/.notdef/.notdef/.notdef/.notdef 
/space/exclam/quotedbl/numbersign/dollar/percent/ampersand/quoteright 
/parenleft/parenright/asterisk/plus/comma/minus/period/slash 
/zero/one/two/three/four/five/six/seven/eight/nine/colon/semicolon 
/less/equal/greater/question/at/A/B/C/D/E/F/G/H/I/J/K/L/M/N 
/O/P/Q/R/S/T/U/V/W/X/Y/Z/bracketleft/backslash/bracketright 
/asciicircum/underscore/quoteleft/a/b/c/d/e/f/g/h/i/j/k/l/m 
/n/o/p/q/r/s/t/u/v/w/x/y/z/braceleft/bar/braceright/asciitilde 
/.notdef/.notdef/.notdef/.notdef/.notdef/.notdef/.notdef/.notdef 
/.notdef/.notdef/.notdef/.notdef/.notdef/.notdef/.notdef/.notdef 
/.notdef/dotlessi/grave/acute/circumflex/tilde/macron/breve 
/dotaccent/dieresis/.notdef/ring/cedilla/.notdef/hungarumlaut 
/ogonek/caron/space/exclamdown/cent/sterling/currency/yen/brokenbar 
/section/dieresis/copyright/ordfeminine/guillemotleft/logicalnot 
/hyphen/registered/macron/degree/plusminus/twosuperior/threesuperior 
/acute/mu/paragraph/periodcentered/cedilla/onesuperior/ordmasculine 
/guillemotright/onequarter/onehalf/threequarters/questiondown 
/Agrave/Aacute/Acircumflex/Atilde/Adieresis/Aring/AE/Ccedilla 
/Egrave/Eacute/Ecircumflex/Edieresis/Igrave/Iacute/Icircumflex 
/Idieresis/Eth/Ntilde/Ograve/Oacute/Ocircumflex/Otilde/Odieresis 
/multiply/Oslash/Ugrave/Uacute/Ucircumflex/Udieresis/Yacute 
/Thorn/germandbls/agrave/aacute/acircumflex/atilde/adieresis 
/aring/ae/ccedilla/egrave/eacute/ecircumflex/edieresis/igrave 
/iacute/icircumflex/idieresis/eth/ntilde/ograve/oacute/ocircumflex 
/otilde/odieresis/divide/oslash/ugrave/uacute/ucircumflex/udieresis 
/yacute/thorn/ydieresis
] def

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Now calculate mm and points
/mm { 72 mul 25.4 div}  def

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% A function to print the textfields properly
% As you can see, this code is taken from somewhere
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Zeilenumbruch

/Wordbreak ( ) def               % Trennzeichen zwischen Worten (Leerzeichen)

% BreaklntoLines umbricht einen Text-String in Zeilen vorgegebener Laenge. Die
% Prozedur benoetigt 3 Parameter: Den Text-String, die Satzbreite und die Pro-
% zedur, die aufgerufen wird, wenn das Ende der Zeile erreicht ist. Diese Pro-
% zedur erhaelt die aktuelle Zeile als Argument auf dem Stack.
/BreakIntoLines
{ /Proc exch def
  /Linewidth exch def            % Satzbreite
  /Textstring exch def
  /Breakwidth Wordbreak          % Breite des Leerezeichens im aktuellen Font
  stringwidth pop def
  /Curwidth 0 def                % Die Breite der laufenden Zeile
  /LastWordbreak 0 def           % Index zum letzten Leerzeichen
  /Startchar 0 def               % Index zum ersten Zeichen der laufenden Zeile
  /RestOfText Textstring def     % Unverarbeiteter Rest des Textes
  
  { RestOfText
    Wordbreak search             % search sucht nach dem ersten Leerzeichen und
    { /Nextword exch def pop     % liefert, falls erfolgreich, das Wort vor dem
      /RestOfText exch def       % Leerzeichen und den restlichen Text
      /Wordwidth Nextword        % Breite des Wortes
      stringwidth pop def
      Curwidth Wordwidth add
      Linewidth gt               % Passt das Wort noch in die Zeile?
      { Textstring Startchar     % Nein. Laufende Zeile als Parameter an Proc
        LastWordbreak            % uebergeben (Zeile ausgeben) und Variablen
   Startchar sub                 % fuer naechste Zeile initialisieren.
   getinterval Proc
   /Startchar
   LastWordbreak def
   /Curwidth Wordwidth
   Breakwidth add def
      }
      { /Curwidth Curwidth       % Ja: Wort in laufende Zeile aufnehmen.
        Wordwidth add
   Breakwidth add def
      } ifelse
      /LastWordbreak
      LastWordbreak Nextword     % Index zum letzten Leerzeichen um ein Wort
      length add 1 add def       % weiterschieben
    }
    { pop exit } ifelse          % Kein blank mehr gefunden: Schleifenende.
  } loop
  /Lastchar                      % Nicht vergessen: letzte Zeile ausgeben
  Textstring length def
  Textstring Startchar
  Lastchar Startchar sub
  getinterval Proc
} def

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Center a string
/center {dup stringwidth pop 2 div neg 0 rmoveto} bind def

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Now the real thing for the circles
%
% I got this from Adobes
%  Blue Book
%  Program 10, on page 167
%  Adobe Systems Incorporated 
%  CreationDate: Thu Dec 28 13:14:59 PST 1989
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

/OutsideCircletext
{ CirctextDict begin             % This routine needs four arguments
    /Radius exch def             % radius of the circle
    /Centerangle exch def        % angle of the starting point
    /PtSize exch def             % fontsize in points
    /Str exch def                % and the text
    /XRadius Radius              % To get better results we use a little bigger radius
    PtSize 4 div add def         % for the distance between the letters
                                 %
    gsave                        % save actual Graphics State
    Centerangle Str
    FindHalfangle add rotate

    Str
    { /Charcode exch def
      ( ) dup 0 Charcode put
      Outsideplacechar
    } forall
    grestore                     % restore Graphics State
  end
} def

/InsideCircletext
{ CirctextDict begin             % 'Insidecircletext' needs the same four arguments
    /Radius exch def             % as 'Outsidecircletext'
    /Centerangle exch def
    /PtSize exch def
    /Str exch def
    /XRadius                     % To get better results we use a little smaller radius
    Radius PtSize 3 div sub      % for the distances between the lines
    def
    gsave
    Centerangle Str
    FindHalfangle sub rotate
    Str
    { /Charcode exch def
      ( ) dup 0 Charcode put
      Insideplacechar
    } forall
    grestore
  end
} def

/CirctextDict 16 dict def
CirctextDict begin
  /FindHalfangle                 % 'FindHalfangle' calculates the length of a string
  { stringwidth pop 2 div        % on the circle
    2 XRadius mul Pi mul div     % The calculation divides the length of the text
    360 mul                      % by the circumference of the circle. Half of the result
  } def                          % will be put on the stack

  /Outsideplacechar              % put one character on outside of the arc
  { /Char exch def               % and rotate the width of the character
    /Halfangle
    Char FindHalfangle def
    gsave
    Halfangle neg rotate         % rotate the coordinate system a half width of the character
    Radius 0 translate           %
    -90 rotate                   % senkrecht zur Kreislinie stellen.
    Char stringwidth pop         % Zeichen zentriert bzgl. des Ursprungs posit.
    2 div neg 0 moveto
    Char show
%   Char true charpath stroke    % This would show outline fonts
    grestore                     % restore the old system
    Halfangle 2 mul neg rotate   % rotate forward for one characterwidth
  } def

  /Insideplacechar               % 'Insideplacechar' works like
  { /Char exch def               % 'Outsideplacechar', but the characters are placed
    /Halfangle                   % inside of the circle and counterclockwise
    Char FindHalfangle def
    gsave
    Halfangle rotate
    Radius 0 translate
    90 rotate
    Char stringwidth pop
    2 div neg 0 moveto
    Char show
    grestore
    Halfangle 2 mul rotate
  } def

  /Pi 3.1415923 def
end

%%EndProlog

END_OF_PROLOG

}

########################
sub print_textfields {

  my $i;
  my $x_position;
  my $y_position;
  my $label_no;

  my @textwidth = qw(70 40 70 40);

  for ( $i=0; $i < 4; $i++) {
    for ($label_no=0; $label_no < $number_of_labels; $label_no++  ) {
     if ($label_active[$label_no]) {
      $x_position = $begin_from_left[$label_no]  + $radius_outer + sin($i * $pi/2) *(($radius_outer -$radius_inner)/2);
      if ($debug) {print "print_textfields::X-pos=", $x_position, "\n";}
      $x_position += 5 if ($i == 1);
      $x_position =  $begin_from_left[$label_no]  +5  if ($i == 3); # shift the x-position right
      if ($debug) {print "print_textfields::label:x $label_no: $x_position\n";}
      $y_position = $begin_from_bottom + $radius_outer + cos($i * $pi/2)*($radius_outer + $radius_inner)/2
                    + ($delta+2*$radius_outer)* sin($label_no * $pi/2);

      print PS_FILE "/$fontfamily[$label_no][$i+4] reencodeISO def\n";
      print PS_FILE "/$fontfamily[$label_no][$i+4] findfont\n"; # The font we want
      print PS_FILE "$fontsize[$label_no][$i+4] scalefont setfont\n"; # scaling the font
      print PS_FILE "$ps_color[$label_no][$i+4] setrgbcolor\n"; # setting the color
      my $t = $text[$label_no][$i+4]; # Get the text to print

      if (defined $t) {
        print PS_FILE "/YLine $y_position mm def\n"; # We need this for the linebreak	
        print PS_FILE "(", $t,")\n";
        print PS_FILE "$textwidth[$i] mm \n";
        print PS_FILE "{\n$x_position mm YLine moveto\n";
        # Ok, here we are, we have to correct the current point by half of
        # the fontsize
        print PS_FILE "\n0 -", $fontsize[$label_no][$i+4]/2 , " rmoveto\n";
        # Only the textfields above and below the hole in the middle should be centered
        if ($i == 0 || $i ==2) {
          print PS_FILE "center ";
        }
        print PS_FILE "show\n";
        print PS_FILE "/YLine YLine ", $fontsize[$label_no][$i+4], " sub def \n }\n BreakIntoLines\n\n";
        print PS_FILE "%The next textfield\n";
      }
     }
    }
  }
}

########################
sub print_ticks {

  my ($i, $tick);
  my $label_no;
  my ($left, $right, $minleft, $maxleft);

  my $x_origin = 0;
  my $y_origin = 0;

  $minleft = (($begin_from_left[0] <=> $begin_from_left[1]) == 1) ? $begin_from_left[1] : $begin_from_left[0]; 
  $maxleft = (($begin_from_left[0] <=> $begin_from_left[1]) == 1) ? $begin_from_left[0] : $begin_from_left[1]; 

  print PS_FILE $minleft / 2 ," mm ", 2*$radius_outer + $delta / 2 + $begin_from_bottom , " mm moveto\n";
  print PS_FILE "gsave\n";
  print PS_FILE "/Helvetica findfont 12 scalefont setfont\n";
  print PS_FILE "90 rotate\n";
  print PS_FILE "(The tickmarks are in mm) center show\n";
  print PS_FILE "grestore\n";
  print PS_FILE "gsave\n";
  print PS_FILE "newpath\n";
  print PS_FILE "/Helvetica findfont 12 scalefont setfont\n";
  print PS_FILE $minleft / 2 + 8," mm ", 2*$radius_outer + $delta / 2 + $begin_from_bottom , " mm moveto\n";
  print PS_FILE "90 rotate\n";
  print PS_FILE "(All comments to colintu\@users.sourceforge.net please) center show\n";
  print PS_FILE "grestore\n";

  print PS_FILE "gsave\n";
  print PS_FILE "/Helvetica findfont 14 scalefont setfont\n"; #Fontsize for the label
  print PS_FILE "$x_origin mm  $y_origin mm translate\n"; # origin of drawing to the middle

  print PS_FILE "newpath\n";

  # Now we want some tickmarks to calibrate our print
  $left = $begin_from_left[0] + $radius_outer;

  print PS_FILE $left   , " mm 0 mm moveto\n";
  print PS_FILE "0 mm ",$begin_from_bottom ," mm  rlineto\n"; #line to the first circle
  print PS_FILE "stroke newpath % line to the first circle\n";

  # now the tickmarks in the vertical direction beginning from bottom
  for ($i=0; $i < $begin_from_bottom; $i+= 2) {
    $tick = 3;
    if ($i % 10 == 0) {
      $tick = 10;
      print PS_FILE $left - 2*$tick , " mm ", $i ," mm  moveto ", "(", $i, ") show\n";
    }
    print PS_FILE $left  - $tick, " mm ", $i ," mm  moveto ", $left + $tick ," mm " , $i ," mm lineto\n stroke newpath\n";
  }

  # next ticks between the labels

  $left  = $minleft + $radius_outer;
  $right = $maxleft + $radius_outer;

  print PS_FILE "0 mm ", 2*$radius_outer + $begin_from_bottom , " mm translate\n";

  for ($i=0; $i < $delta; $i+= 2) {
    $tick = 3;
    if ($i % 10 == 0) {
      $tick = 10;
      print PS_FILE $left - 2*$tick, " mm ", $i ," mm moveto ", "(", $i, ") show\n";
    }
    print PS_FILE $left - $tick, " mm ", $i ," mm moveto ", $right + $tick ," mm " , $i ," mm  lineto\n stroke newpath\n";
  }


  # next ticks at the top of the page

  $left = $begin_from_left[1] + $radius_outer;

  print PS_FILE "0 ", 2*$radius_outer + $delta , " mm translate\n";

  ### correct this with pagelength ####################
  for ($i=0; $i < 3*$delta; $i+= 2) {
    $tick = 3;
    if ($i % 10 == 0) {
      $tick = 10;
      print PS_FILE $left - 2*$tick, " mm ", $i ," mm moveto ", "(", $i, ") show\n";
    }
    print PS_FILE $left - $tick, " mm ", $i ," mm moveto ", $left + $tick ," mm " , $i ," mm lineto\n stroke newpath\n";
  }

  print PS_FILE "grestore\n";

  # horizontal ticks
  # first, we have to start from the left margin
  print PS_FILE "0 ", $radius_outer + $begin_from_bottom ," mm moveto\n";
  print PS_FILE "/Helvetica findfont 12 scalefont setfont\n"; #Fontsize for the tickmarks

  my $top = ($radius_outer + $begin_from_bottom);
  for (my $lab_no = 0; $lab_no < $number_of_labels ; $lab_no++ ) {
    for ($i=0; $i < $begin_from_left[$lab_no]; $i+= 2) {
      $tick = 3;
      if ($i % 10 == 0) {	# every 10 mm we want a bigger tick
	$tick = 10;
	print PS_FILE  $i  , "  mm " , $top + $tick, " mm moveto \n";
	print PS_FILE  "90 rotate ($i) show\n";
	print PS_FILE  "-90 rotate\n";
      }
      print PS_FILE $i, " mm ", $top - $tick," mm  moveto ", $i ," mm " ,$top + $tick ,"  mm lineto\n stroke newpath\n";
    }
    print PS_FILE "0 mm " , 2*$radius_outer + $delta , " mm translate\n";
  }
}

########################
sub evaluate_shortcuts() {

  my @shortcuts = shift;
#  print "ARGS: @\_\n";

}
########################
sub get_bounding_box() {

  my $eps_file = shift;

  if ( open (EPS_FILE ,"<$eps_file") ) {
    while ( <EPS_FILE>) {
      if ( $_ =~ /(%%BoundingBox: )(\d*)( )(\d*)( )(\d*)( )(\d*)/) {
	$Bounding_X = ($2 - $6) / 2;
	$Bounding_Y = ($4 - $8) / 2;
	last;		#!# exit the while loop here
      }
    }
    close ($eps_file);
  }
  else {
    warning_window("There seems to be no bounding box in $eps_file\nHope for the best\n");
  }
}

########################
sub get_eps_file {
  my $FSref;
  my $fn;
  my $epsfile;
  my $i;

 for ( $i=0; $i < $number_of_labels; $i++) {
   $epsfile = $eps_filename[$i] if $eps_file_label[$i];
 }

# set the filename if defined as default !!!!!!!!!!!
  $FSref = $mw -> FileSelect(-directory => $graphics_directory, -title => 'EPS File',
#			     -defaultextension => "eps",
 			     -acceptlabel => 'Ok',
			     -filter => '[^.]*', -initialfile => $epsfile);

  $fn = $FSref -> Show;

  if ((defined $fn) && ($fn ne "")) {
    $graphics_file = $fn;
#   Remember the path 
#   First get it from the string
    $graphics_file =~ /(.*\/)(.*)/;
#   and store it  
    $graphics_directory = $1;
    for ( $i=0; $i < $number_of_labels; $i++) {
      if ($eps_file_label[$i]) {
	    $eps_filename[$i] = $graphics_file;
	    $eps_file_entry[$i] -> configure(-textvariable => \$graphics_file);
      }
    }
  }
}

########################
sub get_fontattributes {

  my $flb;
  my $fw; #Frame
  my ($flco, $i);

  if (! Exists($fmw)) {
  $fmw = $mw->Toplevel();

  $fmw -> title("FONTS, size and colours");

  $fmw->Button(-text => "OK", -command => sub{$fmw->withdraw})->pack(-side => 'bottom');

# A frame for everything except the ok button

  $fff = $fmw -> Frame() -> pack(-side => 'top');

# Now we want a frame for the radiobuttons
  $fw = $fff -> Frame(-relief => 'raised', -bd => 2) -> pack(-side => 'left',
						      -fill => 'both',
						      -anchor => 'e',
						      -expand => '1');

# This frame is divided into three frames

  my $fwb = $fw -> Frame() -> pack(-side => 'bottom',
				-fill => 'both');

  my $fwc = $fw -> Frame() -> pack(-side => 'left',
				-fill => 'both');

  my $fwt = $fw -> Frame() -> pack(-side => 'left',
				-fill => 'both');

  $fwc -> Radiobutton(-text => "Outer Top circle",
		     -value => 0,
		     -variable => \$which_field,
		     -command => sub{set_selectors()}
		     ) ->pack(-expand => 'x',
			    -anchor => 'w');

  $fwc -> Radiobutton(-text => "Inner Top circle",
		     -value => 1,
		     -variable => \$which_field,
		     -command => sub{set_selectors()}
		     ) ->pack(-expand => 'x',
			   -anchor => 'w',);

  $fwc -> Radiobutton(-text => "Inner Bottom circle",
		     -value => 2,
		     -variable => \$which_field,
		     -command => sub{set_selectors()}
		     ) ->pack(-expand => 'x',
			    -anchor => 'w');

  $fwc -> Radiobutton(-text => "Outer Bottom circle",
		     -value => 3,
		     -variable => \$which_field,
		     -command => sub{set_selectors()}
		     ) ->pack(-expand => 'x',
			    -anchor => 'w');

  $fwt -> Radiobutton(-text => "Top textfield",
		     -value => 4,
		     -variable => \$which_field,
		     -command => sub{set_selectors()}
		     ) ->pack(-expand => 'x',
			    -anchor => 'w');

  $fwt -> Radiobutton(-text => "Right textfield",
		     -value => 5,
		     -variable => \$which_field,
		     -command => sub{set_selectors()}
		     ) ->pack(-expand => 'x',
			   -anchor => 'w',);

  $fwt -> Radiobutton(-text => "Bottom textfield",
		     -value => 6,
		     -variable => \$which_field,
		     -command => sub{set_selectors()}
		     ) ->pack(-expand => 'x',
			    -anchor => 'w');

  $fwt -> Radiobutton(-text => "Left textfield",
		     -value => 7,
		     -variable => \$which_field,
		     -command => sub{set_selectors()}
		     ) ->pack(-expand => 'x',
			    -anchor => 'w');

  $fw -> Radiobutton(-text => "Top Label",
		     -value => 1,
		     -variable => \$label_id,
		     -command => sub{set_selectors()}
		     ) ->pack(-expand => 'x',
                              -anchor => 'w',
			    -side => 'top');

  $fw -> Radiobutton(-text => "Bottom Label",
		     -value => 0,
		     -variable => \$label_id,
		     -command => sub{set_selectors()}
		     ) ->pack(-expand => 'x',
                              -anchor => 'w',
			    -side => 'top');

  $fwb -> Radiobutton(-text => "Background",
		     -value => $number_of_background,
		     -variable => \$which_field,
		     -command => sub{set_selectors()}
		     ) ->pack(-expand => 'x', -padx => 100,
			   -pady => 10, -anchor => 'w');

############################################################
# Another frame for the fontlist and size
############################################################

  $flb = $fff -> Frame(-relief => 'raised', -bd => 2) -> pack(-side => 'left',
							      -fill => 'x',
							      -anchor => 'e',
							      -expand => '1');

  $fontlistbox = $flb -> Scrolled("Listbox", -scrollbars => "e", -selectmode => "single", -width => 0) -> pack();

  foreach $i  ( @fontnames) {
    $fontlistbox -> insert('end', $i);
  }

  $fontlistbox -> bind('<Button-1>',
		      sub{$fontfamily[$label_id][$which_field] =  $fontnames[$fontlistbox->curselection->[0]];
			   modify_fonts() }
		      );

  $flb -> Scale(-from => 8,
	       -to => 44,
	       -orient => 'horizontal',
	       -variable => \$scale,
	       -command => sub{$fontsize[$label_id][$which_field] = $scale;
                           modify_fonts() } ) -> pack(-side => 'right',
							-expand => 'x') ;

#####################################
# Next we want a frame for colors
#####################################

my $fco = $fff -> Frame(-relief => 'raised', -bd => 2) -> pack(-side => 'left',
							    -fill => 'x',
							    -anchor => 'e',
							    -expand => '1');

$fco -> bind("<ButtonRelease>",\&modify_color());

$fco ->  Scale(-label => "red",
           -length => 140,
	       -variable => \$rgb[0],
	       -resolution => 1,
	       -command => sub{modify_color()},
	       -from => 255, -to => 0) -> pack(-side => 'left');

$fco ->  Scale(-label => "green",
           -length => 140,
	       -variable => \$rgb[1],
	       -resolution => 1,
	       -command => sub{modify_color()},
	       -from => 255, -to => 0) -> pack(-side => 'left');

$fco ->  Scale(-label => "blue",
           -length => 140,
	       -variable => \$rgb[2],
	       -resolution => 1,
	       -command => sub{modify_color()},
	       -from => 255, -to => 0) -> pack(-side => 'left');
} else {
  $fmw->deiconify();
  $fmw->raise;
}

set_selectors();

}

########################
sub get_graphics {
  my $fwb; #Frame for labelbuttons
  my $fwf; #Frame for the files
  my $fwg; #Frame for graphics-place buttons
  my $fw; #Frame for the radiobuttons
  my ($fwscale, $fwshift);
  my ($ox, $oy);
  my $i;

  if (! Exists($fgw)) {
    $fgw = $mw->Toplevel();

    $fgw -> title("Graphics files");

    $fgw->Button(-text => "OK", -command => sub{$fgw->withdraw})->pack(-side => 'bottom');

# One frame for the labels
    $fwb = $fgw -> Frame(-relief => 'raised', -bd => 2) -> pack(-side => 'top',
							      -fill => 'both',
							      -anchor => 'n',
							      -expand => '1');

# One more frame for the Files
    $fwf = $fgw -> Frame(-relief => 'raised', -bd => 2) -> pack(-side => 'top',
							       -fill => 'both');

# One more for shifting
    $fwshift = $fgw -> Frame(-relief => 'raised', -bd => 2) -> pack(-side => 'top',
							       -fill => 'both');
# One more for scaling
    $fwscale = $fgw -> Frame(-relief => 'raised', -bd => 2) -> pack(-side => 'top',
							       -fill => 'both');

    $fwb -> Checkbutton(-text => "Upper label",
		     -variable => \$eps_file_label[1],
		     -command => sub{set_graphics_attributes()}) -> pack(-side => 'right',
						       -expand => 'x',
						       -anchor => 'w');
    $fwb -> Checkbutton(-text => "Lower label",
		     -variable => \$eps_file_label[0],
		     -command => sub{set_graphics_attributes()}) -> pack(-side => 'right',
						       -expand => 'x',
						       -anchor => 'w',);

    for ($i=0; $i < $number_of_labels; $i++) {
      $eps_file_entry[$i] = $fwf -> Entry( -textvariable => \$eps_filename[$i],
					-background => "#ffffff") -> pack(-side => 'bottom');
    }

    $fwf -> Button(-text => "browse",
		 -command => sub{get_eps_file()}) -> pack();

    $ox = $fwshift -> Scale(-label => "Offset X",
		    -from => -$radius_outer/$scale_x, -to => $radius_outer/$scale_x,
		    -resolution => "0.1",
		    -orient => "horizontal",
		    -command => sub{set_graphics_attributes()},
		    -variable => \$shift_x) -> pack(-side => "left");

    $oy = $fwshift -> Scale(-label => "Offset Y",
		    -from => $radius_outer/$scale_y, -to => -$radius_outer/$scale_y,
		    -resolution => "0.1",
		    -orient => "vertical",
		    -command => sub{set_graphics_attributes()},
		    -variable => \$shift_y) -> pack(-side => "right");

    $fwscale -> Scale(-label => "Scale X",
		    -from => 0.05, -to => 1,
		    -resolution => "0.01",
		    -orient => "horizontal",
		    -command => sub{$ox->configure(-from => -$radius_outer/$scale_x,
                                           -to => $radius_outer/$scale_x); set_graphics_attributes()},
		    -variable => \$scale_x) -> pack(-side => "left");

    $fwscale -> Scale(-label => "Scale Y",
		    -from => 1, -to => 0.05,
		    -resolution => "0.01",
		    -orient => "vertical",
		    -command => sub{$oy->configure(-from => $radius_outer/$scale_y,
                                           -to => -$radius_outer/$scale_y); set_graphics_attributes()},
		    -variable => \$scale_y) -> pack(-side => "right");
  } else {
    $fgw->deiconify();
    $fgw->raise;
  }
}

########################
sub get_converter {
    my $fc;
    my $FSref;
    
    $FSref = $mw -> FileSelect(-directory => "/usr/bin", -title => 'Converter',
                               -acceptlabel => 'Ok');
    $fc = $FSref -> Show;

    $converter = $fc if ((defined $fc) && ($fc ne ""));
}

########################
sub get_previewer {
  my $pv;
  my $FSref;

  $FSref = $mw -> FileSelect(-directory => "/usr/bin", -title => 'Previewer',
                             -acceptlabel => 'Ok');
  $pv = $FSref -> Show;

  if ((defined $pv) && ($pv ne "")) {
    check_viewer($pv);
  }
}
########################
sub get_starting_angle {

if (! Exists($caw)) {
    $caw = $mw -> Toplevel();
    $caw -> title("Angle to middle of text");
    $caw -> Button(-text => "OK",
		   -command => sub {$caw -> withdraw}) -> pack(-side => 'bottom');

  $caw -> Scale(-label => "Angle to middle of text",
				  -from => -90, -to => 90,
				  -resolution => "0.5",
				  -orient => "horizontal", -length => 250,
				  -variable => \$starting_angle) -> pack(-side => "top");
  }
  else {
    $caw -> deiconify();
    $caw -> raise();
  }
}

########################
sub save_label {

  if (defined $label_fn) {
    write_label();
  }
  else {
    save_as();
  }
}

########################
sub save_as {

  my $SAref;
  my $safile;
  my $home = $ENV{'HOME'};

  $SAref = $mw -> FileSelect(-directory => $home, -title => 'Save As',
                             -filter => '[^.]*', -acceptlabel => 'Ok');
  $safile = $SAref -> Show;

  if ((defined $safile) && ($safile ne "")) {
    $label_fn = $safile;
    write_label();
  }
}

########################
sub save_ps_file {

  my $FSref;
  my $filen;
  my $home = $ENV{'HOME'};

  $FSref = $mw -> FileSelect(-directory => $home, -title => 'Save PS File',
                             -filter => '[^.]*', -acceptlabel => 'Ok');
  $filen = $FSref -> Show;

  if ((defined $filen) && ($filen ne "")) {
    $psfile = $filen;
    print_label;
  }
}

########################
sub set_circle_radius {

my (@lf, @lsc, $tf, $bf, $i, $j);

if (! Exists($crw)) {
    $crw = $mw -> Toplevel();
    $crw -> title("Radii");
    $crw -> Button(-text => "OK",
		   -command => sub {$crw -> withdraw}) -> pack(-side => 'bottom');

    $tf = $crw -> Frame(-label => "Radius of the inner circle [mm]", -borderwidth => "5")
                        -> pack(-side => 'top');
    $tf -> Scale(-orient => 'horizontal',
		  -variable => \$radius_inner,
		  -from => 0, -to => 50,
		  -resolution => "0.5",
          -command => sub { for ($j=0; $j<2 ; $j++) { for ($i=0; $i<4 ; $i++) {
                      $lsc[$j][$i]->configure(-from => $radius_inner)}}}) -> pack(-side => 'left');

    $bf = $crw -> Frame(-label => "Radius of the text-circles [mm]") -> pack(-side => 'bottom');
    # Now the radii for the text circles

    my @side = qw (bottom right);

    for ($j=0; $j<2 ; $j++) {
      $lf[$j] = $bf -> Frame(-label => "Label $j", -borderwidth => "5", -relief => 'groove') -> pack(-side => 'left');
      for ($i=0; $i<4 ; $i++) {
        $lsc[$j][$i] = $lf[$j] -> Scale(-orient => 'horizontal',
		     -variable => \$circle_radius[$j][$i],
		     -from => $radius_inner, -to => $radius_outer,
		     -resolution => "0.5",) -> pack(-side => 'top');
      }
    }
  }
  else {
    $crw -> deiconify();
    $crw -> raise();
  }
}

########################
sub modify_fonts {

  if ( $which_field < $number_of_background) {  configure_font($label_id, $which_field);  }
  update_display();
}

########################A
sub set_graphics_attributes {

  my $i;
  for ( $i = 0; $i < $number_of_labels; $i++) {
    if ( $eps_file_label[$i] ) {
      $scale_eps_x[$i] = $scale_x;
      $scale_eps_y[$i] = $scale_y;

      $shift_eps_x[$i] = $shift_x;
      $shift_eps_y[$i] = $shift_y;

      $graphics_file = $eps_filename[$i];
      $eps_file_entry[$i] -> configure(-textvariable => \$eps_filename[$i]) if defined $eps_file_entry[$i];
    }
  }
  display_graphics_file_attributes();
}

########################
sub set_page_scaling {

  if (! Exists($spw)) {
    my $spw = $mw -> Toplevel();
    $spw -> title("Scale the whole page");
    $spw -> Button(-text => "OK",
		   -command => sub {$spw -> withdraw}) -> pack(-side => 'bottom');
    $spw -> Label(-text => "Some printers don\'t print exact circles,\n so you can scale the page") -> pack; 
    $spw -> Scale(-label => "horizontal scale",
		  -orient => 'horizontal',
		  -resolution => 0.01,
		  -variable => \$x_scale,
		  -from => .9, -to => 1.1,) -> pack(-side => 'left');
    $spw -> Scale(-label => "vertical scale",
		  -variable => \$y_scale,
		  -resolution => 0.01,
		  -from => 1.1, -to => .9 ) -> pack;
  }
  else {
    $spw -> deiconify();
    $spw -> raise();
  }

}

########################
sub select_labels {
  for (my $j = 0; $j < $number_of_labels; $j++) {
      if ($label_active[$j]) {
        $ct_clear[$j] -> configure(-state => 'normal');
        $tf_clear[$j] -> configure(-state => 'normal');
      } else {
        $ct_clear[$j] -> configure(-state => 'disabled');
        $tf_clear[$j] -> configure(-state => 'disabled');
      }
  }
  update_display();
}

########################
sub set_positions {

  if (! Exists($spw)) {
    my $spw = $mw -> Toplevel();
    $spw -> title("Change label positions to fit the sheet");
    $spw -> Button(-text => "OK",
		   -command => sub {$spw -> withdraw}) -> pack(-side => 'bottom');
    $spw -> Label(-text => "Use the tickmark scales to determine the positions",
		 -relief => 'raised',
		 -border  =>"3") -> pack(-fill =>'both');

    my $fwt = $spw -> Frame(-relief => 'raised',
			   -border => "3") -> pack(-side => 'top',
						  -fill => 'both');

    for (my $label_no = 0; $label_no < $number_of_labels; $label_no++ ) {
      $fwt -> Entry(-textvariable => \$begin_from_left[$label_no],
		    -text => "Labeltext",
		    -width => '5') -> pack(-side => 'bottom');
      $fwt -> Scale(-label => "move label $label_no horizontaly",
		    -orient => 'horizontal',
		    -length => 250,
		    -resolution => 0.1,
		    -tickinterval => 75,
		    -variable => \$begin_from_left[$label_no],
		    -from => 0, -to => 250,) -> pack(-side => 'bottom');
    }

# We want a frame for the scales
    my $fw = $spw -> Frame(-relief => 'raised',
			   -border => "3",
			   -label => "vertical scales") -> pack(-side => 'bottom',
							       -fill => 'both');

    $fw->Entry(-textvariable => \$begin_from_bottom,
	       -text => "Bottom",
	      -width => '5') -> pack(-side => 'left');

    $fw -> Scale(-label => "start from bottom",
		 -variable => \$begin_from_bottom,
		 -resolution => 0.1,
		 -from => 200, -to => -50 ) -> pack(-side => 'left');


    $fw -> Scale(-label => "distance between the labels",
		 -variable => \$delta,
		 -resolution => 0.1,
		 -from => 100, -to => 0 ) -> pack(-side => 'right');

    $fw->Entry(-textvariable => \$delta,
	       -width => '5',
	       -text => "Delta") -> pack(-side => 'right');

  }
  else {
    $spw -> deiconify();
    $spw -> raise();
  }
}

########################
sub warning_window {

  my $message = shift;
  my $warning_box = $mw->DialogBox(-title => 'Warning', -buttons => ['OK'], -default_button => 'OK');

  my $text = $warning_box -> Label(-text => $message,
					  -background => '#ff0000') -> pack;

# fix needed to get around locking waitVariable() call, which is never unblocked when the dialog is destroyed.
  $warning_box->OnDestroy(sub { $warning_box->{'selected_button'} = $warning_box->{'selected_button'} });

  $warning_box->Show();

}

########################
sub write_label {

  my $date = localtime;

  if (defined $label_fn) {
    open (LABEL_FILE , "> $label_fn") or print  ("Error attempting to write label to $label_fn");

    print LABEL_FILE "#Label data for cd-circleprint\n";
    print LABEL_FILE "#written  $date \n\n";

# Write all of the variables we know about
    my($sym, $val);
    foreach $sym (@LabelVariables) {
        my($eval) = "\$val = \$$sym";
        eval $eval;
        print LABEL_FILE "$sym $val\n" if (defined($val));
    }
  close (LABEL_FILE);
  }
}

########################
sub write_configuration {

  my $date = localtime;
  my $cf;

  if ($configurationfile[2]) {$cf = $configurationfile[2]}
  else {$cf = $configurationfile[1]}

  open (CONF_FILE , "> $cf") or print  ("Error attempting to write configuration to $cf");

  print CONF_FILE "#Configuration for cd-circleprint\n";
  print CONF_FILE "#written  $date \n\n";

  # Write all of the variables we know about from the SaveVariables routine
  my($sym, $val);
  foreach $sym (@SaveVariables) {
      my($eval) = "\$val = \$$sym";
      eval $eval;
      print CONF_FILE "$sym $val\n" if (defined($val));
  }

  close (CONF_FILE);
}

########################
sub write_form_data {

my $FSref;
my $home = $ENV{'HOME'};

$FSref = $mw -> FileSelect(-directory => $home, -title => 'Form Data',
                           -filter => '[^.]*', -acceptlabel => 'Ok');
my $fdfile = $FSref -> Show;

  if ((defined $fdfile) && ($fdfile ne "")) {

    open (FD_FILE, ">$fdfile") || die ("Could not open $fdfile\n");

    my $date = localtime;

    print FD_FILE "#Form Data file for cd-circleprint\n";
    print FD_FILE "#written  $date \n\n";

    my($sym, $val);
    foreach $sym (@FormVariables) {
      my($eval) = "\$val = \$$sym";
      eval $eval;
      print FD_FILE "$sym $val\n" if (defined($val));
    }
    close (FD_FILE);
  }
}

########################
sub dummysub {

  my $dw;
  my $text;

  $dw = MaindWindow -> new;
  $text = $dw -> Scrolled("Text", -scrollbars => 'oe') -> pack;
  $text -> insert('end',"Sorry this function is not implemented yet.");
  $dw -> Button(-text => "close",
			 -command => sub {$dw -> destroy() if Tk::Exists($dw)}) -> pack;
}

########################################
#
# Documentation
#
#######################################


=pod MANUAL PAGE

=head1 NAME

cd-circleprint - create a round label for a CD

=head1 SYNOPSIS

=over

=item B<cd-circleprint> [option[=value..]] FILE

=back

=head1 DESCRIPTION

cd-circleprint prints two round labels for CDs. It uses up to four lines of text for each
label, this is printed in arcs so the text can be much longer than if it were in straight lines.
There are four additional straight text fields for each label.

The output is in PostScript, this should work on most systems.

You can select the font, size, and colour of the text for each field separately, and you
can choose the background colour for each label. An image file in EPS format may also be used as a
background.  If you wish more complicated backgrounds
or colour effects you can save a label and modify it in any graphic program which can read
PostScript.

=head1 OPTIONS

=over

=item B<--config>

Alternative configuration file. 

=item B<--debug>

Enable debuggging mode, various information is printed to standard output.

=item B<--version>

Print version number and exit successfully.

=back

=head1 LAYOUT

All layout is done in PostScript, this should work on most systems.

The result of the layout are two cd-labels on one sheet of paper. On each label there are two
convex and two concave lines of text. If you have a very long line of text, you can use only
one line and make it longer.  There are no limits to the length of text.
However, after 360 degrees the ends of the text will overlap.

There are also four text fields on each label with normal horizontal
lines of text.  These text fields are specified in clockwise order:
above, right, below, and left of the central hole.

The colours are done in the RGB-model of PostScript, you can choose them for each line and 
the background of the label independently.

You can move the circles around the sheet to fit them on most types of label-sheets.

You can also squeeze or stretch the whole thing to correct small errors of your printer.

=head1 USAGE

After starting the program you see sixteen text-entry fields divided into two blocks. 
The upper block is for the arcs, the lower block is for the straight text fields.

Each label has four text fields and four arcs.

The first two lines are for the upper arcs on the label and the last two for the lower arcs.

Write your text in the fields (support for cddb is on the TODO list)

The Save Image menu item creates a postscript file of the label.
A file selection dialogue is displayed so the user can specify the path and filename.

Font attributes and colours can be changed interactively using a dialog available from the menu.

=over

=item B<Shortcuts>

 Control-l: write the label to /tmp
 Control-p: preview the label
 Control-q: quit
 Control-s: save the configuration

=item B<File Menu>

=over

=item I<New>

Start a new label, all label fields are cleared and parameters are reset to default values.

=item I<Open>

A file selection dialog is displayed so that the user can select a label data file which is then
used to set the label values.

=item I<Save>

The current label data values are saved using the current filename.

=item I<Save As>

A file selection dialog is displayed and the current label data values are saved to the file
specified by the user.

=item I<Load Form Data>

Load Form (Paper Layout) data from a specified file.

=item I<Save Form Data>

Save Form Data to a specified file.

=item I<Save Image>

Save an image of the labels as a specified Postscript File.

=item I<Preview>

Launch the predefined preview application to preview the labels.

=item I<Exit>

Exit the program, all unsaved data will be lost.

=back

=item B<Format Menu>

=over

=item I<Fonts & Colours>

Change font family, font size, font-colour and the background colour interactively, all
changes should take effect immediately in the text entry fields.

Note, perl-tk uses the nearest match for the font. The labels may look different on your printer.

=item I<Angle>

Sets the angle by which the centre of the text arcs are offset.

=item I<Radii>

Specify the size of the label inner circle and the radii of the text circles.

=item I<Page Deformation>

Some printers do not work correctly with circles and produce an ellipse, you can squeeze or stretch
the whole page to get perfect circles with your printer.

=item I<Positions>

You can move the circles around the page using this menu.

=item I<Top Label / Bottom Label>

Select which labels will be generated. The input fields for unselected labels are disabled.

=item I<Tickmarks>

There are many cd-label sheets on the market, so you can move the circles around the page. To make this
easier, you can print some tickmarks on the page to measure the distances.
If you have the correct values, you don't need these tickmarks any more and can save some ink.

=item I<Circle Boundaries>

This allows the user to turn off the printing of the circles which show the boundaries
of the labels.

=item I<Graphics>

You can put an image on the label. This image currently has to be in eps-format.

I thought about automatic scaling, but the program would
have to know the real size of the visible part of the graphic instead of just the bounding box.

The scaling and shifting should be self-explanatory. The program gets the bounding box of the eps
image and puts the image in the middle of the label.

=back

=item B<Options Menu>

=over

=item I<Previewer>

Select the application to use for previewing the labels.

=item I<Graphics Converter>

Select the application to use for converting graphics to eps format.

=item I<Load Options>

Load program options from configuration files, this is useful to reset the configuration to a known state.

=item I<Save Options>

Save the current program configuration to either the user specified configuration file
or to the default file if the user did not specify one.

=back

=item B<Help Menu>

=over

=item I<Help>

Display this man page.

=item I<About>

Display program version, description and copyright information.

=back

=back

=head1 CONFIGURATION

You can save your configuration in a file in your $HOME or ask your sysadmin to create a global configuration-file.

=head1 FILES

There is a global configuration file /etc/cd-circleprint.conf and a local configuration file 
$HOME/.cd-circleprint.conf

You can specify a configuration file on the command line in which case the
default configuration file settings can be overridden.
For the format of the configuration files take a look at them.
Comments start with a # and blank lines are ignored.

The program sets its internal default values, looks for the global configuration file, then
for the local configuration file and finally for a user specified file.

Label data is read from a similar format file either specified on the command line
or selected from a file dialog.

=head1 BUGS

There are probably many bugs, please fix them and send me a patch.
Thanks

=head1 AUTHORS

cd-circleprint is written and maintained by Colin Tuckley <colintu@users.sourceforge.net>
cd-circleprint was originally written by Matthias Kabel <matthias.kabel@tyche.de>

You can find the latest version at http://cd-circle-print.sourceforge.net

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.

Thanks to sourceforge.net for hosting free software

=cut

# END of File

