#!/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{"BULK_SOLV_METHOD"} ) ) { push ( @{$my_main{"BULK_SOLV_METHOD"}}, "NONE" ) } ; 
if ( !exists( $my_main{"DFR_RFREE"} ) ) { push ( @{$my_main{"DFR_RFREE"}}, "OFF" ) } ; 
if ( !exists( $my_main{"PREF_ADJUST_STEP"} ) ) { push ( @{$my_main{"PREF_ADJUST_STEP"}}, -1 ) } ; 
if ( !exists( $my_main{"PREF_PRECISION"} ) ) { push ( @{$my_main{"PREF_PRECISION"}}, 3 ) } ; 
if ( !exists( $my_main{"PREF_MAP_GRID"} ) ) { push ( @{$my_main{"PREF_MAP_GRID"}}, 4 ) } ; 
if ( !exists( $my_main{"BREF_FORCE_BOND"}  ) )  { push ( @{$my_main{"BREF_FORCE_BOND"}}, 1.4 ) ; }
if ( !exists( $my_main{"BREF_FORCE_ANGLE"}  ) )  { @{$my_main{"BREF_FORCE_ANGLE"}} =( $my_main{"BREF_FORCE_BOND"} / 2.0 ) ; }
if ( !exists( $my_main{"BREF_FORCE_GROUP"}  ) )  { push ( @{$my_main{"BREF_FORCE_GROUP"}}, -1.0 ) ; }
if ( !exists( $my_main{"BREF_GROUP"}  ) )  { push ( @{$my_main{"BREF_GROUP"}}, "SINGLE" ) ; }
if ( !exists( $my_main{"BREF_IND_STEP"}  ) )  { push ( @{$my_main{"BREF_IND_STEP"}}, 20 ) ; }
if ( !exists( $my_main{"BREF_KICK_B0"}  ) )  { push ( @{$my_main{"BREF_KICK_B0"}}, "0" ) ; }
if ( !exists( $my_main{"BREF_KICK_B1"}  ) )  { push ( @{$my_main{"BREF_KICK_B1"}}, "0" ) ; }
if ( !exists( $my_main{"BREF_NCS_FLAG"}  ) )  { push ( @{$my_main{"BREF_NCS_FLAG"}}, "OFF" ) ; }
if ( !exists( $my_main{"BREF_NCS_FORCE"} ) )  { push ( @{$my_main{"BREF_NCS_FORCE"}} , 0.004 ) ; }
if ( !exists( $my_main{"BREF_OVER_STEP"}  ) )  { push ( @{$my_main{"BREF_OVER_STEP"}}, -1 ) ; }
if ( !exists( $my_main{"BREF_SCAL_XTARG"} ) )  { push ( @{$my_main{"BREF_SCAL_XTARG"}}, 2.0 ) ; }
if ( !exists( $my_main{"MAP_ZONES"}  ) )  { push ( @{$my_main{"MAP_ZONES"}}  , 0 ) ; }
if ( !exists( $my_main{"OREF_IND_STEP"}  ) )  { push ( @{$my_main{"OREF_IND_STEP"}}, 20 ) ; }
if ( !exists( $my_main{"PREF_BACKUP"}  ) )  { push ( @{$my_main{"PREF_BACKUP"}} , "OFF" ) ; }
if ( !exists( $my_main{"PREF_BVAL_MAX"}  ) )  { push ( @{$my_main{"PREF_BVAL_MAX"}}, 300 ) ; }
if ( !exists( $my_main{"PREF_BVAL_MIN"}  ) )  { push ( @{$my_main{"PREF_BVAL_MIN"}}, 1 ) ; }
if ( !exists( $my_main{"PREF_BVAL_ADD"}  ) )  { push ( @{$my_main{"PREF_BVAL_ADD"}}, -9999 ) ; }
if ( !exists( $my_main{"PREF_DIST_CUTOFF"}  ) )  { push ( @{$my_main{"PREF_DIST_CUTOFF"}} , 4.5 ) ; }
if ( !exists( $my_main{"PREF_TICKLE"}  ) )  { push ( @{$my_main{"PREF_TICKLE"}} , -1.0 ) ; }
if ( !exists( $my_main{"PREF_KICK_CR0"}  ) )  { push ( @{$my_main{"PREF_KICK_CR0"}} , 0 ) ; }
if ( !exists( $my_main{"PREF_KICK_CR1"}  ) )  { push ( @{$my_main{"PREF_KICK_CR1"}} , 0 ) ; }
if ( !exists( $my_main{"PREF_MAP_DENS"}  ) )  { push ( @{$my_main{"PREF_MAP_DENS"}} , 1 ) ; }
if ( !exists( $my_main{"PREF_MAP_XDIFF"} ) )  { push ( @{$my_main{"PREF_MAP_XDIFF"}} , 3 ) ; }
if ( !exists( $my_main{"PREF_MAP_XTARG"}  ) )  { push ( @{$my_main{"PREF_MAP_XTARG"}}  , 3 ) ; }
if ( !exists( $my_main{"PREF_ML_AVER"}  ) )  { push ( @{$my_main{"PREF_ML_AVER"}} , 1 ) ; }
if ( !exists( $my_main{"PREF_ML_KICK"}  ) )  { push ( @{$my_main{"PREF_ML_KICK"}} , 1.0 ) ; }
if ( !exists( $my_main{"PREF_ML_MISSIN"}  ) )  { push ( @{$my_main{"PREF_ML_MISSIN"}} , "100" ) ; }
if ( !exists( $my_main{"PREF_NCS_CRYST"}  ) )  { push ( @{$my_main{"PREF_NCS_CRYST"}} , "OFF" ) ; }
if ( !exists( $my_main{"PREF_NCS_FLAG"}  ) )  { push ( @{$my_main{"PREF_NCS_FLAG"}} , "OFF" ) ; }
if ( !exists( $my_main{"PREF_NCS_FORCE"} ) )  { push ( @{$my_main{"PREF_NCS_FORCE"}} , 5.0 ) ; }
if ( !exists( $my_main{"PREF_PRECISION"}  ) )  { push ( @{$my_main{"PREF_PRECISION"}} , 3 ) ; }
if ( !exists( $my_main{"PREF_SCAL_XTARG"} ) )  { push ( @{$my_main{"PREF_SCAL_XTARG"}} , 1.5 ) ; }
if ( !exists( $my_main{"PREF_STEP_COOL"} ) )  { push ( @{$my_main{"PREF_STEP_COOL"}} , 0 ) ; }
if ( !exists( $my_main{"PREF_STEP_MIN"}  ) )  { push ( @{$my_main{"PREF_STEP_MIN"}}  , 30 ) ; }
if ( !exists( $my_main{"PREF_TARGET"}  ) )  { push ( @{$my_main{"PREF_TARGET"}}, "FREE_KICK" ) ; }
if ( !exists( $my_main{"PREF_WAY"}  ) )  { push ( @{$my_main{"PREF_WAY"}} , "FAST" ) ; }

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

my $MACRO_FILE = "refine_all.cmds" ;
my $PROC_ERROR = "FALSE" ;
my $doit = "FALSE" ;

