#!/usr/bin/perl -w
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 ) ; 

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

my $MACRO_FILE = "restore_file.cmds" ;
my $PROC_ERROR = "FALSE" ;
my $doit = "FALSE" ;
my @DUM = split('\.', ${$my_main{"FILE_MODEL"}}[0] ) ;
#print "dumm: ",  $DUM[0], @{$my_main{"FILE_MODEL"}}, "\n" ;
my $SAVE_FILE_ROOT = $DUM[0] ;
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 'f' || substr($keyword, 0,4) eq "file" ) { goto FILE }
    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 
  -f|--file)    root of files for molecular model [$SAVE_FILE_ROOT] 
  -o|--output)  set file name of the created macro [$MACRO_FILE]
     --doit)    create the macro 
END_OF_TEXT
    exit;
 OUTPUT: $MACRO_FILE = shift ( @{$commands{$keyword}} ) ; next ;
 FILE: $SAVE_FILE_ROOT = 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" ;

print MACRO << "END_OF_TEXT" ;

read file $SAVE_FILE_ROOT + ".PDB" atom xpl over \\
          first sele segm name WORK_SEGM end
read file $SAVE_FILE_ROOT + ".CTAB" ctab \\
          first sele segm name WORK_SEGM end
< $SAVE_FILE_ROOT + ".VIEW" 
< ?MAIN_CMDS:re_image.cmds WORK_SEGM
return
END_OF_TEXT
    
close ( MACRO ) ;
