#!/usr/bin/env perl
use strict;
use lib $ENV{ 'MAIN_CONF'}  ;
use main_config ;
my $WORK_MODEL ;

my $MACRO_FILE = "rotate_maps.cmds" ;

if ( @ARGV <= 0 ) { print " create_$MACRO_FILE REQUIRES a segment ID argument \n" ; exit ; } 
else { $WORK_MODEL = join( " ", @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{"DM_DIR_MASK"} ) ) { push ( @{$my_main{"DM_DIR_MASK"}}, "" ) } ; 

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

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 ( $GROUP, $IGR, $SEGM_FROM, $SEGM_TO, $SEGM, $CRYST, $NCRYST) ;
my @LINES = () ;
my $MAP ; my $MAP_ORIG ;
my %segm_cryst = () ;

$NCRYST = $my_main{"SG_NCRYST"}[0] ;
for ( $CRYST = 0; $CRYST < $NCRYST ; $CRYST++ )
{
    $GROUP = join ( '', "SG_CRYST" , $CRYST+1 ) ;
    foreach $SEGM_FROM ( @{$my_main{$GROUP}} )
    {
	$segm_cryst{$SEGM_FROM} = $CRYST ;
    }
}

for ( $IGR = 1; $IGR <= $my_main{"SG_NGROUP"}[0] ; $IGR++ )
{
    $GROUP = join ( '', "SG_GROUP" , $IGR ) ;
#    print " GROUP: $IGR \n" ;
    foreach $SEGM_FROM ( @{$my_main{$GROUP}} )
    {
        if ( $WORK_MODEL eq $SEGM_FROM )
	    {

	    $MAP_ORIG = 2 ;
	    $MAP = $NCRYST * 2 ; if ( $NCRYST == 1 ) { $MAP++; }
	    push ( @LINES, "set vari IMAP = ", $MAP, "\n" ) ;
	    foreach $SEGM_TO ( @{$my_main{$GROUP}} )
	    {
#		print " INN TOO LOOP: $SEGM_TO \n" ;
		if ( $SEGM_FROM ne $SEGM_TO )
		    {
			if ( $NCRYST > 1 ) { $MAP_ORIG = $segm_cryst{$SEGM_TO}*2 + 1; } ;
			
			push ( @LINES, "set vari IMAP = IMAP + 1 \n" ) ;
#			push ( @LINES, "show vari IMAP \n" ) ;
#			push ( @LINES, "set lev 3 \n" ) ;
			
			@LINES = ( @LINES, "read file ", $my_main{"DM_DIR_MASK"}[0], "mask_", $SEGM_FROM, 
			    ".xmap map xpl over IMAP \n" ) ;
			@LINES = ( @LINES, "<mol_", $SEGM_FROM, "_to_", $SEGM_TO, ".com \n") ;
			@LINES = ( @LINES, "make map IMAP from ", $MAP_ORIG, 
			    " rota matr MAT_ROT tran vect XTRAN YTRAN ZTRAN \n" ) ;
			push ( @LINES, "\n" ) ;
			push ( @LINES, "make map IMAP rescale \n" ) ;
			push ( @LINES, "image map IMAP dens 1.0 map_boxx map_boxx map_boxx  \n" ) ;
#			push ( @LINES, "set lev 0 \n" ) ;
			
			@LINES = ( @LINES, "return \n" ) ;
#			print @LINES ;
			print MACRO @LINES ; 
			exit ;
		    }
	    }
}
}
}

	    
	   
