#!/usr/bin/env perl
use strict;
use lib $ENV{ 'MAIN_CONF'}  ;
use main_config ;
my %commands = () ;

if ( @ARGV <= 0 ) { push ( @{$commands{'help'}}, ' ' ) ; } 
else { (%commands) = main_config::get_commands ( @ARGV ) ; }

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 ) ; 

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

if ( !exists($my_main{"DFR_LIMIT_H"} ) ) { push ( @{$my_main{"DFR_LIMIT_H"}}, 0 ) };
if ( !exists($my_main{"DFR_LIMIT_K"} ) ) { push ( @{$my_main{"DFR_LIMIT_K"}}, 0 ) };
if ( !exists($my_main{"DFR_LIMIT_L"} ) ) { push ( @{$my_main{"DFR_LIMIT_L"}}, 0 ) };
if ( !exists($my_main{"FILE_CELL"} ) ) { push ( @{$my_main{"FILE_CELL"}}, "" ) };
if ( !exists($my_main{"FILE_REFL"} ) ) { push ( @{$my_main{"FILE_REFL"}}, "diffract.dat" ) };
if ( !exists($my_main{"FILE_SEQUENCE"} ) ) { push ( @{$my_main{"FILE_SEQUENCE"}}, "" ) };
if ( !exists($my_main{"FILE_MODEL_BACK"} ) ) { push ( @{$my_main{"FILE_MODEL_BACK"}}, "" ) };
if ( !exists($my_main{"FILE_MODEL_TARGET"} ) ) { push ( @{$my_main{"FILE_MODEL_TARGET"}}, "" ) };
if ( !exists($my_main{"FILE_MAPS"} ) ) { push ( @{$my_main{"FILE_MAPS"}}, "" ) };
if ( !exists($my_main{"FILE_MY_TOPO"} ) ) { push ( @{$my_main{"FILE_MY_TOPO"}}, "" ) };
if ( !exists($my_main{"FILE_TOPO"} ) ) { push ( @{$my_main{"FILE_TOPO"}}, "POLAR_H" ) };
if ( !exists($my_main{"DFR_FORMAT"} ) ) { push ( @{$my_main{"DFR_FORMAT"}}, "MAIN" ) };
if ( !exists($my_main{"CRYST_DATA"} ) ) { push ( @{$my_main{"CRYST_DATA"}}, "BRAGG" ) };
if ( !exists($my_main{"INIT_MAP"} ) ) { push ( @{$my_main{"INIT_MAP"}}, "NONE" ) };

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

my $MACRO_FILE = "read.com" ;
my $PROC_ERROR = "FALSE" ;
my $doit = "FALSE" ;
my $SEGM ;