my $keyword ; 
foreach $keyword ( sort keys (%commands) ) 
{
#    print " keyword >$keyword<\n" ;
    if ( $keyword eq 'z' || substr($keyword, 0,3) eq "xyz" ) { goto XYZ }
    if ( $keyword eq '1' || substr($keyword, 0,5) eq "sigma"  ) { goto SIGMA }
    if ( $keyword eq 'u' || substr($keyword, 0,6) eq "cutoff" ) { goto DIST_CUTOFF }
    if ( $keyword eq 'k' || substr($keyword, 0,6) eq "p_kick" ) { goto P_KICK }

    if ( $keyword eq 'v' || substr($keyword, 0,4) eq "over" ) { goto OVER }
    if ( $keyword eq 'b' || substr($keyword, 0,7) eq "bfactor" ) { goto BFACTOR } 
    if ( $keyword eq '2' || substr($keyword, 0,7) eq "b_sigma"  ) { goto B_SIGMA }
    if ( $keyword eq 'd' || substr($keyword, 0,6) eq "define" ) { goto DEFINE }
    if ( $keyword eq 'g' || substr($keyword, 0,5) eq "group" ) { goto GROUP }
    if ( $keyword eq 'p' || substr($keyword, 0,4) eq "bond" ) { goto BOND }
    if ( $keyword eq 'i' || substr($keyword, 0,6) eq "b_kick" ) { goto B_KICK }
    if ( $keyword eq 'j' || substr($keyword, 0,6) eq "tickle" ) { goto TICKLE }
    if ( $keyword eq 'a' || substr($keyword, 0,6) eq "adjust" ) { goto ADJUST }
#    if ( $keyword eq 'l' || substr($keyword, 0,5) eq "angle" ) { goto ANGLE }

    if ( $keyword eq '5' || substr($keyword, 0,10) eq "occupancy" ) { goto OCCUPANCY }

    if ( $keyword eq 'n' || substr($keyword, 0,3) eq "ncs"  ) { goto NCS }
    if ( $keyword eq 'y' || substr($keyword, 0,9) eq "cryst_ncs" ) { goto CRYST_NCS }
    if ( $keyword eq 'f' || substr($keyword, 0,4) eq "fncs" ) { goto FNCS }
    if ( $keyword eq 'g' || substr($keyword, 0,4) eq "gncs" ) { goto GNCS }

    if ( $keyword eq 't' || substr($keyword, 0,6) eq "target" ) { goto TARGET }
    if ( $keyword eq 'c' || substr($keyword, 0,4) eq "cool" ) { goto COOL }
    if ( $keyword eq 'l' || substr($keyword, 0,7) eq "ml_kick" ) { goto ML_KICK }
    if ( $keyword eq 'v' || substr($keyword, 0,7) eq "ml_aver" ) { goto ML_AVER }
    if ( $keyword eq 'm' || substr($keyword, 0,3) eq "map"  ) { goto MAP }
    if ( $keyword eq 'r' || substr($keyword, 0,9) eq "precision" ) { goto PRECISION }
    if ( $keyword eq 'q' || substr($keyword, 0,4) eq "grid" ) { goto GRID }
    if ( $keyword eq 'f' || substr($keyword, 0,4) eq "free" ) { goto FREE }

    if ( $keyword eq 'b' || substr($keyword, 0,5) eq "bramp" ) { goto BRAMP }
    if ( $keyword eq 'j' || substr($keyword, 0,4) eq "badd" ) { goto BADD }
    if ( $keyword eq 'w' || substr($keyword, 0,3) eq "way"  ) { goto WAY }
    if ( $keyword eq 'x' || substr($keyword, 0,6) eq "backup" ) { goto BACKUP }
    if ( $keyword eq 'o' || substr($keyword, 0,6) eq "output" ) { goto OUTPUT }
    if ( $keyword eq 'h' || substr($keyword, 0,4) eq "help" ) { goto HELP }
    if ( substr($keyword, 0,4) eq "doit" ) { $doit = "TRUE" ; next ; }

    print "unknown option >$keyword<\n" ; $PROC_ERROR = "TRUE" ;

  HELP:
    print << "END_OF_TEXT" ;
-h|--help)      prints this message with available options and current status 
-c|--cool)      sets number of cooling cycles [@{$my_main{"PREF_STEP_COOL"}}]

-z|--xyz)       POSITIONAL REFINEMENT steps per cycle [ [-1 off; >0 on] [@{$my_main{"PREF_STEP_MIN"}}]
-1|--sigma)     sigma target for bond deviations  [0.005 - 0.1]
                current = [@{$my_main{"PREF_SCAL_XTARG"}}]
-p|--p_kick)    sets starting and final maximal xyz kick [0.0 - 0.33]
                current = [@{$my_main{"PREF_KICK_CR0"}} - @{$my_main{"PREF_KICK_CR1"}}]
-m|--map)       MAP for DENSITY refinement [@{$my_main{"PREF_MAP_DENS"}}]
-u|--cutoff)    distance cutoff for nonbonded interactions [@{$my_main{"PREF_DIST_CUTOFF"}}]

-v|--overall)   B-FACTOR REFINEMENT overall  [-1 off; >0 on] = [$my_main{"BREF_OVER_STEP"}[0]]
-b|--bfactor)   B-FACTOR REFINEMENT individual steps per cycle steps [-1 off; >0 on ] = [$my_main{"BREF_IND_STEP"}[0]]
-2|--b_sigma)   sigma target for standard deviations of bonded B-values [1. - 10.]
                  current = [@{$my_main{"BREF_SCAL_XTARG"}}]
-k|--b_kick)    sets starting and final maximal B-kick [0 - 30] current = [$my_main{"BREF_KICK_B0"}[0] - $my_main{"BREF_KICK_B1"}[0]]
-p|--bond)      B-value bond inter-group constrain force [-1.0 off; > 0.0 on] = [$my_main{"BREF_FORCE_BOND"}[0]]
-d|--define)    define group B-value organisation [SINGLE/ATOM/RESIDUE/SEGMENT] = [$my_main{"BREF_GROUP"}[0]]
-g|--group)     B-value intra-group constrain force [-1.0 hard; > 0.0 soft] = [$my_main{"BREF_FORCE_GROUP"}[0]]

-5|--occupancy) OCCUPANCY REFINEMENT [-1 off; >0 on] = [$my_main{"OREF_IND_STEP"}[0]]

-n|--ncs)       NCS - Non-Cryst-Symmetry NCS energy flag [ON/OFF]
                current = [@{$my_main{"PREF_NCS_FLAG"}}]
-y|--cryst_ncs) Refine in variety of crystal forms [ON/OFF]: current = [@{$my_main{"PREF_NCS_CRYST"}}]
-g|--gncs)      Non-Cryst-Similarity NCS geometry force = [@{$my_main{"PREF_NCS_FORCE"}}]
-f|--fncs)      B-value NCS force  = [$my_main{"BREF_NCS_FORCE"}[0]]
END_OF_TEXT

    print << "END_OF_TEXT" ;
-t|--target)    TARGET FUNCTION for refinement [MAP/REAL_SPACE/LSQ/CROSS_COR/FREE_KICK/REFMAC/PHENIX]
                current = [@{$my_main{"PREF_TARGET"}}]
-f|--free)      r-free flag [ON/OFF] current [@{$my_main{"DFR_RFREE"}}]
-l|--ml_kick)   kick ratio for ML function  [0.0 - 3.0] [@{$my_main{"PREF_ML_KICK"}}]
-j|--tickle)    tickle for minimizer - negative is off [0.0 - 1.0] [@{$my_main{"PREF_TICKLE"}}]
-a|--adjust)    adjust energy scale steps on the fly - negative is off [@{$my_main{"PREF_ADJUST_STEP"}}]
-v|--ml_aver)   averaging over last n AB coefifients for ML function  [@{$my_main{"PREF_ML_AVER"}}]
-w|--way)       way of reciprocal space refinement [ACCURATE/FAST] [@{$my_main{"PREF_WAY"}}]
-r|--precision) precsion of x derivatives [@{$my_main{"PREF_PRECISION"}}]
-q|--grid)      map grid spacings per resolution [@{$my_main{"PREF_MAP_GRID"}}]
-j|--badd)      B factor add value /-999 leaves default [@{$my_main{"PREF_BVAL_ADD"}}]
-x|--backup)    backup after each cycle [ON/OFF]: current = [@{$my_main{"PREF_BACKUP"}}]
-o|--output)    set file name of the created macro [$MACRO_FILE]
   --doit)      create the macro

