#!/usr/bin/env perl
use strict;
use lib $ENV{ 'MAIN_CONF'}  ;
use main_config ;
use Tk;
use Tk::Dialog;
use Tk::Font;
use LWP::Simple;
use HTML::Parser;
require Tk::TList;
require Tk::ROText;

my $Win_background = "white" ;
my $Win_foreground = "black" ;
my $frame_lab_bck = "grey20" ;
my %commands = () ;
my @segment_list = () ;
my @crystal_list = () ;
my %new_main = () ;

my @strategy_list = qw( EACH ONE LINK WHOLE COMPOSIT BACKGROUND ) ;
#if ( @ARGV <= 0 ) { push ( @{$commands{'help'}}, ' ' ) ; } 
#else { (%commands) = main_config::get_commands ( @ARGV ) ; }

my @all_segments ;
my %group_keys ;

my @all_groups = () ;
my %all_groups_strategy = () ;
my $n_groups ;
my %cryst_keys ;

my @all_space_groups = ( qw /f2_3 h23 h3 i2_3 p1_2_1 p2_3 r3_2 c1_2_1
c2_2_21 c2_2_2 c2 f2_2_2 f23 f4_3_2 i21_21_21 i21_3 i2_2_2 i23 i41_2_2
i41_3_2 i41 i4_2_2 i4_3_2 i4 p1_21_1 p1 P_1 p21_21_21 p21_21_2 p21_3
p21 p2_21_21 p2_2_21 p2_2_2 p23 p2 p31_1_2 p31_2_1 p3_1_2 p31 p32_1_2
p3_2_1 p32_2_1 p32 p3 p41_21_2 p41_2_2 p41_3_2 p41 p4_21_2 p42_21_2
p42_2_2 p4_2_2 p42 p43_21_2 p43_2_2 p4_3_2 p43 p4 p61_2_2 p61 p62_2_2
p6_2_2 p62 p63_2_2 p63 p64_2_2 p64 p65_2_2 p65 p6 r32 r3 / ) ;

my $text_height = 18 ;
my @NCS_group_list = ( "NCS_NONE", "NCS_from_CHAINS", "NCS_from_SEGMENTS" ) ;
my $NCS_group_def = "NCS_from_SEGMENTS" ;

my @all_crystals ;
my $n_crystals ;
my $max_length = 0 ; my @act_lines = () ;
my %file_list = () ;
my %dfr_file_list = () ;
my %dfr_data_list = () ;
my %model_file_list = () ;
my %segm_list = () ;
my @frame_group_list = () ;
my %frame_crystal_list = () ;

my $MACRO_FILE ="create_main_config.pl" ;

##################### MAIN window first to get @ARGV

my $mw = MainWindow->new (-width => 100, -height => 250, -background => $Win_background, -foreground => $Win_foreground );
#my $mw = MainWindow->new (-width => 100, -height => 250 );
my $code_font ;
$code_font = $mw->fontCreate('code', -family => 'coourier', -size => 22) ;
$mw->packPropagate( 0 ) ;
$mw->geometry( "400x600+0+0" ) ;
$mw->title("Tk: main config" );
#$cf->configure(-size => $cf->actual(-size)-1);

$mw->Button(-text => "Smaller", -font => 'code',
		-command => sub {
		    $code_font->configure(-size => $code_font->actual(-size)-1);
		})->pack;


#######################################################
#    print "-------------------------------------TOP macro file:", $MACRO_FILE, "\n" ;

my $conf_file ;
if ( -f "main_config.data" )
{    $conf_file = "main_config.data" ; }
else
{    $conf_file = join ('', $ENV{"MAIN_CONF"}, "main_config.data" ) ; }

my %my_main = main_config::read_main_config_file ( $conf_file ) ; 

update_from_main_config_data () ;

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

my $frame_crystal ;
my $frame_segment ;
my $frame_group ;
my $frame_file ;
my $frame_model ;
my ( $key, $I, $nn, $IGR, $STRATEGY, $GROUP ) ;


my $f = $mw->Frame(-background => $Win_background, -foreground => $Win_foreground )->pack(-side => 'bottom' );
$f->Button(-text => "Quit", -font => 'code',
           -command => sub { exit; })->pack(-side => 'left');
#$f->Button(-text => "add", 
#           -command => \&gen_entry )->pack(-side => 'left');
$f->Button(-text => "create_read", -font => 'code',
           -command => \&create_read )->pack(-side => 'left');
$f->Button(-text => "doit", -font => 'code',
           -command => \&create_all_macros )->pack(-side => 'left');

#$frame_file = $mw->Scrolled("Text", asldjfk;l

$frame_crystal = $mw->Text( -width => $max_length + 30, -height => $text_height, 
			    -background => $Win_background, -foreground => $Win_foreground,
			    -wrap => 'none')->pack(-expand => 'x', -fill => 'both', -side => 'top');
$frame_crystal->configure(-state => 'normal');
$frame_crystal->Frame( -label => " --- CRYSTAL FORMS DATA --- ",  
		       -background => $frame_lab_bck, -relief => 'flat', -borderwidth => 2)->pack(-side => 'top');
$frame_crystal->insert('end', "\n");
$frame_crystal->insert('end', "\n");
$frame_crystal->insert('end', "\n");
generate_crystal_frame ( ) ;


#
#    molecular model data
#
$frame_model = $mw->Text( -width => $max_length + 30, -height => $text_height, 
			  -background => $Win_background, -foreground => $Win_foreground,
			  -wrap => 'none')->pack(-expand => '1', -fill => 'both', -side => 'top');
$frame_model->configure(-state => 'normal');
$frame_model->Frame( -label =>  " --- MOLECULAR MODEL DATA --- ",  
		     -background => $frame_lab_bck, -relief => 'flat', -borderwidth => 2)->pack(-side => 'top');

$frame_model->insert('end', "\n");
$frame_model->insert('end', "\n");
$frame_model->insert('end', "\n");
generate_model_frame ( ) ;



#
#    NCS groups
#
$frame_group = $mw->Scrolled("Text", -font => 'code', -width => $max_length + 30, -height => $text_height, -background => $Win_background, -foreground => $Win_foreground,
                   -wrap => 'none')->pack(-expand => 3, -fill => 'both', -side => 'top');

$frame_group->configure(-state => 'normal');

$frame_group->Frame( -label => " --- Non Crystallographic Symmetry GROUPS --- ",  -background => $frame_lab_bck, -relief => 'flat', -borderwidth => 2)->pack(-side => 'top');
#			   -background => $Win_background, -foreground => $Win_foreground )->pack(-side => 'top');

#    if ( $all_segments[@all_segments-1] ne "    " ) { push(@all_segments, "" ) };
$frame_group->insert('end', "\n");
$frame_group->insert('end', "\n");
$frame_group->insert('end', "\n");

my $w ;
$w = $frame_group->Entry(-textvariable => \$n_groups, -font => 'code', -justify => 'left', -relief => 'groove', 
			 -background => $Win_background, -foreground => $Win_foreground, 
			 -width => $max_length + 12, -borderwidth => 4 )->pack(-side => 'top', -anchor => 'w' );
$w->bind("<Return>", [\&hit_group_return ] ) ;
$frame_group->windowCreate('end', -window => $w);
$frame_group->insert('end', "\n");
$frame_group->insert('end', "\n");
    
    
#$frame_group = $mw->Text( -width => $max_length + 30, -height => $text_height, -background => $Win_background, -foreground => $Win_foreground,
#                   -wrap => 'none')->pack(-expand => 3, -fill => 'both', -side => 'top');

generate_group_frame ( ) ;

#
#    segments & groups & crystals
#
$frame_segment = $mw->Scrolled("Text",  -font => 'code', -width => $max_length + 30, -height => $text_height, -background => $Win_background, -foreground => $Win_foreground,
                   -wrap => 'none')->pack(-expand => 3, -fill => 'both', -side => 'top');
#$frame_segment = $mw->Text( -width => $max_length + 30, -height => $text_height, -background => $Win_background, -foreground => $Win_foreground,
#                   -wrap => 'none')->pack(-expand => 3, -fill => 'both', -side => 'top');
$frame_segment->configure(-state => 'normal');
$frame_segment->Frame( -label => " --- MOLECULAR SEGMENT NAMES and ORGANIZATION --- ",  -background => $frame_lab_bck, -relief => 'flat', -borderwidth => 2)->pack(-side => 'top');
$frame_segment->insert('end', "\n");
$frame_segment->insert('end', "\n");
$frame_segment->insert('end', "\n");

generate_segm_frame () ;


$mw->packPropagate( 1 ) ;

MainLoop;