my $keyword ; 
foreach $keyword ( sort keys (%commands) ) 
{
    if ( $keyword eq 'h' || substr($keyword, 0,4) eq "help" ) { goto HELP }
    if ( $keyword eq 'a' || substr($keyword, 0,4) eq "atom" ) { goto ATOM }
    if ( $keyword eq 'b' || substr($keyword, 0,4) eq "back" ) { goto BACK }
    if ( $keyword eq 'g' || substr($keyword, 0,6) eq "target" ) { goto TARGET }
    if ( $keyword eq 'c' || substr($keyword, 0,4) eq "cell" ) { goto CELL }
#    if ( $keyword eq 'c' || substr($keyword, 0,4) eq "ctab" ) { goto CTAB }
    if ( $keyword eq 'd' || substr($keyword, 0,5) eq "diffr" ) { goto DIFFR }
    if ( $keyword eq 'f' || substr($keyword, 0,10) eq "format_dfr" ) { goto DFR_FORM }
    if ( $keyword eq 'l' || substr($keyword, 0,5) eq "limit" || substr($keyword, 0,3) eq "hkl" ) { goto HKL }
    if ( $keyword eq 'i' || substr($keyword, 0,4) eq "init" ) { goto INIT_MAP }
    if ( $keyword eq 'm' || substr($keyword, 0,3) eq "map" ) { goto MAP }
    if ( $keyword eq 'o' || substr($keyword, 0,6) eq "output" ) { goto OUTPUT }
    if ( $keyword eq 'q' || substr($keyword, 0,3) eq "seq" ) { goto SEQ }
    if ( $keyword eq 'r' || substr($keyword, 0,5) eq "resol" ) { goto RESOL }
    if ( $keyword eq 's' || substr($keyword, 0,4) eq "symm" ) { goto SYMM }
    if ( $keyword eq 'y' || substr($keyword, 0,7) eq "my_topo" ) { goto MY_TOPO }
    if ( $keyword eq 't' || substr($keyword, 0,4) eq "topo" ) { goto TOPO }

    if ( substr($keyword, 0,4) eq "doit" ) { $doit = "TRUE" ; next ; }
    print "unknown option >$keyword<\n" ; $PROC_ERROR = "TRUE" ;

#  -c|--ctab)       file with molecular connectivity table [@{$my_main{"FILE_CTAB"}}]
  HELP:
    my @hkls = () ; my $ii ;
    for ( $ii = 0; $ii <= $#{$my_main{"DFR_LIMIT_H"}}; $ii++ )
    {
	push(@hkls, $my_main{"DFR_LIMIT_H"}[$ii] ) ;
	push(@hkls, ',') ;
	push(@hkls, $my_main{"DFR_LIMIT_K"}[$ii] ) ;
	push(@hkls, ',') ;
	push(@hkls, $my_main{"DFR_LIMIT_L"}[$ii] ) ;
	push(@hkls, '-') ;
    }

#    print " limits:", @{$my_main{"DFR_LIMIT_H"}}, @{$my_main{"DFR_LIMIT_K"}}, @{$my_main{"DFR_LIMIT_L"}}, " hkls:", @hkls, " \n" ;

    pop ( @hkls ) ;
    my $my_hkls= join (" ", @hkls ) ;


    my @rls = () ; 
    for ( $ii = 0; $ii <= $#{$my_main{"DFR_RES_MIN"}}; $ii++ )
    {
	push(@rls, $my_main{"DFR_RES_MIN"}[$ii] ) ;
	push(@rls, ',') ;
	push(@rls, $my_main{"DFR_RES_MAX"}[$ii] ) ;
	push(@rls, '-') ;
    }
    pop ( @rls ) ;
    my $my_resols = join (" ", @rls ) ;

    print " my:::hkls>  $my_hkls < resols > $my_resols <\n" ;

    print << "END_OF_TEXT" ;
  -h|-help|--help) prints this message with available options and current status 
  -a|--atom) file with molecular model [@{$my_main{"FILE_MODEL"}}]
  -b|--back)       file of background molecules [@{$my_main{"FILE_MODEL_BACK"}}]
  -g|--target)     file of target molecules [@{$my_main{"FILE_MODEL_TARGET"}}]
  -c|--cell)       file with unit cell constants [@{$my_main{"FILE_CELL"}}]
  -d|--diffr )     file with diffraction data [@{$my_main{"FILE_REFL"}}] 
  -r|--resol)      resolution limits for diffraction data [$my_resols]
  -f|--format_dfr) diffraction data format [MAIN/SCALEPACK/SHELX/MAP] [@{$my_main{"DFR_FORMAT"}}]
  -l|--limit|--hkl)  set HKL limits for diffraction data [$my_hkls]
  -i|--init )      initial maps to be calculated [NONE/MODEL/FOBS/COMB] [@{$my_main{"INIT_MAP"}}]
  -m|--map)        file names of additional maps to be read [@{$my_main{"FILE_MAPS"}}]
  -o|--output)     file name of the created macro [$MACRO_FILE]
  -q|--seq)        file name with sequence information [@{$my_main{"FILE_SEQUENCE"}}]
  -s|--symm)       space group symmetry [@{$my_main{"FILE_SYMM"}}]
  -t|--topo)       basic topology libraries more than one can be specified
                   by [POLAR_H/RCSB_NUC/ALL_H/SUGAR] current [@{$my_main{"FILE_TOPO"}}] 
                   POLAR_H: amino acid parameters
                   RCSB_NUC: nucleic acids
                   ALL_H: amino acid parameters with all hydrogen atoms included
                   SUGAR: a few carbohydrate rings
  -y|--my_topo)    additional topology libraries [@{$my_main{"FILE_MY_TOPO"}}]
     --doit)     create the macro $MACRO_FILE
END_OF_TEXT

    exit ;


 OUTPUT: $MACRO_FILE = shift ( @{$commands{$keyword}} ) ; next ;

 ATOM: @{$my_main{"FILE_MODEL"}} = shift ( @{$commands{$keyword}} ) ; next ;
# CTAB: @{$my_main{"FILE_CTAB"}} = shift ( @{$commands{$keyword}} ) ; next ;
# CELL: @{$my_main{"FILE_CELL"}} = shift ( @{$commands{$keyword}} ) ; next ;
 CELL: @{$my_main{"FILE_CELL"}} = @{$commands{$keyword}} ; next ;
 SYMM: @{$my_main{"FILE_SYMM"}} = () ;
       foreach $SEGM ( @{$commands{$keyword}}) 
       { push ( @{$my_main{"FILE_SYMM"}}, lc($SEGM) ); }
       next ;
 SEQ: @{$my_main{"FILE_SEQUENCE"}} = shift ( @{$commands{$keyword}} ) ; next ;
 DIFFR: 
    @{$my_main{"FILE_REFL"}} = @{$commands{$keyword}} ; 
#    print "FILE REFL data ", @{$my_main{"FILE_REFL"}}, "\n" ; 
    next ;
 DFR_FORM:
#    print "FILE REFL FORM 0", @{$my_main{"FILE_REFL"}}, "\n" ; 
    @{$my_main{"DFR_FORMAT"}} = @{$commands{$keyword}} ;  