END_OF_TEXT
#-q|--qmap)      MAP for rec. space refinement [@{$my_main{"PREF_MAP_XTARG"}}]
    exit ;
 OUTPUT: $MACRO_FILE = shift ( @{$commands{$keyword}} ) ; next ;

 XYZ:  @{$my_main{"PREF_STEP_MIN"}} = shift ( @{$commands{$keyword}} ) ; next ;
 SIGMA:   @{$my_main{"PREF_SCAL_XTARG"}} = shift ( @{$commands{$keyword}} ) ; next ;
 DIST_CUTOFF:   @{$my_main{"PREF_DIST_CUTOFF"}} = shift ( @{$commands{$keyword}} ) ; next ;

 P_KICK:  
    @{$my_main{"PREF_KICK_CR0"}} = shift ( @{$commands{$keyword}} ) ; 
    @{$my_main{"PREF_KICK_CR1"}} = shift ( @{$commands{$keyword}} ) ; 
#print "kicks: {", $my_main{"PREF_KICK_CR0"}[0], $my_main{"PREF_KICK_CR1"}[0], "} \n" ;
    next ;

 OVER:    @{$my_main{"BREF_OVER_STEP"}} = shift ( @{$commands{$keyword}} ) ; next ;
 BFACTOR:    @{$my_main{"BREF_IND_STEP"}} = shift ( @{$commands{$keyword}} ) ; next ;
 B_SIGMA: @{$my_main{"BREF_SCAL_XTARG"}} = shift ( @{$commands{$keyword}} ) ; next ;
 DEFINE: @{$my_main{"BREF_GROUP"}} = shift ( @{$commands{$keyword}} ) ; next ;
 GROUP:  @{$my_main{"BREF_FORCE_GROUP"}} = shift ( @{$commands{$keyword}} ) ; next ;
 BOND:   
    @{$my_main{"BREF_FORCE_BOND"}} = shift ( @{$commands{$keyword}} ) ; 
    @{$my_main{"BREF_FORCE_ANGLE"}} = ( sqrt( 2*${$my_main{"BREF_FORCE_BOND"}}[0]**2)*0.5  ) ; 
    if ( $my_main{"BREF_FORCE_BOND"}[0] le 0.0 )
	{ $my_main{"BREF_FORCE_ANGLE"}[0] = -1 * $my_main{"BREF_FORCE_ANGLE"}[0] ;}
#print " angle = ", ${$my_main{"BREF_FORCE_ANGLE"}}[0], "sqrt 2 = " , sqrt(2.0), " bond: ", ${$my_main{"BREF_FORCE_BOND"}}[0] , "\n" ;

         next ;
# ANGLE:  @{$my_main{"BREF_FORCE_ANGLE"}} = shift ( @{$commands{$keyword}} ) ; next ;
 B_KICK:  
    @{$my_main{"BREF_KICK_B0"}} = shift ( @{$commands{$keyword}} ) ; 
    @{$my_main{"BREF_KICK_B1"}} = shift ( @{$commands{$keyword}} ) ; 
    next ;

 OCCUPANCY: @{$my_main{"OREF_IND_STEP"}} = shift ( @{$commands{$keyword}} ) ; next ;

  NCS:   @{$my_main{"PREF_NCS_FLAG"}} = shift ( @{$commands{$keyword}} ) ; next ;
  CRYST_NCS:    @{$my_main{"PREF_NCS_CRYST"}} = uc(shift ( @{$commands{$keyword}} )) ; next ;
  GNCS:    @{$my_main{"PREF_NCS_FORCE"}} = shift ( @{$commands{$keyword}} ) ; next ;
  FNCS:  @{$my_main{"BREF_NCS_FORCE"}} = shift ( @{$commands{$keyword}} ) ; next ;

  TARGET: @{$my_main{"PREF_TARGET"}} = uc(shift ( @{$commands{$keyword}} )) ; next ;
  COOL:  @{$my_main{"PREF_STEP_COOL"}} = shift ( @{$commands{$keyword}} ) ; 
         @{$my_main{"BREF_STEP_COOL"}} = $my_main{"PREF_STEP_COOL"}[0] / 2 ;
         next ;
  ML_KICK: @{$my_main{"PREF_ML_KICK"}} = shift ( @{$commands{$keyword}} ) ; next ;
  ML_AVER: @{$my_main{"PREF_ML_AVER"}} = shift ( @{$commands{$keyword}} ) ; next ;
  TICKLE: @{$my_main{"PREF_TICKLE"}} = shift ( @{$commands{$keyword}} ) ; next ;
  ADJUST: @{$my_main{"PREF_ADJUST_STEP"}} = shift ( @{$commands{$keyword}} ) ; next ;
#  ATOMS:  @{$my_main{"PREF_ML_MISSIN"}} = shift ( @{$commands{$keyword}} ) ; next ;
  MAP:   @{$my_main{"PREF_MAP_DENS"}} = shift ( @{$commands{$keyword}} ) ; next ;
  GRID:   @{$my_main{"PREF_MAP_GRID"}} = shift ( @{$commands{$keyword}} ) ; next ;
  BRAMP: 
    @{$my_main{"PREF_BVAL_MIN"}} = shift ( @{$commands{$keyword}} ) ; 
    @{$my_main{"PREF_BVAL_MAX"}} = shift ( @{$commands{$keyword}} ) ; 
    next ;

  BADD: 
    @{$my_main{"PREF_BVAL_ADD"}} = shift ( @{$commands{$keyword}} ) ; 
    next ;

  WAY:    @{$my_main{"PREF_WAY"}} = uc(shift ( @{$commands{$keyword}} )) ; next ;
  FREE:  @{$my_main{"DFR_RFREE"}} = uc(shift ( @{$commands{$keyword}} )) ; next ;
  PRECISION:  @{$my_main{"PREF_PRECISION"}} = shift ( @{$commands{$keyword}} ) ; next ;





TARGET: @{$my_main{"PREF_TARGET"}} = shift ( @{$commands{$keyword}} ) ; next ;
FREE: @{$my_main{"DFR_RFREE"}} = shift ( @{$commands{$keyword}} ) ; next ;
COOL:  @{$my_main{"BREF_STEP_COOL"}} = shift ( @{$commands{$keyword}} ) ; next ;
WAY:    @{$my_main{"PREF_WAY"}} = uc(shift ( @{$commands{$keyword}} )) ; next ;
BACKUP:  @{$my_main{"PREF_BACKUP"}} = 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 ) ; 

###  . ${MAIN_CONF}main_config.data.save.sh

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

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

print "creating \"$MACRO_FILE\" \n" ;
if ( -f $MACRO_FILE ) 
{ 
    my $back = join ('', $MACRO_FILE, ".old" ) ; 
    system ( "mv  $MACRO_FILE $back" ) ; 
}

my $REF_TARGET = $my_main{"PREF_TARGET"}[0] ;
#print " MY REF TARGET: }", $REF_TARGET, "{\n";
if ( $REF_TARGET eq "REFMAC" ) { &create_refmac_refine  ;}
if ( $REF_TARGET eq "PHENIX" ) { &create_phenix_refine  ;}

open ( MACRO,  "> $MACRO_FILE" ) || die "FILE OPEN ERROR: >$MACRO_FILE< \n" ;
my $FH = *MACRO ;