sub generate_crystal_frame
{
#    my (%key_list) = @_ ;
    my $II ;
    my $w ; my $wl ;
    my $text ;


    my $g = $frame_crystal->Frame->pack(-side => 'top');
    $w = $g->Button(-text => "import dfr file", -font => 'code',
           -command => \&use_diffraction_macros )->pack(-side => 'left');
    $frame_crystal->insert('end', "\n");
#    $frame_crystal->insert('end', "\n");


    $w = $frame_crystal->Label(-text => "NUMBER of CRYSTAL FORMS", -font => 'code',
			       -justify => 'center', -relief => 'groove', 
			       -width => $max_length );
    $frame_crystal->windowCreate('end', -window => $w);
    $w = $frame_crystal->Entry(-width => 12, -textvariable => \$n_crystals, 
			       -justify => 'center' );
    $frame_crystal->windowCreate('end', -window => $w);

    $w->bind("<Return>", [\&hit_crystal_return ] ) ;
    $frame_crystal->windowCreate('end', -window => $w);
    $frame_crystal->insert('end', "\n");
#    $frame_crystal->insert('end', "\n");


    foreach $key ( sort (keys %dfr_file_list ))
    {
	my $I ;
	$text = $dfr_file_list{$key}{'LINE'} ;
	$w = $frame_crystal->Label(-text => $text, -font => 'code',-justify => 'center', -relief => 'groove', 
				   -width => $max_length + 20 );
	$frame_crystal_list{$key}{"WINDOW_WORD"} = $w ;
	@{$frame_crystal_list{$key}{"WINDOW_LIST"}} = () ;
	$frame_crystal->windowCreate('end', -window => $w);
	for ($I =0; $I < scalar( @{$dfr_file_list{$key}{'ARRAY'}}); $I++ )
	{
	    $w = $frame_crystal->Entry(-width => 20, -textvariable => \$dfr_file_list{$key}{'ARRAY'}[$I],  -font => 'code', -justify => 'center' );
#	    print " frame crystal $key loop $I ", $dfr_file_list{$key}{'ARRAY'}[$I], "\n" ;
	    $frame_crystal->windowCreate('end', -window => $w);
	    if ( $key eq "FILE_SYMM" )
	    {
		$w->bind("<Double-1>" => [\&space_group_select_box, \$dfr_file_list{$key}{'ARRAY'}[$I] ]);
	    }
	    else
	    {
		$w->bind("<Double-1>" => [\&file_select_box, \$dfr_file_list{$key}{'ARRAY'}[$I], "" ]);
	    }
#	    $w->bind("<Double-1>" => [\&file_select_box, &dfr_file_list, $key, $I ]);
#	    $w->bind("<Double-1>" => [\&file_select_box, $dfr_file_list{$key}[$I] ]);
	push(@{$frame_crystal_list{$key}{"WINDOW_LIST"}}, $w ) ;
	}
	$frame_crystal->insert('end', "\n");
    }

    foreach $key ( sort (keys %dfr_data_list ))
    {
	my $I ;
	$text = $dfr_data_list{$key}{'LINE'} ;
	$w = $frame_crystal->Label(-text => $text, -font => 'code',-justify => 'center', -relief => 'groove', 
				   -width => $max_length + 20 );
	$frame_crystal_list{$key}{"WINDOW_WORD"} = $w ;
	@{$frame_crystal_list{$key}{"WINDOW_LIST"}} = () ;
	$frame_crystal->windowCreate('end', -window => $w);
	for ($I =0; $I < scalar( @{$dfr_data_list{$key}{'ARRAY'}}); $I++ )
	{
	    $w = $frame_crystal->Entry(-width => 20, -textvariable => \$dfr_data_list{$key}{'ARRAY'}[$I],  -font => 'code', -justify => 'center' );
	    $frame_crystal->windowCreate('end', -window => $w);
	    push(@{$frame_crystal_list{$key}{"WINDOW_LIST"}}, $w ) ;
	}
	$frame_crystal->insert('end', "\n");
    }

}
sub hit_crystal_return
{
    my ($e) = @_ ;
    my $j = $e->get ;
    my $wl ; my $w ; my $GROUP ; my $text ;
    my $I ;

    $nn = @all_crystals ;

    print " Hit_crystal_return> entry {", $j, " - old:", $nn, "}\n" ;

    if ( $j == $nn ) 
    {
	print " nothing to do: crystal $j == $nn \n" ;
	return ;
    }

    foreach $key ( keys %dfr_file_list )
    {
	$w = $frame_crystal_list{$key}{"WINDOW_WORD"} ; $w->destroy() if Tk::Exists($w) ;
	for ($I =0; $I < $nn; $I++ )
	{
	    $w = $frame_crystal_list{$key}{"WINDOW_LIST"}[$I] ; $w->destroy() if Tk::Exists($w) ;
	}
	@{$frame_crystal_list{$key}{"WINDOW_LIST"}} = () ;
    }
    foreach $key ( keys %dfr_data_list )
    {
	$w = $frame_crystal_list{$key}{"WINDOW_WORD"} ; $w->destroy() if Tk::Exists($w) ;
	for ($I =0; $I < $nn; $I++ )
	{
	    $w = $frame_crystal_list{$key}{"WINDOW_LIST"}[$I] ; $w->destroy() if Tk::Exists($w) ;
	}
	@{$frame_crystal_list{$key}{"WINDOW_LIST"}} = () ;
    }
    $frame_crystal->delete("6.3", 'end');

    if ( $j > $nn ) 
    {
	print " $j > $nn \n" ;
	foreach $key ( keys %dfr_file_list )
	{
	    for ($I=$nn; $I < $j ; $I++ ) 
	    {
		push(@{$dfr_file_list{$key}{'ARRAY'}}, "" )  ;
	    }
	}
	foreach $key ( keys %dfr_data_list )
	{
	    for ($I=$nn; $I < $j ; $I++ ) 
	    {
		push(@{$dfr_data_list{$key}{'ARRAY'}}, "" )  ;
	    }
	}
    }
    elsif ( $j < $nn )
    {
	
	print " $j << $nn \n" ;

	foreach $key ( keys %dfr_file_list )
	{
	    for ($I=$nn; $I > $j ; $I-- ) 
	    {
		pop(@{$dfr_file_list{$key}{'ARRAY'}} )  ;
	    }
	}
	foreach $key ( keys %dfr_data_list )
	{
	    for ($I=$nn; $I > $j ; $I-- ) 
	    {
		pop(@{$dfr_data_list{$key}{'ARRAY'}} )  ;
	    }
	}

	if ( $j <= 0 ) 
	{

	    print "initialize $j\n" ;
	    $key = "FILE_CELL" ; 
	    @{$dfr_file_list{$key}{'ARRAY'}} = ( "cell.dat") ; 
	    
	    $key = "FILE_REFL" ; 
	    @{$dfr_file_list{$key}{'ARRAY'}} = ("diffract.dat") ; 
	    
	    $key = "FILE_SYMM" ; 
	    @{$dfr_file_list{$key}{'ARRAY'}} = ("p1") ; 
	    
	    $key = "DFR_RES_MIN" ; 
	    @{$dfr_data_list{$key}{'ARRAY'}} = ( "10.0") ; 
	    $key = "DFR_RES_MAX" ; 
	    @{$dfr_data_list{$key}{'ARRAY'}} = ("3.0") ; 
	    $j = 1 ;
	    @all_segments = ( "A" ) ;
	}

    }



    foreach $key ( keys %dfr_file_list )
    {
	$text = $dfr_file_list{$key}{'LINE'} ;
	$w = $frame_crystal->Label(-text => $text, -font => 'code',-justify => 'center', -relief => 'groove', 
				   -width => $max_length + 20 );
	$frame_crystal_list{$key}{"WINDOW_WORD"} = $w ;
	@{$frame_crystal_list{$key}{"WINDOW_LIST"}} = () ;
	$frame_crystal->windowCreate('end', -window => $w);
	for ($I =0; $I < scalar( @{$dfr_file_list{$key}{'ARRAY'}}); $I++ )
	{
	    $w = $frame_crystal->Entry(-width => 20, -textvariable => \$dfr_file_list{$key}{'ARRAY'}[$I],  -font => 'code', -justify => 'center' );
	    $frame_crystal->windowCreate('end', -window => $w);
	    push(@{$frame_crystal_list{$key}{"WINDOW_LIST"}}, $w ) ;
	    if ( $key eq "FILE_SYMM" )
	    {
		$w->bind("<Double-1>" => [\&space_group_select_box, \$dfr_file_list{$key}{'ARRAY'}[$I] ]);
	    }
	    else
	    {
		$w->bind("<Double-1>" => [\&file_select_box, \$dfr_file_list{$key}{'ARRAY'}[$I], "" ]);
	    }
	}
	$frame_crystal->insert('end', "\n");
    }

    foreach $key ( keys %dfr_data_list )
    {
	$text = $dfr_data_list{$key}{'LINE'} ;
	$w = $frame_crystal->Label(-text => $text, -font => 'code',-justify => 'center', -relief => 'groove', 
				   -width => $max_length + 20 );
	$frame_crystal_list{$key}{"WINDOW_WORD"} = $w ;
	@{$frame_crystal_list{$key}{"WINDOW_LIST"}} = () ;
	$frame_crystal->windowCreate('end', -window => $w);
	for ($I =0; $I < scalar( @{$dfr_data_list{$key}{'ARRAY'}}); $I++ )
	{
	    $w = $frame_crystal->Entry(-width => 20, -textvariable => \$dfr_data_list{$key}{'ARRAY'}[$I],  -font => 'code', -justify => 'center' );
	    $frame_crystal->windowCreate('end', -window => $w);
	    push(@{$frame_crystal_list{$key}{"WINDOW_LIST"}}, $w ) ;
	}
	$frame_crystal->insert('end', "\n");
    }

    $nn = $j ;
    $n_crystals = $nn ;
    @all_crystals = ( );
    %cryst_keys = () ;
    for ( $IGR = 1; $IGR <= $nn ; $IGR++ )
    {
	$GROUP= join ( '', "SG_CRYST" , $IGR ) ;
	if ( !exists($cryst_keys{$GROUP}  ) )  { push ( @{$cryst_keys{$GROUP}}, $IGR ) ; }
	push(@all_crystals, $GROUP ) ;
    }

    for ($I=0; $I < @all_segments ; $I++ ) 
    {
	$key = $all_segments[$I] ;
	$GROUP= $segment_list[$I]{"CRYSTAL"} ;
	if ( !exists($cryst_keys{$GROUP}  ) )  { $segment_list[$I]{"CRYSTAL"} = "SG_CRYST1" ; }
    }

    empty_segm_frame () ;
    generate_segm_frame () ;

}