#    my @SEGM = @{$commands{$keyword}} ; # $SEGM = uc($SEGM) ;
#    print "FILE REFL FORM 0", @{$my_main{"FILE_REFL"}},  $SEGM, "\n" ; 
#if ( $SEGM eq "MAIN" || $SEGM eq "SCALEPACK" || $SEGM eq "SHELX" ) 
#{  @{$my_main{"DFR_FORMAT"}} = $SEGM;  }
#else { @{$my_main{"DFR_FORMAT"}} = ( "MAIN" ) ;  } 
##    print "FILE REFL FORM 2", @{$my_main{"FILE_REFL"}}, "\n" ; 
next ;

 INIT_MAP: @{$my_main{"INIT_MAP"}} = shift ( @{$commands{$keyword}} ) ; next ;
 MY_TOPO: @{$my_main{"FILE_MY_TOPO"}} = @{$commands{$keyword}} ; next ;
 TOPO: @{$my_main{"FILE_TOPO"}} = () ;
       foreach $SEGM ( @{$commands{$keyword}}) 
       { push ( @{$my_main{"FILE_TOPO"}}, uc($SEGM) ); }
       next ;

 RESOL: 
{
    my $last = "MAX" ; 
    my $word ;
    @{$my_main{"DFR_RES_MIN"}} = () ;
    @{$my_main{"DFR_RES_MAX"}} = () ;
    
    foreach $word ( @{$commands{$keyword}} )
    {
	print "resol> ", $last, $word, "\n" ;
	if ( $last eq "MAX" )
	{ 
	    push (@{$my_main{"DFR_RES_MIN"}}, $word ) ; 
	    $last = "MIN" ; 
	    print "resol min> ", $last, $word, "\n" ;
	} 
	else
	{ 
	    push ( @{$my_main{"DFR_RES_MAX"}}, $word ) ;  
	    $last = "MAX" ; 
	    print "resol max> ", $last, $word, "\n" ;
	} 
    }
}
    next ;

 HKL: 
#    print "HKL ", join (" ", @{$commands{$keyword}}), "\n" ;
{
    @{$my_main{"DFR_LIMIT_H"}} = () ; 
    @{$my_main{"DFR_LIMIT_K"}} = () ; 
    @{$my_main{"DFR_LIMIT_L"}} = () ; 

    while ( $#{$commands{$keyword}} > 0 )
    {
	print " hkl commands:", $#{$commands{$keyword}}, "\n" ;
	push ( @{$my_main{"DFR_LIMIT_H"}}, shift (@{$commands{$keyword}} ) ) ; 
	push ( @{$my_main{"DFR_LIMIT_K"}}, shift (@{$commands{$keyword}} ) ) ; 
	push ( @{$my_main{"DFR_LIMIT_L"}}, shift (@{$commands{$keyword}} ) ) ; 
    }
#print "L:",  @{$my_main{"DFR_LIMIT_H"}}, "\n" ;
}
    next ;

 MAP: @{$my_main{"FILE_MAPS"}} =  @{$commands{$keyword}} ; next ;
 BACK: @{$my_main{"FILE_MODEL_BACK"}} = shift ( @{$commands{$keyword}} ) ; next ;
 TARGET: @{$my_main{"FILE_MODEL_TARGET"}} = shift ( @{$commands{$keyword}} ) ; next ;

}

if ( $PROC_ERROR eq "TRUE" ) { exit ; }

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

$conf_file = "main_config.data" ; 
main_config::write_main_config_file ( $conf_file, %my_main ) ; 

if ( $doit eq "FALSE" )  { exit ; }

######################################
my $FILE ;
my $WORK_SEGM = join (" ", @{$my_main{"SG_LIST"}} ) ;
print "creating \"$MACRO_FILE\" \n" ;
if ( -f $MACRO_FILE ) 
{ 
    my $back = join ('', $MACRO_FILE, ".old" ) ; 
    system ( "mv  $MACRO_FILE $back" ) ; 
}
open ( MACRO,  "> $MACRO_FILE" ) || die "FILE OPEN ERROR: >$MACRO_FILE< \n" ;
my $FH = *MACRO ;

my $FILE_SEQ = "" ;

if ( length ( ${$my_main{"FILE_SEQUENCE"}}[0]) > 0 )
{
    $FILE_SEQ = ${my_main{"FILE_SEQUENCE"}}[0] ; 
}

# my $FILE_SYMM = join( '', '"?MAIN_SYMM:', ${$my_main{"FILE_SYMM"}}[0], '.symm"' ) ;
# my $FILE_FOBS = ${$my_main{"FILE_REFL"}}[0] ;
# my $FILE_CELL = ${$my_main{"FILE_CELL"}}[0] ;
# my $RESOL_MIN = ${$my_main{"DFR_RES_MIN"}}[0] ;
# my $RESOL_MAX = ${$my_main{"DFR_RES_MAX"}}[0] ;