my $BVAL_MAX = ${$my_main{"PREF_BVAL_MAX"}}[0] ;
my $BVAL_MIN = ${$my_main{"PREF_BVAL_MIN"}}[0] ;
my $NZONES = ${$my_main{"MAP_ZONES"}}[0] ;
my $DIST_CUTOFF = ${$my_main{"PREF_DIST_CUTOFF"}}[0] ;
#print " my zones::", $NZONES, "{\n" ;
my $WAT_SEGM = ${$my_main{"WAT_SEGM"}}[0] ;
my $WAT_SEGM_D = ${$my_main{"WAT_SEGM"}}[$#{$my_main{"WAT_SEGM"}}] ;

my $REF_BVAL = "OFF" ;  if (  $my_main{"BREF_IND_STEP"}[0] > 0 ) { $REF_BVAL = "ON" ; }
my $REF_B_ALL= "OFF" ; if (  $my_main{"BREF_OVER_STEP"}[0] > 0 ) { $REF_B_ALL = "ON" ; }
my $REF_XYZ = "OFF" ; if (  $my_main{"PREF_STEP_MIN"}[0] > 0 ) { $REF_XYZ = "ON" ; }
my $REF_OCC = "OFF" ; if (  $my_main{"OREF_IND_STEP"}[0] > 0 ) { $REF_OCC = "ON" ; }
my $ADJUST =  ${$my_main{"PREF_ADJUST_STEP"}}[0] ;
my $TICKLE =  ${$my_main{"PREF_TICKLE"}}[0] ;

my $TICKLE_TEXT = "" ;
if ( $TICKLE > 0 ) 
{
    $TICKLE_TEXT = "tickle " . $TICKLE ;
}


my $NO_PREP = "" ;

print MACRO << "END_OF_TEXT" ;

! renames new waters to prevent deletions of already accepted solvents
rename segm $WAT_SEGM sele segm name $WAT_SEGM_D end 
set vari II int segm sele segm name $WAT_SEGM end
set vari SEGMENTS = WORK_SEGM
if ( II .gt. 0 ) then
set vari WORK_SEGM char global - 
	segm sele segm name WORK_SEGM .o segm name $WAT_SEGM  end
! X set vari SEGMENTS char global - 
! X 	segm sele segm name SEGMENTS .o segm name WAT end
end_if

END_OF_TEXT


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

#energy stuff and parameters

if ( $NCRYST == 1 ) 
{
print MACRO "<DEF_ALL WORK_SEGM\n" ;
}
else
{
print MACRO "set vari SEGMENTS = \"\\\n" ;
    for ( $CRYST = 0; $CRYST < $NCRYST ; $CRYST++ )
    {
	$GROUP = join ( '', "SG_CRYST" , $CRYST+1 ) ;
	print MACRO join(" ", @{$my_main{$GROUP}}), " \\\n" ;
    }
print MACRO "\"\n" ;
print MACRO "<DEF_ALL SEGMENTS\n" ;


}

print MACRO << "END_OF_TEXT" ;

ener pair off chem ( diel = 2.0 ) ! reduces electrostatics
ener chem ( cutoff $DIST_CUTOFF )
set weight sele atom name H* end = 0.0 ! kick out Hs from calculation
set temp sele atom name H* end = 0.0 
set temp sele temp -0.1 0.1 .a .not atom name H* end = 30.0 ! sets Bs for new atoms
set temp sele temp $BVAL_MAX   1000. end = $BVAL_MAX  
set temp sele temp $BVAL_MIN  -10000 end = $BVAL_MIN


END_OF_TEXT

# BFACTOR setup
if ( $my_main{"BREF_GROUP"}[0] eq "SINGLE" )
{ print MACRO "define sele segm name SEGMENTS end init b-val group single\n" ; }
elsif ( $my_main{"BREF_GROUP"}[0] eq "ATOM" )
{ print MACRO "define sele segm name SEGMENTS end init b-val group atom\n" ; }
elsif ( $my_main{"BREF_GROUP"}[0] eq "RESIDUE" )
{ print MACRO "define sele segm name SEGMENTS end init b-val group residue\n" ; } 
elsif ( $my_main{"BREF_GROUP"}[0] eq "SEGMENT" )
{ print MACRO "define sele segm name SEGMENTS end init b-val group segment\n" ; }
else 
{ 
    print MACRO "%ERROR: BREF_GROUP $my_main{\"BREF_GROUP\"}[0]: bad value\n" ; 
    print "%ERROR: BREF_GROUP $my_main{\"BREF_GROUP\"}[0]: bad value\n" ; 
}

print MACRO "define sele segm name SEGMENTS end init b-val weigh ( = 0.8 root CA root C root N ) \n" ; 
print MACRO << "END_OF_TEXT" ;

ener b-val ( \\
	     group = $my_main{"BREF_FORCE_GROUP"}[0] \\ 
             bond = $my_main{"BREF_FORCE_BOND"}[0] \\ 
             angle = $my_main{"BREF_FORCE_ANGLE"}[0] \\ 
             mini = $my_main{"PREF_BVAL_MIN"}[0] \\ 
             maxi = $my_main{"PREF_BVAL_MAX"}[0] \\
           )

END_OF_TEXT

# MAPs

my $MAP_CREATED = "NO" ;
my $MAP = $my_main{"PREF_MAP_XTARG"}[0] ;

my $MAP_GRID = $my_main{"PREF_MAP_GRID"}[0] ;

if ( $NCRYST == 1 ) 
{
    if ( $REF_TARGET ne "MAP" )
    {
	print MACRO << "END_OF_TEXT" ;

make map from 0 auto_grid $MAP_GRID init empty cell real 
if ( MAP_LAST .lt. 0 ) return
set vari MAP_TARG int global = MAP_LAST

END_OF_TEXT

# 	if ( $my_main{"PREF_MAP_XTARG"}[0] !~ m"[0-9]" )
# 	{
# 	    print MACRO << "END_OF_TEXT" ;
#  ! nmaps + 1	
#  set vari MAP_TARG = nmaps + 1
# 		
# END_OF_TEXT
# 	}
# 	else
# 	{
# 	    if ( $my_main{"SG_NCRYST"}[0] > 1 && $MAP <= $my_main{"SG_NCRYST"}[0] * 2 ) { $MAP = $my_main{"SG_NCRYST"}[0] * 2 + 1 ; }
# print MACRO << "END_OF_TEXT" ;
# 
# ! MAP_TARG as specified
#  set vari MAP_TARG = $MAP
# 
# END_OF_TEXT
# 	}
     }

    if ( $REF_TARGET eq "MAP" ) 
    {
	print MACRO << "END_OF_TEXT" ;

 ener  dens ( on map $my_main{"PREF_MAP_DENS"}[0] poly 2 )

END_OF_TEXT

    }
    elsif ( $REF_TARGET eq "REAL_SPACE" ) 
    {
    $MAP_CREATED = "YES" ;
    print MACRO << "END_OF_TEXT" ;

 ener  dens ( on map MAP_TARG poly 2 )

END_OF_TEXT
    }
    else
    {
	$MAP_CREATED = "YES" ;
	print MACRO << "END_OF_TEXT" ;

  ener x-targ ( \\
                on \\ 
                map MAP_TARG \\
              )

END_OF_TEXT
    }

#     if ( $MAP_CREATED eq "YES" ) 
#     {
# 	
# 	print MACRO << "END_OF_TEXT" ;
# 
#  make map auto_grid 4.0 init cell real 
# if ( MAP_LAST .lt. 0 ) return
# set vari MAP_TARG int = MAP_LAST
# 
# END_OF_TEXT
#     }
}
# several crystal forms
else
{
    print MACRO "define init constr map \n" ;
    for ( $CRYST = 0; $CRYST < $NCRYST ; $CRYST++ )
    {
	if ( $REF_TARGET eq "MAP" ) 
	{
	    $MAP =  $CRYST * 2 + 1 ;
	    print MACRO "make map $MAP conv real \n" ;
	}
	else {
	    $MAP =  $CRYST * 2 + 2 ;
	    print MACRO "make map $MAP conv real \n" ;
	}
	$GROUP = join ( '', "SG_CRYST" , $CRYST+1 ) ;
	print MACRO 
	    "set vari SEG_CRYST = \"", join(" ", @{$my_main{$GROUP}}), "\"\n",
	    "define constr map ", $MAP, 
	    " sele segm name SEG_CRYST end \n",
	    "energy dens ( map $MAP scale 100.0 ) \n" ;
    }
    print MACRO "\n" ;
    if ( $REF_TARGET eq "MAP" ) 
    {
print MACRO << "END_OF_TEXT" ;

 ener  dens ( on map $my_main{"PREF_MAP_DENS"}[0] poly 2 )

END_OF_TEXT

    }
    else
    {

	my $macro_file = join ('', $ENV{"MAIN_CONF"}, "create_multi_deriv_maps.pl" ) ; 
	system ( "$macro_file" ) ; 
	print MACRO << "END_OF_TEXT" ;
  set vari MAP_TARG = $MAP
  ener x-targ ( \\
                on \\ 
                map MAP_TARG \\
              )

END_OF_TEXT
    }
}

my $FL_BACKGROUND = 0 ;
######## NCS region definition
if ( $my_main{"PREF_NCS_FLAG"}[0] eq "ON" ) 
{
# print " groups @{$my_main{\"SG_NMOL\"}}[0] < @{$my_main{\"SG_NGROUP\"}}[0]  \n" ;
    my $NCS_FORCE = $my_main{"PREF_NCS_FORCE"}[0] ;
    print MACRO "ener ncs scale $NCS_FORCE \n" ;
if ( @{$my_main{"SG_NMOL"}}[0] > @{$my_main{"SG_NGROUP"}}[0] )
{
    print MACRO
	"! include all the non equivalent residues here\n", 
	" key out sele .not all end\n",
	" key out_side sele .not all end\n",
	" <define_key_out.com\n\n",
	"! defining groups \n" ;

    my ( $IGR, $GROUP, $STRATEGY );
    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" && $FL_BACKGROUND == 0 )
	{
	    $FL_BACKGROUND++ ;
	    print MACRO "key background sele .n all end\n" ;
	}
	if ( $my_main{$STRATEGY}[0] ne "COMPOSIT" ) 
	{
	    if ( $NCS_START eq "FALSE" )
	    { 
		print MACRO " define init constr ncs \n" ;
		$NCS_START = "TRUE" ;
	    }
	    else
	    { 
		print MACRO " define constraint ncs next \n" ; 
	    }
	    
	    my $MEMBER ; my $NN_GROUP=0 ;
	    foreach $MEMBER ( @{$my_main{$GROUP}} )
	    {
		$NN_GROUP++;
#	print " member: $MEMBER> \n" ;
#		if ( $NN_GROUP ne 1 ) 
#		{
#		    print MACRO
#			" rms coor all eigen \\ \n",
#			"    sele atom name CA N C O H CB %G* %D* \\ \n",
#			"   .a ( segm name  $MEMBER .a .not out ) end sele int_ncs__1 end \n" ;
#		    print MACRO " define constr ncs sele atom name CA N C O H CB %G* %D* \\ \n",
#		    "          .a ( segm name $MEMBER .a .not out ) end  last_rms polar \n"
#		    } 
#		else
#		{
		print MACRO " define constr ncs sele atom name CA N C O H CB %G* %D* \\ \n",
		"          .a ( segm name $MEMBER .a .not out .a .n out_side ) end \n"
#		}
	    }
	    my $NCS_KEY ; my $NCS_TXT ; my $NCS_KEY_BASE ;
	    $NN_GROUP=0 ;
	    foreach $MEMBER ( @{$my_main{$GROUP}} )
	    {
		$NN_GROUP++;
		$NCS_KEY = sprintf ( "%7s%2d%3d", "int_ncs", $IGR, $NN_GROUP );
		$NCS_KEY =~ s/ /\_/g ;
		if ( $NN_GROUP == 1 ) 
		{ $NCS_KEY_BASE = $NCS_KEY ; }
		else
		{ 

		    print MACRO "make pair init sele $NCS_KEY_BASE end sele $NCS_KEY end seq name_mat \n" ;
		    print MACRO "key $NCS_KEY_BASE sele $NCS_KEY_BASE .a by pair $NCS_KEY end \n" ;
		    print MACRO "key $NCS_KEY sele $NCS_KEY .a by pair $NCS_KEY_BASE end \n\n" ;
		    print " key for NCS:", $NCS_KEY, "\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" ;
    }
}
}
else
{
    print MACRO " define init constr ncs \n" ;
}

#    print MACRO "return \n" ;
    print MACRO " set coord save now \n" ;
    print MACRO " set coord save off \n" ;

###########  KICKS and REFINEMENT

#print MACRO "!echo NZONES= }", $NZONES, "{\n" ;

if ( $REF_TARGET ne "MAP" && $REF_TARGET ne "REAL_SPACE"  )

{ 
# print MACRO "< ?MAIN_CMDS_NEW:re_phase.cmds WORK_SEGM MAP_WORK $NZONES\n" ; 
    &create_re_phase ;
}

my $STEP_COOL = 0 ; my $NCOOL = 0 ;

#print " pref_step_cool @{$my_main{\"PREF_STEP_COOL\"}} \n";
if ( @{$my_main{"PREF_STEP_COOL"}}[0] > 1 )
{
    $STEP_COOL = @{$my_main{"PREF_STEP_COOL"}}[0] ;
    $NCOOL = $STEP_COOL ;
# print " pref_step_cool minus 1 @{$my_main{\"PREF_STEP_COOL\"}}[0] \n";
}
else { $NCOOL = 0 ; }

    if ( $REF_B_ALL eq "ON" && $REF_TARGET ne "MAP" )
{
    &create_refine_bval_overall () ;
}

print MACRO "mini list_gen renew\n" ; 

    my $I ; my $COOL_SUM ;
$I=0 ; $COOL_SUM = 0 ;
my @cool_array = () ;
for ( $I=0 ; $I <= $NCOOL ; $I++ )
{
    $COOL_SUM = $COOL_SUM + $I ;
    push ( @cool_array, $COOL_SUM ) ;
#    print " I $I S $COOL_SUM \n" ;
}

$I=0 ; 
if ( $NCOOL == 0 ) { $NCOOL = -1 ; }
for ( $I=0 ; $I <= $NCOOL ; $I++ )
{

#print " in III  $I cool is $NCOOL - @{$my_main{\"PREF_STEP_COOL\"}}[0] \n";
    print MACRO "! $I > cool cycle out of $NCOOL \n";

#    if ( $REF_XYZ eq "ON" && $REF_BVAL eq "OFF" ) 
    if ( $REF_XYZ eq "ON" ) 
    {
	if ( $I > 0 ) { print MACRO "mini list_gen keep\n" ; }
	my $KICK = 0 ;
	if ( @{$my_main{"PREF_STEP_COOL"}}[0] == 1 )
	{
	print MACRO
	" \n",
	" ! kick : 0.02 very small: 0.33 the largest managable by minimizer \n",
	" set coor kick @{$my_main{\"PREF_KICK_CR0\"}}[0] sele segm name SEGMENTS end \n\n";
	}
	elsif ( @{$my_main{"PREF_STEP_COOL"}}[0] > 1 )
	{
	    my $PX = ( $COOL_SUM - $cool_array[$STEP_COOL-$I] ) / $COOL_SUM ;
	    $KICK = ( @{$my_main{"PREF_KICK_CR0"}}[0] - @{$my_main{"PREF_KICK_CR1"}}[0] ) *
		(1. - $PX) + @{$my_main{"PREF_KICK_CR1"}}[0] ;
#    print " PARTIAL: ( $COOL_SUM - $I) / $STEP_COOL = $PX > $KICK \n";
#    print " PARTIAL: ( $STEP_COOL - $I) / $STEP_COOL = $PX > $KICK \n";
	    printf MACRO
	"\n set coor kick %6.3f sele segm name SEGMENTS end \n", $KICK ;
	}

	else { print MACRO "\n ! no kick applied \n" ; }

	&create_refine_xyz ( $KICK ) ;

    }

#    if ( $REF_BVAL eq "ON" && $REF_XYZ eq "OFF" ) 
    if ( $REF_BVAL eq "ON" ) 
    {
	if ( $STEP_COOL == 1 )
	{
	    print MACRO << "END_OF_TEXT" ;

! kick : 4. the usual one 
set temp kick $my_main{"BREF_KICK_B0"}[0] sele segm name SEGMENTS end 
END_OF_TEXT
	}
		elsif ( $STEP_COOL > 1 )
	{
	    my $PX = ( $COOL_SUM - $cool_array[$STEP_COOL-$I] ) / $COOL_SUM ;
#	    print " pcss: $PX, $COOL_SUM, $STEP_COOL\n" ;
	    my $KICK_VAL = ( $my_main{"BREF_KICK_B0"}[0] - $my_main{"BREF_KICK_B1"}[0] ) *
		(1. - $PX) + @{$my_main{"BREF_KICK_B1"}}[0] ;
	    print MACRO "set temp kick $KICK_VAL sele segm name SEGMENTS end \n" ;
	}
	else { print MACRO "! no B-value kick applied \n" ; }

	&create_refine_bval ;
    }
######## OCCUAPNCY REF
    if ( $REF_OCC eq "ON" )
    {
	&create_refine_occupancy () ;
    }
}

#print " ncool = $NCOOL \n" ;
if ( $NCOOL <= 0 )
{
    if ( $REF_XYZ eq "ON" ) 
    {
	&create_refine_xyz ( ) ;
    }
    
    if ( $REF_BVAL eq "ON" ) 
    {
	&create_refine_bval () ;
    }
######## OCCUAPNCY REF
    if ( $REF_OCC eq "ON" )
    {
	&create_refine_occupancy () ;
    }
}

if ( ${$my_main{"PREF_BACKUP"}}[0] eq "ON" )
{
    my $my_file ; 
    if ( @{$my_main{"PREF_STEP_COOL"}}[0] > 1 )
    {
	my $PX = ( $STEP_COOL - $I ) / $STEP_COOL ;
#    print " PARTIAL: ( $STEP_COOL - $I) / $STEP_COOL = $PX \n";
	my $KICK = ( @{$my_main{"PREF_KICK_CR0"}}[0] - @{$my_main{"PREF_KICK_CR1"}}[0] ) *
	    $PX + @{$my_main{"PREF_KICK_CR1"}}[0] ;
	my $ttt = sprintf ( "%6.2f",  $KICK );
	$ttt =~ s/ //g ;
	$my_file = join ( "", "SAVE_FILE_refined_", 
			  $ttt, "-", $I, , ".PDB" ) ;
    }
    else
    {
	$my_file = join ( "", "SAVE_FILE_refined_", $I, , ".PDB" ) ;
    }
    
    print MACRO "write over file $my_file sele segm name SEGMENTS end coor pdb \n" ;
    
}

 

####### return to interactive local minimizer

if ( $MAP_CREATED eq "YES" ) 
{
print MACRO << "END_OF_TEXT" ;
 delete map MAP_TARG
 delete vari MAP_TARG
END_OF_TEXT
}

if ( $NCRYST > 1 ) 
{
print MACRO << "END_OF_TEXT" ;
define init constr map
END_OF_TEXT
}

if ( $my_main{"PREF_NCS_FLAG"}[0] eq "ON" ) 
{
print MACRO << "END_OF_TEXT" ;
energy ncs off
END_OF_TEXT
}

print MACRO << "END_OF_TEXT" ;
 ! reset scale for MINIMIZE (later on ...)
 ener  dens ( on map MAP_2FOFC poly 2 ) \\ 
       ncs off
 mini any position write 1 step 15 list renew
mini adjust ( bond = 0.02 step = 100 )

set coord save on

return
END_OF_TEXT

close(MACRO) ;

exit ;


sub create_re_phase
{

print MACRO << "END_OF_TEXT" ;
key map_dens select segm name WORK_SEGM end
END_OF_TEXT

my $NZONES = ${$my_main{"MAP_ZONES"}}[0] ;
my $ZONE_TEXT ;
if ( $NZONES > 0 ) { $ZONE_TEXT = join ( " ", "shell", $NZONES ) ; } else { $ZONE_TEXT = "" ; } ;

my $BADD = ${$my_main{"PREF_BVAL_ADD"}}[0] ;
if ( $BADD > -999 ) 
{ 
    my $TEXT = join ( " ", "four b_add", $BADD ) ;
print MACRO $TEXT, "\n" ; 
}



print MACRO << "END_OF_TEXT" ;

if ( RESOL_MAX .gt. 1.5 ) then
set weight sele segm name WORK_SEGM .a atom name H* end = 0.0
set temp sele segm name WORK_SEGM .a temp -100. 1.0 end = 1.0
end_if

END_OF_TEXT

print MACRO "refl bulk ( least_square )\n" ; 

if ( ${$my_main{"MAP_BULK"}}[0] eq "ON" || ${$my_main{"MAP_BULK"}}[0] eq "USE" )
{
print MACRO << "END_OF_TEXT" ;
refl aniso off

set rad sele segm name WORK_SEGM .a .n segm name XWAT* end  vdw
scale 1.06 rad sele  segm name WORK_SEGM end 

make map MAP_TARG bulk \\
     ( select segm name WORK_SEGM end \\
       solvent 0.0 fill 1.8 shrink 0.4 ) 


make map MAP_TARG set 999990 1000000 1.0
make map MAP_TARG set -1000000 -999990 0.0

fourier map MAP_TARG 
refl bulk off
refl sele defined .a resol RESOL_MIN 3.0 end set ampl phase fpart = fcalc * 1.0
refl bulk ( on )

END_OF_TEXT
}
if (  ${$my_main{"MAP_BULK"}}[0] eq "USE" )
{
print MACRO << "END_OF_TEXT" ;
refl bulk on

END_OF_TEXT
}
elsif (  ${$my_main{"MAP_BULK"}}[0] eq "OFF" )
{
print MACRO << "END_OF_TEXT" ;
refl bulk off

END_OF_TEXT
}




#refl sele defined .a resol RESOL_MIN 3.0 end aniso ( on init )
if ( ${$my_main{"MAP_ANISO"}}[0] eq "ON" )
{
print MACRO << "END_OF_TEXT" ;
refl sele defined end aniso ( on init )
END_OF_TEXT
}
elsif (  ${$my_main{"MAP_ANISO"}}[0] eq "USE" )
{
print MACRO << "END_OF_TEXT" ;
refl aniso on
END_OF_TEXT
}
elsif (  ${$my_main{"MAP_ANISO"}}[0] eq "OFF" )
{
print MACRO << "END_OF_TEXT" ;
refl aniso off

END_OF_TEXT
}

print MACRO << "END_OF_TEXT" ;

make map MAP_TARG conv real
make map MAP_TARG zero

make map MAP_TARG atom symm -
                  atom dens -
                  sele map_dens end

fourier map MAP_TARG 
END_OF_TEXT

#	print MACRO "refl aniso ( init )\n" ; 
#{

if ( ${$my_main{"MAP_BULK"}}[0] eq "ON" )
{    
    print MACRO "reflection sele WORK_REFL end $ZONE_TEXT r-values ( bulk ) \n" ;
}

if ( ${$my_main{"MAP_ANISO"}}[0] eq "ON" )
{
#	if ( $MAP_TARGET eq "ML" ) 
#	{ print MACRO "refl aniso ( max_like )\n" ; }
    print MACRO "reflection sele WORK_REFL end $ZONE_TEXT r-values ( aniso )\n" ;
}

if ( $my_main{"DFR_RFREE"}[0] eq "ON" )
{
    print MACRO "    reflection sele TEST end r-values fix\n" ;
}

print MACRO "make map MAP_TARG convert real \n" ;
print MACRO "make map MAP_TARG zero \n" ;

}

sub create_refine_bval_overall
{
print MACRO << "END_OF_TEXT" ;

! Over all B-value Refinement based on Wilson plot differences
 ener dens map MAP_TARG

 mini b-val over \\ 
      sele segm name SEGMENTS end \\ 
      step = $my_main{"BREF_OVER_STEP"}[0] \\
      phase \( sele WORK_REFL .a resol 15. 3.0 end \\
END_OF_TEXT
#      phase \( sele WORK_REFL .a resol 10. RESOL_MAX end \\

    if ( $my_main{"BULK_SOLV_METHOD"}[0] ne "NONE" )
{    print MACRO " 	     partial \\ \n" ; }

    print MACRO << "END_OF_TEXT" ;
            ) 

END_OF_TEXT
}

sub create_refine_xyz
{
if ( $REF_TARGET eq "REAL_SPACE" ) 
{
    &create_re_phase ;
print MACRO << "END_OF_TEXT" ;


< ?MAIN_CMDS_NEW:calc_fofc_map.cmds MAP_TARG 2. 1.  0.

END_OF_TEXT
}
print MACRO << "END_OF_TEXT" ;

mini adjust ( bond = @{$my_main{"PREF_SCAL_XTARG"}}[0] step = 100 )

END_OF_TEXT

if ( $REF_TARGET eq "REAL_SPACE" ) 
{
    my $IX = int( $my_main{"PREF_STEP_MIN"}[0] / 50 ) ;
    if ( $IX < 0 ) { $IX = 10 ; }
print MACRO << "END_OF_TEXT" ;

 mini any position  sele segm name SEGMENTS .a .n background end \\ 
 	 step = $my_main{"PREF_STEP_MIN"}[0] \\ 
 	 writ = $IX

END_OF_TEXT
goto FINISH 
}

if ( $REF_TARGET eq "MAP" ) 
{
    my $IX = int ( $my_main{"PREF_STEP_MIN"}[0] / 50 ) ;
    if ( $IX < 0 ) { $IX = 10 ; }
print MACRO << "END_OF_TEXT" ;

 mini any position  sele segm name SEGMENTS .a .n background end \\ 
 	 step = $my_main{"PREF_STEP_MIN"}[0] \\ 
 	 writ = $IX

END_OF_TEXT
goto FINISH 
}

my $PRECISION = ${$my_main{"PREF_PRECISION"}}[0] ;
print MACRO << "END_OF_TEXT" ;

energy x-targ ( precision $PRECISION )

END_OF_TEXT

print MACRO << "END_OF_TEXT" ;

mini $TICKLE_TEXT $NO_PREP \\
     any position  sele segm name SEGMENTS .a .n background end \\
     step = $my_main{"PREF_STEP_MIN"}[0] \\
END_OF_TEXT

if ( $ADJUST > 0 ) 
{
#    print " adjust in position $ADJUST\n" ;
print MACRO << "END_OF_TEXT" ;
     adjust ( update $ADJUST )  \\
END_OF_TEXT

$NO_PREP = "no_prep" ;
}


print MACRO "     phase \( \\ \n" ;
for ( $CRYST = 1; $CRYST <= $NCRYST ; $CRYST++ )
{
    if ( $NCRYST > 1 ) 
    {
	print MACRO "     crystal $CRYST \\ \n" ;
    }
    if ( $my_main{"DFR_RFREE"}[0] eq "ON" )
    {    
	if ( $REF_TARGET eq "FREE_KICK" ) 
	{
	    print MACRO "             sele WORK_REFL end \\ \n" ; 
	    print MACRO "             free sele WORK_REFL end \\ \n" ; 
	    print MACRO "             test sele TEST end \\ \n" ; 
	}
	else
	{    
	    print MACRO "             sele WORK_REFL end \\ \n" ; 
	    print MACRO "             free sele TEST end \\ \n" ; 
	}
    }
    else
    { 
	    print MACRO "             sele  WORK_REFL end \\ \n" ; 
	if ( $REF_TARGET eq "FREE_KICK" ) 
	{	
	    print MACRO "             free sele WORK_REFL end \\ \n" ; 
	}
    }
}

if ( $my_main{"PREF_WAY"}[0] eq "ACCURATE" )
{    print MACRO "        each_step \\ \n" ; }

if ( $REF_TARGET eq "MAP" )
{    print MACRO "     target \( map ) \\ \n" ; }
elsif ( $REF_TARGET eq "LSQ" )
{    print MACRO "     target \( least_square ) \\ \n" ; }
elsif ( $REF_TARGET eq "CROSS_COR" )
{
    my $N_AVER = $my_main{"PREF_ML_AVER"}[0] ;
    print MACRO "     target \( max_like $N_AVER ) \\ \n" ; 
     if ( $my_main{"DFR_RFREE"}[0] ne "ON" ) 
     { print "CROSS CORRELATION refinement - R-FREE FLAG NOT SET?\n" ; }
}
elsif ( $REF_TARGET eq "FREE_KICK" )
{    
    my $KICK = $my_main{"PREF_ML_KICK"}[0] ;
    my $N_AVER = $my_main{"PREF_ML_AVER"}[0] ;
    print MACRO "     target \( free_kick $KICK $N_AVER ) \\ \n" ; 
}




# mutli crystal phasing
#if ( $NCRYST > 1 ) 
#{    print MACRO " 	     macro = multi_deriv_maps.com \\ \n" ; }

if ( $REF_TARGET eq "REAL_SPACE" ) 
{    
    print MACRO << "END_OF_TEXT" ;
      \) \\
	  writ = 10

END_OF_TEXT
}
else
{
    print MACRO << "END_OF_TEXT" ;
      \) \\
     writ = 1  

END_OF_TEXT
}
FINISH:
}
 
sub create_refine_bval
{


print MACRO << "END_OF_TEXT" ;

 mini adjust ( bval =  @{$my_main{"BREF_SCAL_XTARG"}}[0] step = 20 )
 mini writ 1
!  ener x-targ on \\ 
!      x-targ map MAP_TARG \\
!      x-targ scale = 100

 mini $TICKLE_TEXT $NO_PREP \\
      any ( b-val ) \\ 
      sele segm name SEGMENTS .a weigh 0.001 1.1 end \\ 
      step = $my_main{"BREF_IND_STEP"}[0] \\
END_OF_TEXT

if ( $ADJUST > 0 ) 
{
#    print " adjust in bval $ADJUST\n" ;
print MACRO << "END_OF_TEXT" ;
     adjust ( update $ADJUST )  \\
END_OF_TEXT
}

if ( $my_main{"DFR_RFREE"}[0] eq "ON" )
{    
    if ( $REF_TARGET eq "FREE_KICK" ) 
    {
	print MACRO "     phase \( sele WORK_REFL end \\ \n" ; 
	print MACRO "            free sele WORK_REFL end \\ \n" ; 
	print MACRO "            test sele TEST end \\ \n" ; 
    }
    else
    {    
	print MACRO "     phase \( sele WORK_REFL end \\ \n" ; 
	print MACRO "            free sele TEST end \\ \n" ; 
    }
}
else
{ 
    print MACRO "    phase \( sele defined end \\ \n" ; 
    if ( $REF_TARGET eq "FREE_KICK" ) 
    {	
	print MACRO "            free sele defined end \\ \n" ; 
    }
}

#if ( $my_main{"DFR_RFREE"}[0] eq "ON" )
#{    print MACRO "             free sele TEST end \\ \n" ; }
if ( $my_main{"PREF_WAY"}[0] eq "ACCURATE" )
{    print MACRO "             each_step \\ \n" ; }

    if ( $my_main{"BULK_SOLV_METHOD"}[0] ne "NONE" )
{    print MACRO " 	     partial \\ \n" ; }

if ( $REF_TARGET eq "LSQ" )
{    print MACRO " 	     target ( least_square ) \\ \n" ; }
elsif ( $REF_TARGET eq "CROSS_COR" )
{    my $N_AVER = $my_main{"PREF_ML_AVER"}[0] ;
    print MACRO " 	     target ( max_like $N_AVER ) \\ \n" ; }
elsif ( $REF_TARGET eq "CR_COR_EST" )
{    print MACRO " 	     target ( estim_ml missing @{$my_main{\"PREF_ML_MISSIN\"}}[0] ) \\ \n" ; }
elsif ( $REF_TARGET eq "CR_COR_APR" )
{    print MACRO " 	     target ( aprox_ml ) \\ \n" ; }
elsif ( $REF_TARGET eq "FREE_KICK" )
{    
    my $KICK = $my_main{"PREF_ML_KICK"}[0] ;
    my $N_AVER = $my_main{"PREF_ML_AVER"}[0] ;
    print MACRO " 	     target ( free_kick $KICK $N_AVER ) \\ \n" ; 
}

    print MACRO << "END_OF_TEXT" ;
            ) \\ 
     writ = 1 
END_OF_TEXT

$NO_PREP = "no_prep" ;

}