################
#
#    segm id groups option change
#
####################
sub empty_segm_frame
{
    my $I; my $w ; my $start_line ;
    for ($I=0; $I < @all_segments ; $I++ ) 
    {
	$w = $segment_list[$I]{"WINDOW_GROUP"} ; $w->destroy() if Tk::Exists($w) ;
	$w = $segment_list[$I]{"WINDOW_SEGM"} ; $w->destroy() if Tk::Exists($w) ;
	$w = $segment_list[$I]{"WINDOW_CRYST"} ; $w->destroy() if Tk::Exists($w) ;
	my $start_line = join (".", $I+1, "2" ) ;
	$frame_segment->delete($start_line, 'end');
    }
    $frame_segment->delete("0.0", 'end');
    $frame_segment->insert('end', "\n");
    $frame_segment->insert('end', "\n");
    $frame_segment->insert('end', "\n");
}

sub empty_group_frame
{
    my $I ; my $w ; my $start_line ;
#	print " $j << $nn \n" ;
	for ($I=$n_groups; $I > 0 ; $I-- ) 
	{
	    $w = $frame_group_list[$I-1]{"WINDOW_WORD"} ; $w->destroy() if Tk::Exists($w) ;
	    $w = $frame_group_list[$I-1]{"WINDOW_OPTION"} ; $w->destroy() if Tk::Exists($w) ;
	    
#	    print " empty frame:",  , "\n" ; 
	    pop ( @all_groups ) ;
	    my $start_line = join (".", $I+4, "2" ) ;
#	    print " window group removed  $I - $start_line\n" ;
	    $frame_group->delete($start_line, 'end');
	}
	$frame_group->insert('end', "\n");
}

sub generate_model_frame
{
#    my (%key_list) = @_ ;
    my $II ;
    my $w ; my $wl ;
    my $text ;

my $g = $frame_model->Frame->pack(-side => 'top');

$w = $g->Button(-text => "import PDB file",-font => 'code',
           -command => \&use_model_macros )->pack(-side => 'left');
$w = $g->Button(-text => "from www PDB",-font => 'code',
           -command => \&use_www_PDB )->pack(-side => 'right');
$w = $g->Button(-text => "tk_read",-font => 'code',
           -command => \&tk_read )->pack(-side => 'left');
$w = $g->Button(-text => "tk_re_image",-font => 'code',
           -command => \&tk_re_image )->pack(-side => 'left');
#    $w->bind("<Double-1>" => [\&file_select_box, \$model_file_list{$key}{'ARRAY'}[$I], "" ]);
#	$frame_model->insert('end', "\n");
	$frame_model->insert('end', "\n");

    foreach $key ( keys %model_file_list )
    {
	my $I ;
	$text = $model_file_list{$key}{'LINE'} ;
	$w = $frame_model->Label(-text => "$text", -font => 'code',-justify => 'center', -relief => 'groove', 
				   -width => $max_length + 20 );
	$frame_model->windowCreate('end', -window => $w);
	for ($I =0; $I < scalar( @{$model_file_list{$key}{'ARRAY'}}); $I++ )
	{
	    $w = $frame_model->Entry(-width => 20, -textvariable => \$model_file_list{$key}{'ARRAY'}[$I],  -font => 'code', -justify => 'center' );
	    $frame_model->windowCreate('end', -window => $w);
	    $w->bind("<Double-1>" => [\&file_select_box, \$model_file_list{$key}{'ARRAY'}[$I], "" ]);
	}
	
	$frame_model->insert('end', "\n");
    }

}


sub generate_group_frame
{
#    my (%key_list) = @_ ;
    my $II ;
    my $w ; my $wl ;
    @all_groups = sort ( @all_groups ) ;
    for ($I=0; $I < $n_groups ; $I++ ) 
    {
	$key = $all_groups[$I] ;
#	print $key, " kind: ", $segment_list[$I]{"GROUP"}, " label item \n" ;
	
	$w = $frame_group->Label(-text => $all_groups[$I], -font => 'code',-justify => 'left', -relief => 'groove', 
				   -background => $Win_background, -foreground => $Win_foreground, 
				   -width => $max_length + 12, -borderwidth => 4 )->pack(-side => 'top', -anchor => 'w' );
	$frame_group->windowCreate('end', -window => $w);
	$wl = $frame_group->Optionmenu(-width => 7, -background => $Win_background, -foreground => $Win_foreground,
				-textvariable => \$all_groups_strategy{$key}, 
				-options => [ @strategy_list ]
	    )->pack();


	$frame_group->windowCreate('end', -window => $wl);
	$frame_group->insert('end', "\n");
	$frame_group_list[$I]{"WINDOW_WORD"} = $w ;
	$frame_group_list[$I]{"WINDOW_OPTION"} = $wl ;
    }
}

sub hit_group_return
{
    my ($e) = @_ ;
#    my (%z) = @_ ;
    my $j = $e->get ;
    my $wl ; my $w ; my $GROUP ;
#    print " Hit_group_return> entry {", $w, " number: ", $j, "\n" ;

    $nn = @all_groups ;

    if ( $j > $nn ) 
    {
#	print " $j > $nn \n" ;
	for ($I=$nn; $I < $j ; $I++ ) 
	{

	$GROUP= join ( '', "SG_GROUP" , $I+1 ) ;
#	print " kind: ", $segment_list[$I]{"GROUP"}, " label item \n" ;
	push( @all_groups, $GROUP ) ; 
	$all_groups_strategy{$GROUP} = "EACH" ;
	$w = $frame_group->Label(-text => $all_groups[$I], -font => 'code',-justify => 'left', -relief => 'groove', 
				   -background => $Win_background, -foreground => $Win_foreground, 
				   -width => $max_length + 12, -borderwidth => 4 )->pack(-side => 'top', -anchor => 'w' );
	$frame_group->windowCreate('end', -window => $w);
	$wl = $frame_group->Optionmenu(-width => 7, -background => $Win_background, -foreground => $Win_foreground,
				-textvariable => \$all_groups_strategy{$GROUP}, 
				-options => [ @strategy_list ]
	    )->pack();
	$frame_group_list[$I]{"WINDOW_WORD"} = $w ;
	$frame_group_list[$I]{"WINDOW_OPTION"} = $wl ;

	$frame_group->windowCreate('end', -window => $wl);
	$frame_group->insert('end', "\n");

	}
    }
    elsif ( $j < $nn )
    {

#	print " $j << $nn \n" ;
	for ($I=$nn; $I > $j ; $I-- ) 
	{
	    $w = $frame_group_list[$I-1]{"WINDOW_WORD"} ; $w->destroy() if Tk::Exists($w) ;
	    $w = $frame_group_list[$I-1]{"WINDOW_OPTION"} ; $w->destroy() if Tk::Exists($w) ;
	    
#	    print " pop groups: ", pop ( @all_groups ), "\n" ; 
	    pop ( @all_groups ) ; 
	    my $start_line = join (".", $I+4, "2" ) ;
#	    print " window group removed  $I - $start_line\n" ;
	    $frame_group->delete($start_line, 'end');
	}
	$frame_group->insert('end', "\n");
#	print " new groups", scalar(@all_groups)," \n" ;
    }
    else
    {
	print " groups ELSE $j == $nn \n" ;
    }

#    print join(" - ", @all_groups), "\n" ;

#     @all_segments = @new_list ;

    empty_segm_frame () ;
    generate_segm_frame () ;


}

