#!/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{"FILE_VEIW"} ) ) { push ( @{$my_main{"FILE_VIEW"}}, "SAVE_FILE.VIEW" ) };


#########################################################
my $MACRO_FILE = "save_file_view.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 's' || substr($keyword, 0,12) eq "view_as_file" ) { goto SAVE_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 
  -s|--view_as_file) root words of files [$VIEW_FILE] 
  -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 ;
 SAVE_FILE: $SAVE_FILE_VIEW = shift ( @{$commands{$keyword}} ) ; next ;
}

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

@{$my_main{"FILE_VIEW"}} = ( $SAVE_FILE_VIEW ) ;

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

$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" ;


$SAVE_FILE_VIEW = ${$my_main{"FILE_VIEW"}}[0] ;


print MACRO << "END_OF_TEXT" ;
subroutine char SAVE_FILE
save over file $SAVE_FILE_VIEW view
return
END_OF_TEXT
    
close ( MACRO ) ;