sub create_refine_occupancy
{
print MACRO << "END_OF_TEXT" ;

 ener x-targ on \\ 
      x-targ map MAP_TARG \\
      x-targ scale = 100

END_OF_TEXT

if ( $REF_TARGET ne "FREE_KICK" ) 
{
print MACRO << "END_OF_TEXT" ;
set vari MAP_PART int = MAP_LAST

make map MAP_PART atom symm -
           atom dens -
           sele segm name SEGMENTS .a weight 1.0 1000 end
END_OF_TEXT
}
print " target $REF_TARGET\n" ;
print MACRO "  mini occupancy \\ \n" ;
print MACRO "       sele segm name SEGMENTS .a weigh 0.001 0.999 end \\ \n" ;
if (  $REF_TARGET eq "FREE_KICK" ) 
{ print MACRO "       sele segm name SEGMENTS end \\ \n" ; }
print MACRO "       step = ", $my_main{"OREF_IND_STEP"}[0], " \\ \n" ;


if ( $my_main{"DFR_RFREE"}[0] eq "ON" )
{    
    if ( $REF_TARGET eq "FREE_KICK" ) 
    {
	print MACRO "     phase \( sele WORK_REFL end \\ \n" ; 
	print MACRO "            free sele WORK_REFL end \\ \n" ; 
	print MACRO "            test sele TEST end \\ \n" ; 
    }
    else
    {    
	print MACRO "     phase \( sele WORK_REFL end \\ \n" ; 
	print MACRO "            free sele TEST end \\ \n" ; 
    }
}
else
{ 
    print MACRO "    phase \( sele defined end \\ \n" ; 
}

    if ( $REF_TARGET ne "FREE_KICK" ) 
{ print MACRO " 	     part_map MAP_PART \\ \n" ; }


if ( $REF_TARGET eq "LSQ" )
{    print MACRO " 	     target ( least_square ) \\ \n" ; }
elsif ( $REF_TARGET eq "FREE_KICK" )
{
    my $KICK = $my_main{"PREF_ML_KICK"}[0] ;
    my $N_AVER = $my_main{"PREF_ML_AVER"}[0] ;
    print MACRO " 	     target \( free_kick $KICK $N_AVER ) \\ \n" ; 
}
elsif ( $REF_TARGET eq "CROSS_COR" )
{    print MACRO " 	     target ( max_like 1 ) \\ \n" ; }
elsif ( $REF_TARGET eq "CR_COS_EST" )
{    print MACRO " 	     target ( estim_ml missing @{$my_main{\"PREF_ML_MISSIN\"}}[0] ) \\ \n" ; }
elsif ( $REF_TARGET eq "CR_COR_APR" )
{    print MACRO " 	     target ( aprox_ml ) \\ \n" ; }


print MACRO << "END_OF_TEXT" ;
            \) \\ 
     writ = 1 