if ( length ($FILE_SEQ) > 0 ) 
{ print MACRO "set vari FILE_SEQ = $FILE_SEQ \n" ; }

# set vari FILE_SYMM = $FILE_SYMM 
# set vari FILE_FOBS = $FILE_FOBS
# set vari FILE_CELL = $FILE_CELL 
# 
# set vari RESOL_MIN global real = $RESOL_MIN 
# set vari RESOL_MAX global real = $RESOL_MAX 

if ( length ($my_main{"FILE_TOPO"}[0] ) <= 0  ) 
{
print MACRO << "END_OF_DATA" ;
! TOPOLOGY AND PARAMETERS SECTION 
topo init
read param init 
end_of_file

read file >top/top_99_csd.main top main
read file >top/par_99_csd.main par 
read file >top/top_prot_adds.main top main 
read file >top/par_prot_adds.main par main 
read file >top/top_sme.main top main 
read file >top/par_sme.main par main 
read file >top/top_dna_rna.main top main
read file >top/par_dna_rna.main par
read file >top/top_ion.main top main
read file >top/par_ion.main par main 

set vari DEF_ALL char global = "?MAIN_UTILS:def_top_par_prot_nuc.com"
set vari FORCE_HBON real global = 30. 
set vari DIST_HBON real global = 1.95

END_OF_DATA

} 
else
{
    print MACRO "! TOPOLOGY AND PARAMETERS SECTION \n"  ; 
    print MACRO "topo init \n"  ; 
    print MACRO "read param init \n"  ; 
    print MACRO "end_of_file\n\n"  ; 
    foreach $FILE ( @{$my_main{"FILE_TOPO"}} )
    {
	print "topo loop: $FILE \n";
	if ( uc($FILE) eq "POLAR_H" )
	{ 
	    print MACRO"read file >top/top_99_csd.main top main \n" ;
	    print MACRO"read file >top/par_99_csd.main par \n" ;
	    print MACRO"read file >top/top_prot_adds.main top main  \n" ;
	    print MACRO"read file >top/par_prot_adds.main par main  \n" ;
	    print MACRO"read file >top/top_ion.main top main \n" ;
	    print MACRO"read file >top/par_ion.main par main \n" ;
	    print MACRO"read file >top/top_sme.main top main \n" ;
	    print MACRO"read file >top/par_sme.main par main \n" ;
	    print MACRO"read file >top/top_dna_rna.main top main \n" ;
	    print MACRO"read file >top/par_dna_rna.main par \n" ;
	}
	if ( uc($FILE) eq "ALL_H" )
	{ 
	    print MACRO "read file >top/top_allh_prot_99_csd.main top main \n" ;
  	    print MACRO "read file >top/top_prot_adds.main top main \n" ;
	    print MACRO "read file >top/top_ion.main top main \n"  ; 
	    print MACRO "read file >top/par_allh_prot_99_csd.main par main \n" ;
  	    print MACRO "read file >top/par_prot_adds.main par main  \n" ;
	    print MACRO "read file >top/par_ion.main par main \n"  ; 
	    print MACRO "read file >top/par_allh_mse.main par main \n"  ; 
	    print MACRO"read file >top/top_dna_rna.main top main \n" ;
	    print MACRO"read file >top/par_dna_rna.main par \n" ;
#	    print MACRO "< ?MAIN_UTILS:get_top_par_PURY_ALLH\n"  ; 
	}
	if ( uc($FILE) eq "SUGAR" )
	{
	    print MACRO "read file >top/top_sugar.main top main \n"  ; 
	    print MACRO "read file >top/par_sugar.main par \n"  ; 
	}
#	if ( uc($FILE) eq "RCSB_NUC" && uc($FILE) ne "ALL_H"   && uc($FILE) ne "POLAR_H"  )
#	{ 
#	    print MACRO"read file >top/top_dna_rna.main top main \n" ;
#	    print MACRO"read file >top/par_dna_rna.main par \n" ;
#	}
    }
    print MACRO "set vari DEF_ALL char global = \"?MAIN_UTILS:def_top_par_prot_nuc.com\" \n" ;
    print MACRO "set vari FORCE_HBON real global = 30. \n" ;
    print MACRO "set vari DIST_HBON real global = 1.6 \n" ;
    print MACRO "\n" ;
}

 print MACRO "key background sele .n all end\n" ;


my %file_top_hash ;
my %file_par_hash ;
my %file_cif_hash ;
my @list_files = () ;
my @list_cif_files = () ;
print " my topologies ", join(" ", @{$my_main{"FILE_MY_TOPO"}} ) , "\n" ;