sub generate_segm_frame
{
#    my (%key_list) = @_ ;
    my $text ;
    my $w ; my $wl ;


    $text = join(" - ", @all_groups ) ;
    print " all groups{", $text, "}\n" ;


#    if ( $all_segments[@all_segments-1] ne "    " ) { push(@all_segments, "" ) };
#    print "GENERATE_SEGM_FRAME> last segment {", $all_segments[@all_segments-1], "} [", scalar(@all_segments), "]\n" ;
    if ( $all_segments[@all_segments-1] ne "" ) { push(@all_segments, "" ) ; }
    for ($I=0; $I < @all_segments ; $I++ ) 
    {
	$key = $all_segments[$I] ;
#	print $key, " kind: ", $segment_list[$I]{"GROUP"}, " label item \n" ;
	
	$w = $frame_segment->Entry(-textvariable => \$all_segments[$I], -justify => 'left', -relief => 'groove', 
				   -background => $Win_background, -foreground => $Win_foreground, 
				   -width => $max_length + 12, -borderwidth => 4 )->pack(-side => 'top', -anchor => 'w' );
	$segment_list[$I]{"WINDOW_SEGM"} = $w ;
	$w->bind("<Return>", [\&hit_segment_return,  $I ] ) ;
	$frame_segment->windowCreate('end', -window => $w);
#	widgets_segm{$key}{"SEG_ID"} = $w ;
#	print " SEGM list group", $segment_list[$I]{"GROUP"}, " x ", join(" - ", @all_groups ), "\n" ;
	$wl = $frame_segment->Optionmenu(-width => 12, -background => $Win_background, -foreground => $Win_foreground,
				-textvariable => \$segment_list[$I]{"GROUP"}, 
				-variable => \$segment_list[$I]{"GROUP"}, 
				-options => \@all_groups 
	    )->pack();

	$segment_list[$I]{"WINDOW_GROUP"} = $wl ;
	$frame_segment->windowCreate('end', -window => $wl);
#	$frame_segment->insert('end', "\n");

 	$wl = $frame_segment->Optionmenu(-width => 12, -background => $Win_background, -foreground => $Win_foreground  ,
		       -textvariable => \$segment_list[$I]{"CRYSTAL"}, 
		       -variable => \$segment_list[$I]{"CRYSTAL"}, 
		       -options => [ @all_crystals ]
 	    );
	$segment_list[$I]{"WINDOW_CRYST"} = $wl ;
 	$frame_segment->windowCreate('end', -window => $wl);
	$frame_segment->insert('end', "\n");
    }

}

sub hit_segment_return
{
    my ($e, $II) = @_ ;
#    my (%z) = @_ ;
    my $w = $e->get ;
    my $wl ;
#    print " Hit_return> entry {", $w, " number: ", $II, "\n" ;
    $all_segments[$II] = $w ;
#    $all_segments[$II] = uc($w) ;
#    $all_segments[$II] = $II ;
#    $segment_list[$I]{"GROUP"} = $II ;
     my @new_list ;
 
    my $k ; my $nn = @all_segments ; my $j=0 ;
    for ($k = 0; $k < $nn ; $k++ )
    {
#	print " in hit $k all_segments{", $all_segments[$k], 	 "}" ;
	if ( length($all_segments[$k]) > 0 ) 
	    
#	{ push ( @new_list, $all_segments[$k] ) ; print "PUSH print {", $all_segments[$k], "}\n" ; }
	{ 
	    $all_segments[$j] = $all_segments[$k]; 
	    $segment_list[$j]{"GROUP"} = $segment_list[$k]{"GROUP"} ;
	    $segment_list[$j]{"CRYSTAL"} = $segment_list[$k]{"CRYSTAL"} ;
#	    print "PUSH $j from $k {", $all_segments[$k], "}\n" ; 
	    $j++ ; 
	}
	else
	{
#	    print " NO PUSH $j from $k {", $all_segments[$k], "}\n" ; 

	}
    }
#    push(@all_segments, "" ) ; 
    $all_segments[$j] = "" ; $j++ ;
    if ( $j > $nn ) 
    {
#	print " $j >> $nn \n" ;
	my $I = $j-1 ;
	$wl = $frame_segment->Entry(-textvariable => \$all_segments[$I], -justify => 'left', -relief => 'groove', 
				   -background => $Win_background, -foreground => $Win_foreground, 
				   -width => $max_length + 12 )->pack(-side => 'top', -anchor => 'w' );
	$segment_list[$I]{"WINDOW_SEGM"} = $wl ;
	$wl->bind("<Return>", [\&hit_segment_return,  $I ] ) ;
	$frame_segment->windowCreate('end', -window => $wl);
#	widgets_segm{$key}{"SEG_ID"} = $w ;
	$wl = $frame_segment->Optionmenu(-width => 7, -background => $Win_background, -foreground => $Win_foreground,
				-textvariable => \$segment_list[$I]{"GROUP"}, 
				-variable => \$segment_list[$I]{"GROUP"}, 
				-options => [ @all_groups ]
	    )->pack();

	$segment_list[$I]{"WINDOW_GROUP"} = $wl ;
	$frame_segment->windowCreate('end', -window => $wl);
#	$frame_segment->insert('end', "\n");

 	$wl = $frame_segment->Optionmenu(-width => 12, -background => $Win_background, -foreground => $Win_foreground  ,
		       -textvariable => \$segment_list[$I]{"CRYSTAL"}, 
		       -variable => \$segment_list[$I]{"CRYSTAL"}, 
		       -options => [ @all_crystals ]
 	    );
	$segment_list[$I]{"WINDOW_CRYST"} = $wl ;
 	$frame_segment->windowCreate('end', -window => $wl);
	$frame_segment->insert('end', "\n");

	if ( $II != $nn) { $segment_list[$II+1]{"WINDOW_SEGM"}->focus() ; }
 
    }
    elsif ( $j < $nn )
    {

#	print " $j << $nn \n" ;

	$w = $segment_list[$nn-1]{"WINDOW_SEGM"} ; $w->destroy() if Tk::Exists($w) ;
	$w = $segment_list[$nn-1]{"WINDOW_GROUP"} ; $w->destroy() if Tk::Exists($w) ;
	$w = $segment_list[$nn-1]{"WINDOW_CRYST"} ; $w->destroy() if Tk::Exists($w) ;
	my $start_line = join (".", $nn+1, "3" ) ;
	$frame_segment->delete($start_line, 'end');
	$frame_segment->insert('end', "\n");
 	pop ( @all_segments ) ; pop ( @all_segments ) ; 
	push ( @all_segments, "" ) ;
	my $I = @all_segments - 1 ;

	$segment_list[$I]{"GROUP"} = $segment_list[0]{"GROUP"} ;
	$segment_list[$I]{"CRYSTAL"} = $segment_list[0]{"CRYSTAL"} ;
	$key = $all_segments[$I] ;
#	print $key, " kind: ", $segment_list[$I]{"GROUP"}, " label item \n" ;
	
	$w = $frame_segment->Entry(-textvariable => \$all_segments[$I], -justify => 'left', -relief => 'groove', 
				   -background => $Win_background, -foreground => $Win_foreground, 
				   -width => $max_length + 12, -borderwidth => 4 )->pack(-side => 'top', -anchor => 'w' );
	$segment_list[$I]{"WINDOW_SEGM"} = $w ;
	$w->bind("<Return>", [\&hit_segment_return,  $I ] ) ;
	$frame_segment->windowCreate('end', -window => $w);
#	widgets_segm{$key}{"SEG_ID"} = $w ;
#	print " SEGM list group", $segment_list[$I]{"GROUP"}, " x ", join(" - ", @all_groups ), "\n" ;
	$wl = $frame_segment->Optionmenu(-width => 7, -background => $Win_background, -foreground => $Win_foreground,
				-textvariable => \$segment_list[$I]{"GROUP"}, 
				-variable => \$segment_list[$I]{"GROUP"}, 
				-options => \@all_groups 
	    )->pack();

	$segment_list[$I]{"WINDOW_GROUP"} = $wl ;
	$frame_segment->windowCreate('end', -window => $wl);
#	$frame_segment->insert('end', "\n");

 	$wl = $frame_segment->Optionmenu(-width => 12, -background => $Win_background, -foreground => $Win_foreground  ,
		       -textvariable => \$segment_list[$I]{"CRYSTAL"}, 
		       -variable => \$segment_list[$I]{"CRYSTAL"}, 
		       -options => [ @all_crystals ]
 	    );
	$segment_list[$I]{"WINDOW_CRYST"} = $wl ;
 	$frame_segment->windowCreate('end', -window => $wl);
	$frame_segment->insert('end', "\n");

#	print " new ", scalar(@all_segments)," \n" ;
    }
    else
    {
#	print " ELSE $j == $nn \n" ;
	if ( $II+1 != $nn) { $segment_list[$II+1]{"WINDOW_SEGM"}->focus() ; }
    }

#     @all_segments = @new_list ;


#    print join("-", @all_segments), "\n" ;

#    $segment_list[$I]{"WINDOW_GROUP"} = $wl ;

#    foreach $k ( keys %{$e} ) 
#{
#    print " each key:", $k, " - ",  "\n" ;
#}

#    print " Hit_return> array {", @_, "\n" ;
}
sub sg_list_routine
{
    my $II = $_[0] ;
    return ( $all_segments[$II]  ) ;
}

sub gen_entry
{
    print " GEN ENTRY in {", $all_segments[@all_segments], "}\n" ;

}