END_OF_TEXT
}


sub create_refmac_refine
{
    print " IN REFMAC REFINE\n" ;

    my $MTZ_FILE = $my_main{"FILE_MTZ"}[0] ;
    my $MTZ_FILE_OUT = $MTZ_FILE ;
    my $CYCLE_REF = $my_main{"PREF_STEP_MIN"}[0] ;
    $MTZ_FILE_OUT =~ s/.mtz// ;
    $MTZ_FILE_OUT = $MTZ_FILE_OUT . "_out.mtz" ;

    open ( MACRO,  "> refine_refmac.sh" ) || die "FILE OPEN ERROR: >$MACRO_FILE< \n" ;
    print MACRO << "END_OF_TEXT" ;
 
refmac5 xyzin model_refmac_in.pdb xyzout model_refmac_out.pdb hklin $MTZ_FILE hklout $MTZ_FILE_OUT \<\< eof
make hydr no
ridge dist sigma 0.02
ncycle $CYCLE_REF
end
eof
END_OF_TEXT

close ( MACRO ) ;

    system "chmod +x refine_refmac.sh" ;

    my $WS = join( " ", @{$my_main{"WAT_SEGM"}} ) ;

    open ( MACRO,  "> $MACRO_FILE" ) || die "FILE OPEN ERROR: >$MACRO_FILE< \n" ;
    print MACRO << "END_OF_TEXT" ;

rena seq "" sele resi name HOH .o segm name $WS end from 1 
rena seq "" sele seq A* B* C* D* E* F* G* W* end delete
write over file model_refmac_in.pdb sele segm name WORK_SEGM end coor pdb standard
shell "./refine_refmac.sh > refine_refmac.log"

 dele atom sele all end
 read file model_refmac_out.pdb coor pdb 
END_OF_TEXT

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" ) 
{
    &create_constrain_composit_inter () ;
}

    print MACRO << "END_OF_TEXT" ;
<>cmds_new/sel_active.cmds WORK
< ?MAIN_UTILS:make_bonds_from_topo.com WORK_SEGM
< ?MAIN_UTILS:fill_atoms.com WORK_SEGM
< re_image.cmds WORK_SEGM 
return
END_OF_TEXT

close(MACRO) ;

exit;

}