if ( length ($my_main{"FILE_MY_TOPO"}[0] ) > 0  )
{
    foreach $FILE ( @{$my_main{"FILE_MY_TOPO"}} )
    {
#	print " each file: $FILE \n" ;
	if ( lc($FILE) =~ "top" ) 
	{
	    if ( not lc($FILE) =~ "par" ) 
	    {
		if ( lc($FILE) =~ "main") 
		{
		    print MACRO "read file ", $FILE, " topo main\n";
		}
		else 
		{
		    print MACRO "read file ", $FILE, " topo xpl\n";
		}
		$FILE =~ s/top// ;
		$FILE =~ s/~// ;
		$FILE =~ s/main// ;
		$FILE =~ s/cns// ;
		$FILE =~ s/xpl// ;
		$FILE =~ s/_// ;
		$FILE =~ s/\.// ;
		$file_top_hash{$FILE} = "DONE" ;
#	    print "file after s-top $FILE \n" ;
	    }
	}
    }
    foreach $FILE ( @{$my_main{"FILE_MY_TOPO"}} )
    {
	if ( lc($FILE) =~ "par" ) 
	{
	    print MACRO "read file ", $FILE, " par main\n";
	    $FILE =~ s/par// ;
	    $FILE =~ s/~// ;
	    $FILE =~ s/main// ;
	    $FILE =~ s/cns// ;
	    $FILE =~ s/xpl// ;
	    $FILE =~ s/_// ;
	    $FILE =~ s/\.// ;
#	    print "file after s-par $FILE \n" ;
	    $file_par_hash{$FILE} = "DONE" ;
	}
    }

    foreach $FILE ( @{$my_main{"FILE_MY_TOPO"}} )
    {
	if ( lc($FILE) =~ "cif" ) 
	{
	    print MACRO "read file ", $FILE, " topo cif\n";
	    $FILE =~ s/cif// ;
	    $FILE =~ s/\.// ;
#	    print "file after s-cif par $FILE \n" ;
	    $file_par_hash{$FILE} = "DONE" ;
	}
    }
    print MACRO "read file MAIN_UTILS:dummy.dat topo main \n" ;
    print MACRO " \n" ;
}

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

my $key ; my $found ;
foreach $FILE ( sort( @all_files ) )
{
    if ( lc($FILE) !~ "com" ) 
    {
	if ( lc($FILE) =~ "top" ) 
	{ 
	    $found = "NO" ; 
	    foreach $key ( %file_top_hash )
	    {
		if ( $FILE =~ $key ) 
		{ 
#		    print " {$FILE}: top key next: $key \n" ; 
		    $found = "YES" ; 
		}
	    }
	    if ( $found eq "NO" ) { 
		push( @list_files, $FILE ) ; 
#		print " top key last: $key \n" ; 
	    }
	}
	if ( lc($FILE) =~ "par" ) 
	{ 
	    $found = "NO" ; 
	    foreach $key ( %file_par_hash )
	    {
		if ( $FILE =~ $key ) 
		{ 
#		    print " {$FILE}: par key next: $key \n" ; 
		    $found = "YES" ; 
		}
	    }
	    if ( $found eq "NO" ) 
	    { 
		push( @list_files, $FILE ) ; 
#		print " par key last: $key \n" ; 
	    }
	}
 	if ( lc($FILE) =~ "cif" ) 
 	{ 
 	    $found = "NO" ; 
 	    foreach $key ( %file_cif_hash )
 	    {
 		if ( $FILE =~ $key ) 
 		{ 
 #		    print " {$FILE}: par key next: $key \n" ; 
 		    $found = "YES" ; 
 		}
 	    }
 	    if ( $found eq "NO" ) 
 	    { 
 		push( @list_files, $FILE ) ; 
#		print " cif key last: $FILE \n" ; 
 	    }
 	}
    }
}

my %list_of_tp; 