sub update_main_group_keys
{
    my $nn;
    my $IGR ;
    my $key ;
    pop (@all_segments ) ;

#    print " CREATE MACRO:\n" ;
    for ( $IGR = 1; $IGR <= $my_main{"SG_NGROUP"}[0] ; $IGR++ )
    {
	$GROUP= join ( '', "SG_GROUP" , $IGR ) ;
#	print "IGR: ", $IGR, $GROUP, "\n" ;
	$STRATEGY = join ( '', "SG_GROUP" , $IGR, "_STRATEGY" ) ;
	delete ( $my_main{$GROUP} ) ;
	delete ( $my_main{$STRATEGY} ) ;
    }


    %group_keys = () ;
    $nn = 0 ;
    @{$my_main{"SG_LIST"}} = () ;
    foreach $key ( @all_segments )
    {
	$GROUP = $segment_list[$nn]{"GROUP"} ;
#	print $nn, " my groupp; ", $GROUP, "\n" ;
	push ( @{$group_keys{$GROUP}}, $key ) ; 
	push ( @{$my_main{"SG_LIST"}}, $key ) ; 
	$nn++ ;
    }
    $my_main{"SG_NMOL"}[0] = $nn ;


    $nn = 0 ; foreach $key ( keys %group_keys ) { $nn++ ; }
    $my_main{"SG_NGROUP"}[0] = $nn ;

    for ( $IGR = 1; $IGR <= $my_main{"SG_NGROUP"}[0] ; $IGR++ )
    {
#	    push ( @all_groups, $IGR ) ; 
	$GROUP= join ( '', "SG_GROUP" , $IGR ) ;
#	print " nn IGR: ", $IGR, $GROUP, " nn:", $nn, "\n" ;
	@{$my_main{$GROUP}} = () ;
	push(@{$my_main{$GROUP}}, @{$group_keys{$GROUP}} ) ;
	
	$STRATEGY = join ( '', "SG_GROUP" , $IGR, "_STRATEGY" ) ;
	@{$my_main{$STRATEGY}} = ( $all_groups_strategy{$GROUP} ) ;
#	print " STRATEGY: $STRATEGY {", $all_groups_strategy{$GROUP}, " - ",	@{$my_main{$STRATEGY}}, "}\n" ;
#	push( @{$my_main{$GROUP}}, ) ;
#	printf ( "  %3d %4s  strategy: %20s %8s  | @{$my_main{$GROUP}} \n", $IGR, @{$my_main{$GROUP}}, $STRATEGY, @{$my_main{$STRATEGY}}) ; 
    }
    push (@all_segments, "" ) ;
}
##
##@all_groups = 0 ;
##foreach $key ( keys %group_keys ) 
##{ 
##    push ( @all_groups, $key ) ; 
###    print " push $key \n"; 
##}
##$n_groups = @all_groups ; 