sub create_phenix_refine
{
    print " IN PHENIX REFINE\n" ;

    my $MTZ_FILE = $my_main{"FILE_MTZ"}[0] ;
    my $MTZ_FILE_OUT = $MTZ_FILE ;
    my $CYCLE_REF = $my_main{"PREF_STEP_MIN"}[0] ;
    $MTZ_FILE_OUT =~ s/.mtz// ;
    $MTZ_FILE_OUT = $MTZ_FILE_OUT . "_out.mtz" ;

# ligands you need a cif file

    open ( MACRO,  "> refine_phenix.sh" ) || die "FILE OPEN ERROR: >$MACRO_FILE< \n" ;
    print MACRO << "END_OF_TEXT" ;
 
phenix.refine model_phenix_in.pdb $MTZ_FILE 

phenix.refine --show-defaults=all > params.inp

phenix.refine params.inp

END_OF_TEXT

close ( MACRO ) ;

    system "chmod +x refine_phenix.sh" ;

    my $WS = join( " ", @{$my_main{"WAT_SEGM"}} ) ;

    open ( MACRO,  "> $MACRO_FILE" ) || die "FILE OPEN ERROR: >$MACRO_FILE< \n" ;
    print MACRO << "END_OF_TEXT" ;

rena seq "" sele resi name HOH .o segm name $WS end from 1 
rena seq "" sele seq A* B* C* D* E* F* G* W* end delete
write over file model_phenix_in.pdb sele segm name WORK_SEGM end coor pdb ! standard
shell "./refine_phenix.sh > refine_phenix.log"

 dele atom sele all end
 read file model_phenix_in_refine_001.pdb coor pdb 
END_OF_TEXT

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" ) 
{
    &create_constrain_composit_inter () ;
}

    print MACRO << "END_OF_TEXT" ;
<>cmds_new/sel_active.cmds WORK
< ?MAIN_UTILS:make_bonds_from_topo.com WORK_SEGM
< ?MAIN_UTILS:fill_atoms.com WORK_SEGM
< re_image.cmds WORK_SEGM 
return
END_OF_TEXT

close(MACRO) ;

exit;

}
