#!/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{"CENTER_NEXT"} ) ) { push ( @{$my_main{"CENTER_NEXT"}}, "RESIDUE" ) } ; 

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

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

my $keyword ; 
foreach $keyword ( sort keys (%commands) ) 
{
    if ( $keyword eq 'h' || substr($keyword, 0,4) eq "help" ) { goto HELP }
    if ( $keyword eq 'o' || substr($keyword, 0,6) eq "output" ) { goto OUTPUT }
    if ( $keyword eq 'b' || substr($keyword, 0,2) eq "by" ) { goto BY }
    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 
  -o|--output)  set file name of the created macro [$MACRO_FILE]
  -b|--by)      goto the next residue by [RESIDUE/VALIDATE] [@{$my_main{"CENTER_NEXT"}}]
     --doit)    create the macro "$MACRO_FILE"
END_OF_TEXT
    exit;
OUTPUT: $MACRO_FILE = shift ( @{$commands{$keyword}} ) ; next ;

BY: @{$my_main{"CENTER_NEXT"}} = 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 ; }

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

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 $DM_NCYC = $my_main{"DM_NCYC"}[0] ;
if ( $DM_NCYC == 0 ) { $DM_NCYC = 1 ; }

if ( $my_main{"CENTER_NEXT"}[0] eq "RESIDUE" ) 
{
print MACRO << "END_OF_TEXT" ; 

set vari NEXT_RESI int global = NEXT_RESI + 1
image cent calc sele resi numb NEXT_RESI end
image map over
return
END_OF_TEXT
}
else
{
print MACRO << "END_OF_TEXT" ; 
stream unit 66    
image cent calc sele resi numb NEXT_RESI end
image map over
return
END_OF_TEXT
}
close ( MACRO ) ;