sub update_main_crystal_keys
{
    my $nn;
    my $IGR ;
    my $key ;
    pop (@all_segments ) ;

#    print " CREATE MACRO:\n" ;
    for ( $IGR = 1; $IGR <= $my_main{"SG_NCRYST"}[0] ; $IGR++ )
    {
	$GROUP= join ( '', "SG_CRYST" , $IGR ) ;
	if ( exists( $my_main{$GROUP} ) )  { delete ( $my_main{$GROUP} ) ; }
    }


    %cryst_keys = () ;
    $nn = 0 ;
#    @{$my_main{"SG_CRYST"}} = () ;
    foreach $key ( @all_segments )
    {
	$GROUP = $segment_list[$nn]{"CRYSTAL"} ;
	print $nn, " my groupp; ", $GROUP, "\n" ;
	push ( @{$cryst_keys{$GROUP}}, $key ) ; 
	$nn++ ;
    }
    if ( $nn < 1 ) 
    { 
	$nn = 1 ;
	$GROUP= join ( '', "SG_CRYST" , $nn ) ;
 	push ( @{$cryst_keys{$GROUP}}, "A" ) ; 
	@all_segments = ( "A" ) ;
    }
    $my_main{"SG_NCRYST"}[0] = $nn ;


    $nn = 0 ; foreach $key ( keys %cryst_keys ) { $nn++ ; }
    if ( $nn < 1 ) { $nn = 1 ; }
    $my_main{"SG_NCRYST"}[0] = $nn ;

    for ( $IGR = 1; $IGR <= $my_main{"SG_NCRYST"}[0] ; $IGR++ )
    {
	$GROUP= join ( '', "SG_CRYST" , $IGR ) ;
	@{$my_main{$GROUP}} = () ;
	push(@{$my_main{$GROUP}}, @{$cryst_keys{$GROUP}} ) ;
#	printf ( "  %3d %4s  | @{$my_main{$GROUP}} $GROUP \n", $IGR, @{$my_main{$GROUP}} ) ; 
    }
    push (@all_segments, "" ) ;

    @all_crystals = () ;
    foreach $key ( keys %cryst_keys ) 
    { 
	push ( @all_crystals, $key ) ; 
    }
    $n_crystals = @all_crystals ;

#   my $MOLECULES = join ( ' ', @{$my_main{"SG_LIST"}} ) ;


    $key = "FILE_CELL" ; 
    @{$my_main{$key}} = @{$dfr_file_list{$key}{'ARRAY'}} ;
    if ( $#{$my_main{$key}} <= 0 ) { @{$my_main{$key}} = ( "cell.dat") ; print " add cell dat \n" ;}
	 
    $key = "FILE_REFL" ; 
    @{$my_main{$key}} = @{$dfr_file_list{$key}{'ARRAY'}} ;
    if ( $#{$my_main{$key}} <= 0 ) { @{$my_main{$key}} = ("diffract.dat") ; }
    
    $key = "FILE_SYMM" ; 
    @{$my_main{$key}} = @{$dfr_file_list{$key}{'ARRAY'}} ;
    if ( $#{$my_main{$key}} < 0 ) { @{$my_main{$key}} = ("p1") ; }

    $key = "DFR_RES_MIN" ; @{$my_main{$key}} = @{$dfr_data_list{$key}{'ARRAY'}} ;
    if ( $#{$my_main{$key}} < 0 ) { @{$my_main{$key}} = ( "10.0") ; }
    $key = "DFR_RES_MAX" ; @{$my_main{$key}} = @{$dfr_data_list{$key}{'ARRAY'}} ;
    if ( $#{$my_main{$key}} < 0 ) { @{$my_main{$key}} = ("3.0") ; }

}


sub file_select_box
{
#    my ( $event, %parent, $key, $I) = @_ ;
    my ( $event, $key, $filter_file) = @_ ;
    my @all_files ;
    my @list_files = () ;
#    my $filter_file = "[0-9,A-Z,a-z]" ;
#    my $filter_file = "" ;

    print " box:", ${$key},  "\n" ;
    my $tt = ${$key} ;
    my $lb; my $nw ; my $w ; my $ff ; my $my_file ;

    $nw = MainWindow->new (-width => 600, -height => 350, -background => $Win_background, -foreground => $Win_foreground );
    $nw->title("Tk: main config:: file replacement for {$tt}");

    my $f = $nw->Text( -width => $max_length + 30, -height => 1, -background => $Win_background, -foreground => $Win_foreground,
                   -wrap => 'none')->pack(-expand => 'x', -fill => 'both', -side => 'top');
    $f->configure(-state => 'normal');
    $w = $f->Label(-text => "File Filter", -font => 'code',-justify => 'center', -relief => 'groove', 
				    -width => $max_length );
    $f->windowCreate('end', -window => $w);
    $w = $f->Entry(-width => 60, -textvariable => \$filter_file, -justify => 'left' );
    $f->windowCreate('end', -window => $w);

    $w->bind("<Key>", [\&list_regenerate, \@all_files, \@list_files, \$filter_file, \$lb ] ) ;


    $f = $nw->Text(-background => $Win_background, -foreground => $Win_foreground)->pack(-side => 'bottom');
    $f->Button(-text => "Cancel", -font => 'code',
	       -command => sub {  $nw->destroy() if Tk::Exists($nw) ; })->pack(-side => 'left');
    $f->Button(-text => "Done",-font => 'code',
	       -command => sub {  
		  my $x_file_name = $lb->get($lb->curselection()) ;
#		  print "the file name: {", $x_file_name, "}\n" ;
#		  $parent{$key}{'ARRAY'}[$I] = $x_file_name ;
		  ${$key} = $x_file_name ;
		   $nw->destroy() if Tk::Exists($nw) ; 
	       })->pack(-side => 'bottom');


    my $path = './' ;
    opendir( ALLFILES, $path );
    @all_files = readdir( ALLFILES );
    closedir( ALLFILES );

    $lb = $nw->Scrolled("Listbox", -scrollbars => "e", -selectmode => "single")->pack (-fill => 'both' ) ;

    @list_files = () ;
    foreach $my_file ( sort( @all_files ) )
    {
	if ( $my_file =~ $filter_file ) { push( @list_files, $my_file ) ; }
    }
#    @list_files = @all_files ;


    $lb->insert('end', @list_files ) ;
#    $lb->insert('end', qw/red green yellow blue/) ;

    $lb->bind('<Button-1>', 
	      sub{ 
		  my $x_file_name = $lb->get($lb->curselection()) ;
#		  print "the file name: {", $x_file_name, "}\n" ;
	      } ) ;
    $lb->bind('<Double-1>', 
	      sub{ 
		  my $x_file_name = $lb->get($lb->curselection()) ;
#		  print "the CLICK file name: {", $x_file_name, "}\n" ;
		  if ( -d $x_file_name ) 
		  { 
		      print " directory file \n" ; 
		  } 
		  else
		  {
		      ${$key} = $x_file_name ;
		      $nw->destroy() if Tk::Exists($nw) ; 
		  }
	      } ) ;

}


sub space_group_select_box
{
#    my ( $event, %parent, $key, $I) = @_ ;
    my ( $event, $key) = @_ ;
    my @list_files = () ;
#    my $filter_file = "[0-9,A-Z,a-z]" ;
    my $filter_file = "" ;

#    print " box:", ${$key},  "\n" ;
    my $tt = ${$key} ;
    my $lb; my $nw ; my $w ; my $ff ; my $my_file ;

    $nw = MainWindow->new (-width => 600, -height => 350, -background => $Win_background, -foreground => $Win_foreground );
    $nw->title("Tk: main config:: space group selector {$tt}");

    my $f = $nw->Text( -width => $max_length + 30, -height => 1, -background => $Win_background, -foreground => $Win_foreground,
                   -wrap => 'none')->pack(-expand => 'x', -fill => 'both', -side => 'top');
    $f->configure(-state => 'normal');
    $w = $f->Label(-text => "Space Group Filter", -font => 'code',-justify => 'center', -relief => 'groove', 
				    -width => $max_length );
    $f->windowCreate('end', -window => $w);
    $w = $f->Entry(-width => 20, -textvariable => \$filter_file, -justify => 'left' );
    $f->windowCreate('end', -window => $w);

    $w->bind("<Key>", [\&main_config::list_regenerate, \@all_space_groups, \@list_files, \$filter_file, \$lb ] ) ;


    $f = $nw->Text(-background => $Win_background, -foreground => $Win_foreground)->pack(-side => 'bottom');
    $f->Button(-text => "Cancel", -font => 'code',
	       -command => sub {  $nw->destroy() if Tk::Exists($nw) ; })->pack(-side => 'left');
    $f->Button(-text => "Done",-font => 'code',
	       -command => sub {  
		  my $x_file_name = $lb->get($lb->curselection()) ;
#		  print "the file name: {", $x_file_name, "}\n" ;
#		  $parent{$key}{'ARRAY'}[$I] = $x_file_name ;
		  ${$key} = $x_file_name ;
		   $nw->destroy() if Tk::Exists($nw) ; 
	       })->pack(-side => 'bottom');


    $lb = $nw->Scrolled("Listbox", -scrollbars => "e", -selectmode => "single")->pack (-fill => 'both' ) ;

    @list_files = () ;
    foreach $my_file ( sort( @all_space_groups ) )
    {
	if ( $my_file =~ $filter_file ) { push( @list_files, $my_file ) ; }
    }
#    @list_files = @all_files ;


    $lb->insert('end', @list_files ) ;
#    $lb->insert('end', qw/red green yellow blue/) ;

    $lb->bind('<Button-1>', 
	      sub{ 
		  my $x_file_name = $lb->get($lb->curselection()) ;
#		  print "space group: {", $x_file_name, "}\n" ;
	      } ) ;
    $lb->bind('<Double-1>', 
	      sub{ 
		  my $x_file_name = $lb->get($lb->curselection()) ;
#		  print "the CLICK file name: {", $x_file_name, "}\n" ;
		  ${$key} = $x_file_name ;
		  $nw->destroy() if Tk::Exists($nw) ; 
	      } ) ;

}

sub create_all_macros
{
    update_main_crystal_keys() ;
    update_main_group_keys() ;
 
    main_config::write_main_config_file ( "main_config.data", %my_main ) ; 
#}
     print "macro file:", $MACRO_FILE, "\n" ;
     my @system_string = ( $MACRO_FILE ) ;
     
     
     push (@system_string, "--doit" ) ;
     my $call = join (" ", @system_string ) ;
     print $call, "\n" ;
     system ( $call ) ;
#     exit;
}

sub create_read
{
    update_main_crystal_keys() ;
    update_main_group_keys() ;
 
    main_config::write_main_config_file ( "main_config.data", %my_main ) ; 
#}

    my $MACRO = "create_read.pl" ;
#     print "macro file:", $MACRO, "\n" ;
     my @system_string = ( $MACRO ) ;
     
     
     push (@system_string, "--doit" ) ;
     my $call = join (" ", @system_string ) ;
     print $call, "\n" ;
     system ( $call ) ;
#     exit;
}


sub use_diffraction_macros
{
    my $diffr_file = "my.mtz" ;
    my $filter_file = "" ;
#    file_select_box ( \$diffr_file, \$filter );
    print " IMPORT diffraction file", $diffr_file, "\n" ;
    my @all_files ;
    my @list_files = () ;

    my $lb; my $NW ; my $w ; my $ff ; my $my_file ;

    $NW = MainWindow->new (-width => 600, -height => 350, -background => $Win_background, -foreground => $Win_foreground );
    $NW->title("Tk: main config:: diffraction file processing");

    my $f = $NW->Text( -width => $max_length + 30, -height => 1, -background => $Win_background, -foreground => $Win_foreground,
                   -wrap => 'none')->pack(-expand => 'x', -fill => 'both', -side => 'top');
    $f->configure(-state => 'normal');
    $w = $f->Label(-text => "File Filter", -font => 'code',-justify => 'center', -relief => 'groove', 
				    -width => $max_length );
    $f->windowCreate('end', -window => $w);
    $w = $f->Entry(-width => 60, -textvariable => \$filter_file, -justify => 'left' );
    $f->windowCreate('end', -window => $w);

    $w->bind("<Key>", [\&main_config::list_regenerate, \@all_files, \@list_files, \$filter_file, \$lb ] ) ;


    $f = $NW->Text(-background => $Win_background, -foreground => $Win_foreground)->pack(-side => 'bottom');
    $f->Button(-text => "Cancel", -font => 'code',
	       -command => sub { $NW->destroy() if Tk::Exists($NW) ; })->pack(-side => 'left');
    $f->Button(-text => "Doit",-font => 'code',
	       -command => sub 
	       {  
		   $diffr_file = $lb->get($lb->curselection()) ;
		   process_diffraction_file ( $diffr_file ) ;
		   $NW->destroy() if Tk::Exists($NW) ; 
	       }
	)->pack(-side => 'bottom');
    

    my $path = './' ;
    opendir( ALLFILES, $path );
    @all_files = readdir( ALLFILES );
    closedir( ALLFILES );

    $lb = $NW->Scrolled("Listbox", -scrollbars => "e", -selectmode => "single")->pack (-fill => 'both' ) ;

    @list_files = () ;
    foreach $my_file ( sort( @all_files ) )
    {
	if ( uc($my_file) =~ uc($filter_file) ) { push( @list_files, $my_file ) ; }
    }
#    @list_files = @all_files ;


    $lb->insert('end', @list_files ) ;
#    $lb->insert('end', qw/red green yellow blue/) ;

    $lb->bind('<Button-1>', 
	      sub{ 
		  $diffr_file = $lb->get($lb->curselection()) ;
#		  print "the file name: {", $x_file_name, "}\n" ;
	      } ) ;
    $lb->bind('<Double-1>', 
	      sub{ 
		  $diffr_file = $lb->get($lb->curselection()) ;
		  print "the CLICK file name: {", $diffr_file, "}\n" ;
		  if ( -d $diffr_file ) 
		  { 
		      print " directory file \n" ; 
		  } 
		  else
		  {
		      process_diffraction_file ( $diffr_file ) ;
#		      ${$key} = $diffr_file ;
		      $NW->destroy() if Tk::Exists($NW) ; 
		  }
	      } ) ;

}

sub process_diffraction_file
{
    my $diffr_file = shift (@_) ;
    
    if ( $diffr_file =~ ".mtz" )
    {
	my @system_string = ( "use_mtz.pl" ) ;
	push (@system_string, "--mtz", $diffr_file ) ;
	push (@system_string, "--doit" ) ;
	my $call = join (" ", @system_string ) ;
	print $call, "\n" ;
	system ( $call ) ;
	print "selected MTZ file: {", $diffr_file, "}\n" ;
    }
    elsif ( $diffr_file =~ ".sca" )
    {
	my @system_string = ( "use_sca.pl" ) ;
	push (@system_string, "--file", $diffr_file ) ;
	push (@system_string, "--doit" ) ;
	my $call = join (" ", @system_string ) ;
	print $call, "\n" ;
	system ( $call ) ;
	print "selected SCALEPACK file: {", $diffr_file, "}\n" ;
    }
    elsif ( $diffr_file =~ ".cif" ||  $diffr_file =~ ".sf")
    {
	my @system_string = ( "use_cif.pl" ) ;
	push (@system_string, "--cif_file", $diffr_file ) ;
	push (@system_string, "--doit" ) ;
	my $call = join (" ", @system_string ) ;
	print $call, "\n" ;
	system ( $call ) ;
	print "selected CIF file: {", $diffr_file, "}\n" ;
    }
    elsif ( $diffr_file =~ ".fcf" )
    {
	print "selected SHELX file: {", $diffr_file, "}\n" ;
    }
    else
    {
	print " unrecognized file type: {", $diffr_file, "}\n" ;
    }
    $conf_file = "main_config.data" ; 
    %my_main = main_config::read_main_config_file ( $conf_file ) ; 
    $key = "FILE_SYMM" ; ${$dfr_file_list{$key}{'ARRAY'}}[0] = ${$my_main{$key}}[0] ;
    print "space group: {", @{$dfr_file_list{$key}{'ARRAY'}}, " main: ", @{$my_main{$key}}, "}\n" ;
    $key = "DFR_RES_MAX" ; ${$dfr_data_list{$key}{'ARRAY'}}[0] = ${$my_main{$key}}[0] ;
    $key = "DFR_RES_MIN" ; ${$dfr_data_list{$key}{'ARRAY'}}[0] = ${$my_main{$key}}[0] ;
#		   $modl_file = $diffr_file ;
#		   empty_segm_frame () ;
#		   empty_group_frame () ;
#		   %my_main = main_config::read_main_config_file ( $conf_file ) ; 
    update_from_main_config_data () ;
#		   generate_group_frame () ;
#		   generate_segm_frame () ;
#
}

sub use_model_macros
{
    my $modl_file="my.pdb" ;
    my $filter_file = "pdb" ;

    my @all_files ;
    my @list_files = () ;

    my $lb; my $NW ; my $w ; my $ff ; my $my_file ;

    $NW = MainWindow->new (-width => 600, -height => 350, -background => $Win_background, -foreground => $Win_foreground );
    $NW->title("Tk: main config:: PDB file processing");

    my $f = $NW->Text( -width => $max_length + 30, -height => 1, -background => $Win_background, -foreground => $Win_foreground,
                   -wrap => 'none')->pack(-expand => 'x', -fill => 'both', -side => 'top');
    $f->configure(-state => 'normal');
    $w = $f->Label(-text => "File Filter", -font => 'code',-justify => 'center', -relief => 'groove', 
				    -width => $max_length );
    $f->windowCreate('end', -window => $w);
    $w = $f->Entry(-width => 60, -textvariable => \$filter_file, -justify => 'left' );
    $f->windowCreate('end', -window => $w);

    $w->bind("<Key>", [\&main_config::list_regenerate, \@all_files, \@list_files, \$filter_file, \$lb ] ) ;


    $f = $NW->Text(-background => $Win_background, -foreground => $Win_foreground)->pack(-side => 'bottom');
    $f->Optionmenu(-width => 30, -background => $Win_background, -foreground => $Win_foreground,
				-textvariable => \$NCS_group_def, 
				-options => [ @NCS_group_list ]
	    )->pack();
    $f->Button(-text => "Cancel", -font => 'code',
	       -command => sub {  $NW->destroy() if Tk::Exists($NW) ; })->pack(-side => 'left');
    $f->Button(-text => "Doit",-font => 'code',
	       -command => sub 
	       {  
		   my $x_file_name = $lb->get($lb->curselection()) ;
		   print "selected PDB file: {", $x_file_name, "}\n" ;
		   $modl_file = $x_file_name ;
		   my @system_string = ( "create_auto_start.pl" ) ;
		   push (@system_string, "--pdb", $modl_file ) ;
		   my @x = split ( "_", $NCS_group_def ) ;
		   my $NCS_string = $x[$#x] ;
		   push (@system_string, "--groups", $NCS_string ) ;
		   push (@system_string, "--doit" ) ;
		   my $call = join (" ", @system_string ) ;
		   print $call, "\n" ;
		   system ( $call ) ;
		   empty_segm_frame () ;
		   empty_group_frame () ;
		   if ( -f "main_config.data" )
		   {    $conf_file = "main_config.data" ; }
		   else
		   {    $conf_file = join ('', $ENV{"MAIN_CONF"}, "main_config.data" ) ; }
		   %my_main = main_config::read_main_config_file ( $conf_file ) ; 
		   update_from_main_config_data () ;
		   generate_group_frame () ;
		   generate_segm_frame () ;
#		   @x = @{$my_main{"SG_LIST"}} ; print " in import segs:", join( " ", @x), "\n" ;

		   $key = "FILE_SYMM" ; ${$dfr_file_list{$key}{'ARRAY'}}[0] = ${$my_main{$key}}[0] ;
#		   print " space group from atoms: ", ${$dfr_file_list{$key}{'ARRAY'}}[0], " = ", ${$my_main{$key}}[0] , "\n";
		   $NW->destroy() if Tk::Exists($NW) ; 
	       }
	)->pack(-side => 'bottom');
    

    my $path = './' ;
    opendir( ALLFILES, $path );
    @all_files = readdir( ALLFILES );
    closedir( ALLFILES );

    $lb = $NW->Scrolled("Listbox", -scrollbars => "e", -selectmode => "single")->pack (-fill => 'both' ) ;

    @list_files = () ;
    foreach $my_file ( sort( @all_files ) )
    {
	if ( uc($my_file) =~ uc($filter_file) ) { push( @list_files, $my_file ) ; }
    }
#    @list_files = @all_files ;


    $lb->insert('end', @list_files ) ;
#    $lb->insert('end', qw/red green yellow blue/) ;

    $lb->bind('<Button-1>', 
	      sub{ 
		  my $x_file_name = $lb->get($lb->curselection()) ;
#		  print "the file name: {", $x_file_name, "}\n" ;
	      } ) ;
    $lb->bind('<Double-1>', 
	      sub{ 
		  my $x_file_name = $lb->get($lb->curselection()) ;
#		  print "the CLICK file name: {", $x_file_name, "}\n" ;
		  if ( -d $x_file_name ) 
		  { 
		      print " directory file \n" ; 
		  } 
		  else
		  {
#		      ${$key} = $x_file_name ;
		      $NW->destroy() if Tk::Exists($NW) ; 
		  }
	      } ) ;

}


sub use_www_PDB
{
    my $NW ;
    my $x_file_name="mine" ; my $modl_file ; my $pdb_id ;

    $NW = MainWindow->new (-width => 600, -height => 350, -background => $Win_background, -foreground => $Win_foreground );
    $NW->title("Tk: main config:: www PDB file imoprt");

    my $f = $NW->Text( -width => $max_length + 30, -height => 1, -background => $Win_background, -foreground => $Win_foreground,
                   -wrap => 'none')->pack(-expand => 'x', -fill => 'both', -side => 'top');
    $f->configure(-state => 'normal');
    $w = $f->Label(-text => "PDB id", -font => 'code',-justify => 'center', -relief => 'groove', 
				    -width => $max_length );
    $f->windowCreate('end', -window => $w);
    $w = $f->Entry(-width => 60, -textvariable => \$pdb_id, -justify => 'left' );
    $f->windowCreate('end', -window => $w);

    $f = $NW->Text(-background => $Win_background, -foreground => $Win_foreground)->pack(-side => 'bottom');
    $f->Optionmenu(-width => 30, -background => $Win_background, -foreground => $Win_foreground,
				-textvariable => \$NCS_group_def, 
				-options => [ @NCS_group_list ]
	    )->pack();
    $f->Button(-text => "Cancel", -font => 'code',
	       -command => sub {  $NW->destroy() if Tk::Exists($NW) ; })->pack(-side => 'left');
    $f->Button(-text => "Doit",-font => 'code',
	       -command => sub 
	       {  
		   my $x_file_name = uc ($pdb_id) ;
		   $x_file_name = $x_file_name.".pdb";
		   if (-e $x_file_name) {
		   } else {
		       getstore ("http://www.rcsb.org/pdb/files/$x_file_name", $x_file_name);
		   }
		   print "selected PDB file: {", $x_file_name, "}\n" ;
		   $modl_file = $x_file_name ;
		   my @system_string = ( "create_auto_start.pl" ) ;
		   push (@system_string, "--pdb", $modl_file ) ;
		   my @x = split ( "_", $NCS_group_def ) ;
		   my $NCS_string = $x[$#x] ;
		   push (@system_string, "--groups", $NCS_string ) ;
		   push (@system_string, "--doit" ) ;
		   my $call = join (" ", @system_string ) ;
		   print $call, "\n" ;
		   system ( $call ) ;
		   empty_segm_frame () ;
		   empty_group_frame () ;
		   if ( -f "main_config.data" )
		   {    $conf_file = "main_config.data" ; }
		   else
		   {    $conf_file = join ('', $ENV{"MAIN_CONF"}, "main_config.data" ) ; }
		   %my_main = main_config::read_main_config_file ( $conf_file ) ; 
		   update_from_main_config_data () ;
		   generate_group_frame () ;
		   generate_segm_frame () ;
		   $key = "FILE_SYMM" ; ${$dfr_file_list{$key}{'ARRAY'}}[0] = ${$my_main{$key}}[0] ;
#		   print " space group from atoms: ", ${$dfr_file_list{$key}{'ARRAY'}}[0], " = ", ${$my_main{$key}}[0] , "\n";
		   $NW->destroy() if Tk::Exists($NW) ; 
	       }
	)->pack(-side => 'bottom');
}

sub tk_read
{
    update_main_crystal_keys() ;
    update_main_group_keys() ;
 
    main_config::write_main_config_file ( "main_config.data", %my_main ) ; 

    my @system_string = ( "tk_config.pl -m create_read.pl&" ) ;
    my $call = join (" ", @system_string ) ;
    print $call, "\n" ;
    system ( $call ) ;
}
sub tk_re_image
{
    my @system_string = ( "tk_re_image.pl&" ) ;
    my $call = join (" ", @system_string ) ;
    print $call, "\n" ;
    system ( $call ) ;
}

sub update_from_main_config_data
{
my $key ;

my ( $nn, $kind ) ;
# print "segm list:", $my_main{"SG_LIST"}, "\n" ;
@all_segments = () ;
foreach $kind ( @{$my_main{"SG_LIST"}} ) 
{
    push ( @all_segments, $kind ) ;
}

$key = "FILE_CELL" ;
@{$dfr_file_list{$key}}{'LINE'} = "UNIT CELL DATA " ;
for ($I =0; $I < scalar( @{$my_main{$key}}); $I++ )
{ $dfr_file_list{$key}{'ARRAY'}[$I] = ${$my_main{$key}}[$I] ; }
$dfr_file_list{$key}{'KIND'} = "DIFFRACT" ;

$key = "FILE_REFL" ;
@{$dfr_file_list{$key}}{'LINE'} = "DIFFRACTION DATA" ;
for ($I =0; $I < scalar( @{$my_main{$key}}); $I++ )
{ $dfr_file_list{$key}{'ARRAY'}[$I] = ${$my_main{$key}}[$I] ; }
$dfr_file_list{$key}{'KIND'} = "DIFFRACT" ;

$key = "FILE_SYMM" ;
@{$dfr_file_list{$key}}{'LINE'} = "SPACE GROUP" ;
for ($I =0; $I < scalar( @{$my_main{$key}}); $I++ )
{ $dfr_file_list{$key}{'ARRAY'}[$I] = ${$my_main{$key}}[$I] ; }
$dfr_file_list{$key}{'KIND'} = "DIFFRACT" ;

$key = "DFR_RES_MIN" ;
@{$dfr_data_list{$key}}{'LINE'} = "RESOLUTION LOW" ;
for ($I =0; $I < scalar( @{$my_main{$key}}); $I++ )
{ $dfr_data_list{$key}{'ARRAY'}[$I] = ${$my_main{$key}}[$I] ; }
$dfr_data_list{$key}{'KIND'} = "DIFFRACT" ;

$key = "DFR_RES_MAX" ;
@{$dfr_data_list{$key}}{'LINE'} = "RESOLUTION HIGH" ;
for ($I =0; $I < scalar( @{$my_main{$key}}); $I++ )
{ $dfr_data_list{$key}{'ARRAY'}[$I] = ${$my_main{$key}}[$I] ; }
$dfr_data_list{$key}{'KIND'} = "DIFFRACT" ;


#$key = "SEGMENTS" ;
#@{$model_file_list{$key}}{'LINE'} = "SEGMENT NAME LIST" ;
#@{$model_file_list{$key}{'ARRAY'}} = @all_segments ;
#$model_file_list{$key}{'KIND'} = "MODEL" ;

$key = "FILE_MODEL" ;
@{$model_file_list{$key}}{'LINE'} = "ATOMIC MODEL" ;
@{$model_file_list{$key}{'ARRAY'}} = @{$my_main{$key}} ;
$model_file_list{$key}{'KIND'} = "MODEL" ;

# $key = "FILE_CTAB" ;
# @{$model_file_list{$key}}{'LINE'} = "CONNECTIVITY TABLE" ;
# @{$model_file_list{$key}{'ARRAY'}} = @{$my_main{$key}} ;
# $model_file_list{$key}{'KIND'} = "MODEL" ;
 
$key = "FILE_SEQUENCE" ;
if ( !exists($my_main{$key}  ) )  { push ( @{$my_main{$key}}, "seqeunce.dat" ) ; }
@{$model_file_list{$key}}{'LINE'} = "SEQUENCE DATA" ;
@{$model_file_list{$key}{'ARRAY'}} = @{$my_main{$key}} ;
$model_file_list{$key}{'KIND'} = "MODEL" ;

$key = "FILE_TOPO" ;
if ( !exists($my_main{$key}  ) )  { push ( @{$my_main{$key}}, "" ) ; }
@{$model_file_list{$key}}{'LINE'} = "TOPOLOGY DATA" ;
@{$model_file_list{$key}{'ARRAY'}} = @{$my_main{$key}} ;
$model_file_list{$key}{'KIND'} = "MODEL" ;

$key = "FILE_MY_TOPO" ;
if ( !exists($my_main{$key}  ) )  { push ( @{$my_main{$key}}, "" ) ; }
@{$model_file_list{$key}}{'LINE'} = "MY TOPOLOGY DATA" ;
@{$model_file_list{$key}{'ARRAY'}} = @{$my_main{$key}} ;
$model_file_list{$key}{'KIND'} = "MODEL" ;

foreach $key ( sort keys %my_main )
{
    if ( $key =~ m"SG\_" )
    { 
	@{$segm_list{$key}}{'LINE'} = ($key) ;
	@{$segm_list{$key}}{'VALUE'} = @{$my_main{$key}} ;
	@{$segm_list{$key}}{'LIST'} = @{$my_main{$key}} ;
	$segm_list{$key}{'KIND'} = "LIST" ;
#	print " segm: ", $key, "} ", join( " ", @{$segm_list{$key}}{'VALUE'}), "\n" ;
    }
}

my ($group, $IGR, $I, $SEGM, $my_group, $GROUP, $STRATEGY ) ;

# my $nn ; 
$nn = 0 ;
@all_groups = () ;
foreach $key ( @all_segments )
{
#    print " key in list {", $key, "}\n" ;
    $my_group = "-1" ;
    for ( $IGR = 1; $IGR <= $my_main{"SG_NGROUP"}[0] ; $IGR++ )
    {
#	    push ( @all_groups, $IGR ) ; 
	$GROUP= join ( '', "SG_GROUP" , $IGR ) ;
	if ( !exists($group_keys{$GROUP}  ) )  { push ( @{$group_keys{$GROUP}}, $IGR ) ; }
	
	$STRATEGY = join ( '', "SG_GROUP" , $IGR, "_STRATEGY" ) ;
	$all_groups_strategy{$GROUP} = $my_main{$STRATEGY}[0] ;

#	if ( exists($my_main{$GROUP}  ) ) 
#	{
#	    printf ( " %3d %4s  | @{$my_main{$GROUP}} \n", $IGR, @{$my_main{$STRATEGY}} ) ; 
#	}
	foreach $SEGM ( @{$my_main{$GROUP}} )
	{
	    if ( $SEGM eq $key ) 
	    {
		$my_group = $GROUP ;
	    }
	}
	
    }
#    print " segment $key is in $my_group igr: $IGR \n" ;
#	$segment_list{$key}{"GROUP"} = $my_group ;
    $segment_list[$nn]{"GROUP"} = $my_group ;
#    $segment_list("CRYSTAL") = $my_crystal ;
    $nn++ ;
}
    

$nn = 0 ;
foreach $key ( @all_segments )
{
    $my_group = $my_main{$GROUP}[@{$my_main{$GROUP}}-1] ;
    for ( $IGR = 1; $IGR <= $my_main{"SG_NCRYST"}[0] ; $IGR++ )
    {
	$GROUP= join ( '', "SG_CRYST" , $IGR ) ;
	if ( !exists($cryst_keys{$GROUP}  ) )  { push ( @{$cryst_keys{$GROUP}}, $IGR ) ; }
	
	foreach $SEGM ( @{$my_main{$GROUP}} )
	{
	    if ( $SEGM eq $key ) 
	    {
		$my_group = $GROUP ;
	    }
	}
	
    }
#    print " segment $key is in crystal $my_group igr: $IGR \n" ;
    $segment_list[$nn]{"CRYSTAL"} = $my_group ;
    $nn++ ;
}



#    foreach $key ( keys %group_keys ) { push ( @all_groups, @{$group_keys{$key}} ) ; print " push $key \n"; }
foreach $key ( keys %group_keys ) 
{ 
    push ( @all_groups, $key ) ; 
#    print " push $key \n"; 
}
$n_groups = @all_groups ; 

@all_crystals = () ;
foreach $key ( keys %cryst_keys ) 
{ 
    push ( @all_crystals, $key ) ; 
#    print " push cryst $key \n"; 
}
$n_crystals = @all_crystals ;

}