foreach $FILE ( @list_files )
{
    my @words = split ( '\.', $FILE ) ;
#    print $FILE, ":: <", $words[0], '>--<', $words[1], ">\n" ;
    if ( $#words > 0 )
    {
	if ( lc($words[1]) eq "main" ) { push( @{$list_of_tp{$words[0]}}, "main" ) ; } ;
	if ( lc($words[1]) eq "cns" ) { push( @{$list_of_tp{$words[0]}}, "cns" ) ; } ;
	if ( lc($words[1]) eq "cif" ) 
	{ 
	    if ( length $words[0] <= 3  )
	    { push( @{$list_of_tp{$words[0]}}, "cif" ) ; }
	} 
    }
}


foreach $FILE ( sort (keys %list_of_tp) )
{
    my $nn_main = 0 ;
    my $nn_cns = 0 ;
    my $nn_cif = 0 ;
    my $FORM ;
    foreach $FORM ( @{$list_of_tp{$FILE}} )
    {
	if ( $FORM eq "main" ) { $nn_main++ ; }
	if ( $FORM eq "cns" ) { $nn_cns++ ; }
	if ( $FORM eq "cif" ) { $nn_cif++ ; }
    }

    if ( lc($FILE) =~ "top" )
    {
	print " found top file: $FILE \n" ;
	if ( $nn_main > 0) 
	{
	    print MACRO "read file ", $FILE.".main", " topo main\n";
	}
	elsif ( $nn_cns > 0 ) 
	{
	    print MACRO "read file ", $FILE.".cns", " topo xpl\n";
	}
    }
    
    if ( $nn_cif > 0 ) 
    {
	print "read file ", $FILE.".cif", " topo cif\n";
	print MACRO "read file ", $FILE.".cif", " topo cif\n";
    }
    
}


foreach $FILE ( sort (keys %list_of_tp) )
{
    my $nn_main=0 ;
    my $nn_cns=0 ;
    my $FORM ;
    foreach $FORM ( @{$list_of_tp{$FILE}} )
    {
	if ( $FORM eq "main" ) { $nn_main++ ; }
	if ( $FORM eq "cns" ) { $nn_cns++ ; }
    }

    if ( lc($FILE) =~ "par" ) 
    {
    print " found par file: $FILE \n" ;
	if ( $nn_main > 0) 
	{
	    print MACRO "read file ", $FILE.".main", " par main\n";
	}
	elsif ( $nn_cns > 0 ) 
	{
	    print MACRO "read file ", $FILE.".cns", " par main\n";
	}
    }
    
}


#echo "-- 1 --"

if ( $my_main{"SG_NMOL"}[0] > $my_main{"SG_NGROUP"}[0] ) 
{	    
print MACRO  "set vari MAT_ROT global int = 3 \n" ; 
my $line = join( '', "load_", ${$my_main{"SG_NMOL"}}[0], "mol.com" ) ;
print MACRO  "< $line \n" ; 
}

if ( length (${$my_main{"FILE_SEQUENCE"}}[0]) > 0 )
{
    print MACRO "read file MAIN_UTILS:seq_sim_penalty.table sequence table \n" ;
    print MACRO "read file FILE_SEQ sequence protein \n" ;
}

my $FILE_ATOM = ${$my_main{"FILE_MODEL"}}[0] ;

my $MY_FORM ;
if ( lc($FILE_ATOM) =~ "cif" )
{ $MY_FORM = 'mmcif' ; }
else
{ $MY_FORM = 'pdb' ; }

my @xx = split ('\.', $FILE_ATOM) ; pop (@xx) ;
my $FILE_CTAB = join("", @xx, ".CTAB" ) ;
my $FILE_HBOND = join("", @xx, ".HBOND" ) ;
print MACRO << "END_OF_DATA" ;
! ATOMS SECTION

set vari FILE_ATOM = $FILE_ATOM 
set vari FILE_CTAB = $FILE_CTAB
set vari FILE_HBOND = $FILE_HBOND

read file FILE_ATOM atom $MY_FORM
set vari WORK_SEGM char global segm sele .n segm name SKEL end 
set vari II int atom sele segm name WORK_SEGM end
show vari II
if ( II .le. 0 ) then

    set vari WORK_SEGM char global = $WORK_SEGM 
end_if

 set rad sele segm name WORK_SEGM end vdw

read file FILE_CTAB ctable
show bonds
if ( IRESULT_0 .le. natom / 2 ) then
 echo " --------------==================== in bonds =================------------"
key active sele segm name WORK_SEGM end
show key active
 < ?MAIN_UTILS:make_bonds_from_topo.com WORK_SEGM
 key xx sele .n by bond all end
 show key xx
 calculate bond sele by resi xx end neigh

end_if

read file FILE_HBOND hbond
END_OF_DATA


# multi crystals
my ( $IGR, $NCRYST, $CRYST, $GROUP );

$NCRYST = $my_main{"SG_NCRYST"}[0] ;

if ( $NCRYST > 1 )
{
    main_config::create_constrain_cryst_inter ( $FH, %my_main ) ;
}

if (  $my_main{"PREF_NCS_CRYST"}[0] ne "ON" ) { $NCRYST = 1 ; } 

# composit groups - multiple confomrations ...

# 


my $CMP = "NO" ;
my $STRATEGY;
for ( $IGR = 1; $IGR <= @{$my_main{"SG_NGROUP"}}[0] ; $IGR++ )
{
    $GROUP= join ( '', "SG_GROUP" , $IGR ) ;
    $STRATEGY = join ( '', "SG_GROUP" , $IGR, "_STRATEGY" ) ;
#    print " my group strategy: >",  $my_main{$STRATEGY}[0], "<\n" ;
    if ( $my_main{$STRATEGY}[0] eq "COMPOSIT" ) { $CMP = "YES" ; }
}

if ( $CMP eq "YES" ) 
{
    main_config::create_constrain_composit_inter ( $FH, %my_main ) ;
}

# # my $CMP = "NO" ;
# # if ( @{$my_main{"SG_NMOL"}}[0] > @{$my_main{"SG_NGROUP"}}[0] )
# # {
# #     my ( $IGR, $GROUP, $STRATEGY );
# #     for ( $IGR = 1; $IGR <= @{$my_main{"SG_NGROUP"}}[0] ; $IGR++ )
# #     {
# # 	$GROUP= join ( '', "SG_GROUP" , $IGR ) ;
# # 	$STRATEGY = join ( '', "SG_GROUP" , $IGR, "_STRATEGY" ) ;
# # 	if ( $my_main{$STRATEGY}[0] eq "COMPOSIT" ) { $CMP = "YES" ; }
# #     }
# # }
# # 
# # if ( $CMP eq "YES" ) 
# # {
# #     print MACRO "define init constr inter \n" ;
# # 
# #     my $MEMBER ; my $NN_GROUP=0 ;
# #     if ( @{$my_main{"SG_NMOL"}}[0] > @{$my_main{"SG_NGROUP"}}[0] )
# #     {
# # 	my ( $IGR, $GROUP, $STRATEGY );
# # 	for ( $IGR = 1; $IGR <= @{$my_main{"SG_NGROUP"}}[0] ; $IGR++ )
# # 	{
# # 	    $GROUP= join ( '', "SG_GROUP" , $IGR ) ;
# # 	    $STRATEGY = join ( '', "SG_GROUP" , $IGR, "_STRATEGY" ) ;
# # 	    if ( $my_main{$STRATEGY}[0] eq "COMPOSIT" ) 
# # 	    { 
# # #	print " COMPOSIT groups: $IGR, <$GROUP> \n" ;
# # 		
# # 		my $LINE = join (" ", @{$my_main{$GROUP}} ) ;
# # 		print MACRO " key outgr  sele .n segm name $LINE end\n" ;
# # 		foreach $MEMBER ( @{$my_main{$GROUP}} )
# # 		{
# # #	print " groups: $IGR, <$GROUP> $MEMBER\n" ;
# # 		    print MACRO 
# # 			" define constr inter \\\n",
# # 			"sele segm name $MEMBER end sele segm name $MEMBER .o outgr end \n" ;
# # 		}
# # 	    }
# # 	    else
# # 	    { 
# # 		my $LINE = join (" ", @{$my_main{$GROUP}} ) ;
# # 		print MACRO 
# # 		    " define constr inter \\\n",
# # 		    "sele segm name $LINE end \\\n",
# #                     "sele segm name WORK_SEGM end \n" ;
# # 	    }
# # 	}
# #     }
# #     print MACRO " key outgr drop\n" ;
# # 
# # }


print MACRO << "END_OF_DATA" ;

<DEF_ALL WORK_SEGM
define init group 
! set charge sele .not atom name C CA N H O .a \\ 
!    resi name ASP GLU LYS ARG end = 0.0
key active sele segm name WORK_SEGM end
key passive sele segm name WORK_SEGM end

END_OF_DATA
    if ( $my_main{"SG_NCRYST"}[0] > 1 ) 
{
    my  $GROUP = join ( '', "SG_CRYST" , $my_main{"SG_NCRYST"}[0] ) ;
    $SEGM = join(" ", @{$my_main{$GROUP}} ) ;
    print MACRO "set vari WORK_SEGM char global = \"$SEGM\" \n" ;
}
# DIFRRACTION DATA
#    print " cryst data number >", $my_main{"SG_NCRYST"}[0], "<\n" ;

for ($CRYST=0; $CRYST < $my_main{"SG_NCRYST"}[0]; $CRYST++ )
{
    print " cryst data >", $CRYST, "<\n" ;
main_config::write_get_diffr_data (*MACRO, \%my_main, $CRYST ) ; 
my $MAP = join ( '', "MAP_CRYS_" , $CRYST+1 ) ;

print MACRO << "END_DATA" ;
! map section

make map from 0 empty init auto_grid cell real
set vari $MAP = nmaps
make map from nmaps empty init 

set vari MAP_2FOFC global inte = $MAP 
set vari MAP_FO global inte = $MAP 
set vari MAP_FOFC global inte = $MAP + 1 
set vari MAP_WORK global inte = $MAP + 1 

END_DATA
}


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

if ( length ($my_main{"FILE_MAPS"}[0]) > 0 && $my_main{"FILE_MAPS"}[0] ne " " )
{
    foreach $FILE ( @{$my_main{"FILE_MAPS"}} )
    {
	my @xx = split ('\.', $FILE) ; 
	my $file_ext = pop (@xx) ;
	if ( lc($file_ext) eq "mrc" ) 
	{	    
	    print MACRO "open unit 10 file $FILE unform rec 1024\n" ;
	    print MACRO "read unit 10 map mrc init\n" ;
	    print MACRO "clo uni 10\n" ;
	    print MACRO "show vari MAP_LAST\n" ;
	    print MACRO "make map MAP_LAST rescale\n" ;
	}
	else
	{
	    print MACRO "read file $FILE map xplor \n"  ;
	}
    }
}

#echo "-- 3 --"

print MACRO << "END_OF_DATA" ;
ener chem ( all on ) dens ( on map MAP_2FOFC scal 25. )

< SAVE_FILE.MAP
END_OF_DATA

# if ( $my_main{"INIT_MAP"}[0] eq "MODEL" )
# {
# print MACRO << "END_OF_DATA" ;
# 
# ! map calculation from model
# < ?MAIN_CMDS:re_phase.cmds WORK_SEGM MAP_WORK
# < ?MAIN_CMDS:calc_fofc_diff_map.cmds MAP_2FOFC 2. 1. 
# < ?MAIN_CMDS:calc_fofc_diff_map.cmds MAP_FOFC 1. 1.
# 
# copy map 2 3
# 
# END_OF_DATA
# }

if ( $my_main{"INIT_MAP"}[0] eq "FOBS" )
{
print MACRO << "END_OF_DATA" ;

! map calculation
<?MAIN_CMDS:calc_fo_map.cmds MAP_FO

END_OF_DATA
}

if ( $my_main{"INIT_MAP"}[0] eq "COMB" )
{
print MACRO << "END_OF_DATA" ;

! map calculation
<?MAIN_CMDS:phase_comb.cmds MAP_FO

END_OF_DATA
}

print MACRO << "END_OF_DATA" ;

!      final part: opening display, unit cell, chain trace ...

ima cent sele segm numb 1 end
image group on
<SAVE_FILE.VIEW
<MAIN_UTILS:show.cell

END_OF_DATA

my $COLOR = 90 ;
foreach $FILE ( @{$my_main{"FILE_MODEL_BACK"}} )
{
    $FILE =~ s/ // ;
    if ( length($FILE) > 0 ) 
    {	
	print MACRO "<?MAIN_UTILS:background_file_image \\ \n" ; 
	print MACRO "   $FILE $COLOR \"delete\" \n" ; 
    }
    $COLOR = $COLOR + 10 ;
}

foreach $FILE ( @{$my_main{"FILE_MODEL_TARGET"}} )
{
    $FILE =~ s/ // ;
    if ( length($FILE) > 0 ) 
    {	
	print MACRO "<?MAIN_UTILS:background_file_image \\ \n" ; 
	print MACRO "   $FILE $COLOR \"keep\" \n" ; 
    }
    $COLOR = $COLOR + 10 ;
}

print MACRO << "END_OF_DATA" ;

image group name CHAIN_TRACE
image sele atom name CA C N .a segm name WORK_SEGM end col 1 bond
ima from erase
END_OF_DATA

    my ( $MAP_FROM, $MAP_TO ) ;

$NCRYST = $my_main{"SG_NCRYST"}[0] ;

for ( $CRYST = 0; $CRYST < $NCRYST ; $CRYST++ )
{
$MAP_FROM = $CRYST * 2 + 1 ;	     
$MAP_TO = $MAP_FROM + 1 ;	     
print MACRO << "END_OF_DATA" ;
 ima col 245 map $MAP_FROM dens 0.8 26 26 26
 ima col  90 map $MAP_TO dens 2.5 26 26 26 
END_OF_DATA
}
##echo "-- 5 --"

my $I = 2 ;
foreach $FILE ( @{$my_main{"FILE_MAPS"}} )
{
    $FILE =~ s/ // ;
    $I++ ; if ( length($FILE) > 0 ) 
{ print MACRO "image map $I dens 1.0 26 26 26  \n" ; }
}

my $NCS_START = "FALSE" ;
for ( $IGR = 1; $IGR <= @{$my_main{"SG_NGROUP"}}[0] ; $IGR++ )
{
    $GROUP= join ( '', "SG_GROUP" , $IGR ) ;
    $STRATEGY = join ( '', "SG_GROUP" , $IGR, "_STRATEGY" ) ;
#	print " groups: $IGR, <$GROUP> \n" ;
    if ( $my_main{$STRATEGY}[0] eq "BACKGROUND" ) 
    {
	my $NN_GROUP= @{$my_main{$GROUP}} ;
	my $MEMBER =  ${$my_main{$GROUP}}[$NN_GROUP-1] ;
	print MACRO "key background sele background .o segm name $MEMBER end \n" ;
    }
}
print MACRO " ener ncs @{$my_main{\"PREF_NCS_FLAG\"}}[0] \n" ;

$NCS_START = "FALSE" ;
for ( $IGR = 1; $IGR <= @{$my_main{"SG_NGROUP"}}[0] ; $IGR++ )
{
    $GROUP= join ( '', "SG_GROUP" , $IGR ) ;
    $STRATEGY = join ( '', "SG_GROUP" , $IGR, "_STRATEGY" ) ;
#	print " groups: $IGR, <$GROUP> \n" ;
    if ( $my_main{$STRATEGY}[0] eq "BACKGROUND" ) 
    {
	my $NN_GROUP= @{$my_main{$GROUP}} ;
	my $MEMBER =  ${$my_main{$GROUP}}[$NN_GROUP-1] ;
	print MACRO "key background sele background .o segm name $MEMBER end \n" ;
    }
}

print MACRO << "END_OF_DATA" ;

<?MAIN_CMDS:re_image.cmds WORK_SEGM

return
END_OF_DATA

close (MACRO) ;
