#!/usr/bin/env perl
use strict;
use lib $ENV{ 'MAIN_CONF'}  ;
use main_config ;
use File::Find ;

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 %new_main = () ;
my %column = () ; 
my @symmetry = () ;
my @words ;
my $record ;
my %column_list ;
my $ICL = 0 ;
my $FILE ;
my $loop_count = 0 ;

my ( $A, $B, $C, $AL, $BE, $GA ) ;
$A = -999 ;

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

if ( !exists( $my_main{"FILE_SFCIF"} ) ) { push ( @{$my_main{"FILE_SFCIF"}}, "sf.cif" )} ;
if ( !exists( $my_main{"REFL_TEST_FRACT"} ) ) { push ( @{$my_main{"REFL_TEST_FRACT"}}, 20 )} ;
my $RAND_FRACT = $my_main{"REFL_TEST_FRACT"}[0] ;

push ( @{$new_main{"CIF_FOBS"}}, "" ) ;
push ( @{$new_main{"CIF_SIGMA"}}, "" ) ;
push ( @{$new_main{"CIF_PHASE"}}, "" ) ;
push ( @{$new_main{"CIF_WEIGHT"}}, "" ) ;
push ( @{$new_main{"CIF_TEST"}}, "" ) ;
push ( @{$new_main{"CIF_IND_H"}}, "" ) ;
push ( @{$new_main{"CIF_IND_K"}}, "" ) ;
push ( @{$new_main{"CIF_IND_L"}}, "" ) ;
push ( @{$new_main{"CIF_FCALC"}}, "" ) ;
push ( @{$new_main{"CIF_FCALC_PHASE"}}, "" ) ;
push ( @{$new_main{"INIT_MAP"}}, "NONE" ) ;
push ( @{$new_main{"CIF_IOBS"}}, "" ) ;
push ( @{$new_main{"CIF_ISIGMA"}}, "" ) ;
my $KEY ;
foreach $KEY ( %my_main )
{
    if ($KEY =~ m"MTZ_" ) { @{$new_main{$KEY}} = @{$my_main{$KEY}} }
}

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

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 'c' || substr($keyword, 0,8) eq "cif_file" ) { goto CIF_FILE }
    if ( $keyword eq 'f' || substr($keyword, 0,4) eq "fobs" ) { goto FOBS }
    if ( $keyword eq 'i' || substr($keyword, 0,4) eq "iobs" ) { goto IOBS }
    if ( $keyword eq 'g' || substr($keyword, 0,6) eq "isigma" ) { goto ISIGMA }
    if ( $keyword eq 'l' || substr($keyword, 0,5) eq "fcalc" ) { goto FCALC }
    if ( $keyword eq 'm' || substr($keyword, 0,8) eq "fc_phase" ) { goto FC_PHASE }
    if ( $keyword eq 'p' || substr($keyword, 0,5) eq "phase" ) { goto PHASE }
    if ( $keyword eq 's' || substr($keyword, 0,5) eq "sigma" ) { goto SIGMA }
    if ( $keyword eq 't' || substr($keyword, 0,4) eq "test" ) { goto TEST }
    if ( $keyword eq 'w' || substr($keyword, 0,6) eq "weight" ) { goto WEIGHT }
    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
                  if SF labels were not defined before the first found 
                  F, Q, P and W records are taken as FOBS, SIGMA, PHASE and WEIGHT
                  A are matched for HLA, HLB, HLC and HLD keywords 
  -c|--cif_file)  SF CIF input file [$my_main{"FILE_SFCIF"}[0]]
  -f|--fobs)      FOBS label in cif file [$new_main{"CIF_FOBS"}[0]]
  -s|--sigma)     SIGMA of FOBS label in cif file [$new_main{"CIF_SIGMA"}[0]]
  -i|--iobs)      IOBS label in cif file [$new_main{"CIF_IOBS"}[0]]
  -g|--isigma)    ISIGMA of IOBS label in cif file [$new_main{"CIF_ISIGMA"}[0]]
  -p|--phase)     PHASE label in cif file [$new_main{"CIF_PHASE"}[0]]
  -l|--fcalc)     FCALC label in cif file [$new_main{"CIF_FCALC"}[0]]
  -m|--fc_phase)  FCALC PHASE label in cif file [$new_main{"CIF_FCALC_PHASE"}[0]]
  -t|--test)      TEST flag label in cif file [$new_main{"CIF_TEST"}[0]]
  -w|--weight)    WEIGHT of PHASE label in cif file [$new_main{"CIF_WEIGHT"}[0]]
     --doit)      save extracted data in "main_config.data" 
                  write cell constants and symmetry operators file
END_OF_TEXT
    exit ;
CIF_FILE: @{$my_main{"FILE_SFCIF"}} = shift ( @{$commands{$keyword}} ) ; next ;
FOBS: @{$new_main{"CIF_FOBS"}} = shift ( @{$commands{$keyword}} ) ; next ;
IOBS: @{$new_main{"CIF_IOBS"}} = shift ( @{$commands{$keyword}} ) ; next ;
FCALC: @{$new_main{"CIF_FCALC"}} = shift ( @{$commands{$keyword}} ) ; next ;
FC_PHASE: @{$new_main{"CIF_FCALC_PHASE"}} = shift ( @{$commands{$keyword}} ) ; next ;
SIGMA: @{$new_main{"CIF_SIGMA"}} = shift ( @{$commands{$keyword}} ) ; next ;
ISIGMA: @{$new_main{"CIF_ISIGMA"}} = shift ( @{$commands{$keyword}} ) ; next ;
PHASE: @{$new_main{"CIF_PHASE"}} = shift ( @{$commands{$keyword}} ) ; next ;
TEST: @{$new_main{"CIF_TEST"}} = shift ( @{$commands{$keyword}} ) ; next ;
WEIGHT: @{$new_main{"CIF_WEIGHT"}} = shift ( @{$commands{$keyword}} ) ; next ;
}

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

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

my $CIF_FILE = $my_main{"FILE_SFCIF"}[0] ;
print "reading sf cif file \"$CIF_FILE\" \n" ;

my @sf_lines = () ;

open ( SFC,  "< $CIF_FILE" ) || die "FILE OPEN ERROR: >$CIF_FILE< \n" ;

my $n_keys = 0;

while ( <SFC>) 
{ $record = $_; 
  chomp $record ; 
  my @aa = split( "", $record ) ;
  while ( $#aa >= 1 && $aa[0] eq " " ) { shift(@aa) ; } 
  if ( $#aa <= 1 ) { next ; }
  $record = join ( "", @aa ) ;
  push( @sf_lines,  $record ) ; 
} close ( SFC ) ;

#my $I ;
#for ($I=0; $I<40; $I++) { print $I, "> ", $sf_lines[$I], "\n" ; }
my $nn = 0; 
my $line_beg = -1 ;
my $line_end = -1 ;
my $IOK = 1 ;
$ICL = 0 ;
%column = () ;
%column_list = () ;
my $line ;
foreach $line ( @sf_lines )
{
#    my @chrs = () ; 
#    @chrs = split ( '', $record ) ;
#    @words = split ( ' ', $record ) ;
    $nn++;
    $record = $line ;


    if( substr($record, 0, 5 ) eq "_cell" )
    {
	
#	print $nn, " ============== record:", $record, "\n" ;
	@words = split ( ' ', $record ) ;
	print scalar(@words), " words:", join(" ", @words), "\n" ;

	if ( $words[0] eq "_cell.length_a" ) { $A = $words[1] ; }
	if ( $words[0] eq "_cell.length_b" ) { $B = $words[1] ; }
	if ( $words[0] eq "_cell.length_c" ) { $C = $words[1] ; }
	if ( $words[0] eq "_cell.angle_alpha" ) { $AL = $words[1] ; }
	if ( $words[0] eq "_cell.angle_beta" ) { $BE = $words[1] ; }
	if ( $words[0] eq "_cell.angle_gamma" ) { $GA = $words[1] ; }
    }

    if( substr($record, 0, 9 ) eq "_symmetry" )
    {
	
#	print $nn, " ============== record:", $record, "\n" ;
	@words = split ( ' ', $record ) ;
	print scalar(@words), " words:", join(" ", @words), "\n" ;
	if ( $words[0] eq "_symmetry.space_group_name_H-M" ) 
	{
	    @words = split ( '\'', $record ) ;
	    my $my_symmetry = $words[1] ;
	    $my_symmetry =~ s/ // ;
	    $my_symmetry =~ tr/ /_/ ;
	    print "words:", join("|", @words), "-=-", $my_symmetry, "\n" ;
	    @{$new_main{"SPACE_GROUP"}} = ( $my_symmetry ) ;
	}
    }

    if( substr($record, 0, 6 ) eq "_refln" )
    {
    $n_keys++;
	
#	print $nn, " ============== record:", $record, "\n" ;
	@words = split ( '\.', $record ) ;
#	print scalar(@words), " words:", @words, "\n" ;

	if ( $words[0] eq "_refln" ) # ||  $words[0] eq "_reflns" ) 
	{
	    $line_beg = $nn ; $IOK = 0 ;
	    $ICL++ ;
	    $column{$words[1]} = $ICL ;
	    $column_list{$words[1]} = $ICL ;
	    print $nn, " column: $ICL name: >$words[1]< \n" ;
#	    my @xx = split("", $words[1] ) ;
#	    if ( $xx[$#xx] eq " " ) { pop(@xx) ; }
#	    my $wrd = join("", @xx ) ;
	    my $wrd = $words[1] ;
				     
	    if ( length( $new_main{"CIF_IND_H"}[0]) <= 0 && lc($wrd)  =~ m"index_h" ) 
	    { @{$new_main{"CIF_IND_H"}} = ( $wrd )} ;
	    if ( length( $new_main{"CIF_IND_K"}[0]) <= 0 && lc($wrd)  =~ m"index_k" ) 
	    { @{$new_main{"CIF_IND_K"}} = ( $wrd )} ;
	    if ( length( $new_main{"CIF_IND_L"}[0]) <= 0 && lc($wrd) =~ m"index_l" ) 
	    { @{$new_main{"CIF_IND_L"}} = ( $wrd )} ;
	    if ( length( $new_main{"CIF_FOBS"}[0]) <= 0 
		 && substr($wrd, 0,6) eq "F_meas" && $wrd !~ m"sigma")
	    { 
		@{$new_main{"CIF_FOBS"}} = ( $wrd ) ; 
		print "fob wrd>", $wrd, "<\n" ;
	    }
	    if ( length( $new_main{"CIF_SIGMA"}[0]) <= 0 
		 && substr($wrd, 0,6) eq "F_meas" && $wrd =~ m"sigma")
	    { @{$new_main{"CIF_SIGMA"}} = ( $wrd ) ; }

# preference for structure factors over intens - by Jaka
	    if ( length( $new_main{"CIF_IOBS"}[0]) <= 0 
		 && substr($wrd, 0,6) eq "intens" && $wrd !~ m"sigma")
	    { @{$new_main{"CIF_IOBS"}} = ( $wrd ) ; }
	    if ( length( $new_main{"CIF_SIGMA"}[0]) <= 0 
		 && substr($wrd, 0,6) eq "intens" && $wrd =~ m"sigma")
	    { @{$new_main{"CIF_ISIGMA"}} = ( $wrd ) ; }

	    if ( length( $new_main{"CIF_FCALC"}[0]) <= 0 
		 && substr($wrd, 0,1) eq "F" && $wrd =~ m"calc")
	    { @{$new_main{"CIF_FCALC"}} = ( $wrd ) ; }

	    if ( length( $new_main{"CIF_FCALC_PHASE"}[0]) <= 0 
		 && substr($wrd, 0,5) eq "phase" && $wrd =~ m"calc")
	    { @{$new_main{"CIF_FCALC_PHASE"}} = ( $wrd ) ; }

	    if ( length( $new_main{"CIF_PHASE"}[0]) <= 0 
		 && substr($wrd, 0,5) eq "phase" && $wrd =~ m"meas")
	    { @{$new_main{"CIF_PHASE"}} = ( $wrd ) ; }
	    
	    if ( length( $new_main{"CIF_TEST"}[0]) <= 0 && lc($wrd) =~ m"test" ) 
	    { @{$new_main{"CIF_TEST"}} = ( $wrd )} ;
	}
    }
    elsif ( substr($record, 0, 4 ) eq "#END" ) 
    {
	print " END: last $nn \n" ;
	$line_end = $nn ;
	last ;
    }
    elsif ( substr($record, 0, 1 ) eq "#" ) 
    {
	$IOK = 1 ;
#	$ICL = 0 ;
#	%column_list = () ;
    }
    elsif ( substr($record, 0, 5 ) eq "loop_" ) 
    {
	print $nn, "   ---- loop --- \n" ;
	$IOK = 1 ;
	$loop_count++ ;
	$ICL = 0 ;
	%column_list = () ;
	$n_keys = 0;
    }
    else
    {
	if ( $IOK == 0 ) { $line_end = $nn } ;
    }
}

foreach $KEY ( sort keys (%new_main) ) 
{
    my $colkey = $new_main{$KEY}[0] ;
    printf " %20s:   @{$new_main{$KEY}} \n", $KEY ;
    if ( exists ($column{$colkey})){ delete $column{$colkey} ; }
}

foreach $KEY ( sort keys (%new_main) ) 
{
    print "$KEY: @{$new_main{$KEY}} \n" ;
    if ( $KEY eq "SPACE_GROUP" )
    {
	@{$my_main{"FILE_SYMM"}} = @{$new_main{"SPACE_GROUP"}} ;
	next ;
    }
    if ( $KEY eq "CIF_IND_H" )
    { @{$my_main{"CIF_IND_H"}} = ( @{$new_main{"CIF_IND_H"}} ) ; 	next ; }
    if ( $KEY eq "CIF_IND_K" )
    { @{$my_main{"CIF_IND_K"}} = ( @{$new_main{"CIF_IND_K"}} ) ; 	next ; }
    if ( $KEY eq "CIF_IND_L" )
    { @{$my_main{"CIF_IND_L"}} = ( @{$new_main{"CIF_IND_L"}} ) ; 	next ; }

    if ( $KEY eq "CIF_FOBS" )
    { @{$my_main{"CIF_FOBS"}} = ( @{$new_main{"CIF_FOBS"}} ) ; 	next ; }
    if ( $KEY eq "CIF_SIGMA" )
    { @{$my_main{"CIF_SIGMA"}} = ( @{$new_main{"CIF_SIGMA"}} ) ; next ; }
    if ( $KEY eq "CIF_PHASE" )
    { 
	@{$my_main{"CIF_PHASE"}} = ( @{$new_main{"CIF_PHASE"}} ) ; 
	@{$my_main{"INIT_MAP"}} = ( @{$new_main{"INIT_MAP"}} ) ; 
	next ; 
    }

    if ( $KEY eq "CIF_IOBS" )
    { @{$my_main{"CIF_IOBS"}} = ( @{$new_main{"CIF_IOBS"}} ) ; 	next ; }
    if ( $KEY eq "CIF_ISIGMA" )
    { @{$my_main{"CIF_ISIGMA"}} = ( @{$new_main{"CIF_ISIGMA"}} ) ; next ; }

    if ( $KEY eq "CIF_FCALC" )
    { @{$my_main{"CIF_FCALC"}} = ( @{$new_main{"CIF_FCALC"}} ) ; 	next ; }

    if ( $KEY eq "CIF_FCALC_PHASE" )
    { @{$my_main{"CIF_FCALC_PHASE"}} = ( @{$new_main{"CIF_FCALC_PHASE"}} ) ; 	next ; }

    if ( $KEY eq "CIF_WEIGHT" )
    { @{$my_main{"CIF_WEIGHT"}} = ( @{$new_main{"CIF_WEIGHT"}} ) ; next ; }
    if ( $KEY eq "CIF_HLA" )
    { @{$my_main{"CIF_HLA"}} = ( @{$new_main{"CIF_HLA"}} ) ; next ; }
    if ( $KEY eq "CIF_HLB" )
    { @{$my_main{"CIF_HLB"}} = ( @{$new_main{"CIF_HLB"}} ) ; next ; }
    if ( $KEY eq "CIF_HLC" )
    { @{$my_main{"CIF_HLC"}} = ( @{$new_main{"CIF_HLC"}} ) ; next ; }
    if ( $KEY eq "CIF_HLD" )
    { @{$my_main{"CIF_HLD"}} = ( @{$new_main{"CIF_HLD"}} ) ; next ; }
    if ( $KEY eq "CIF_TEST" )
    { @{$my_main{"CIF_TEST"}} = ( @{$new_main{"CIF_TEST"}} ) ; next ; }
    if ( $KEY eq "RESOLUTION" )
    { 
	@{$my_main{"DFR_RES_MIN"}} = ( $new_main{"RESOLUTION"}[0] ) ;
	@{$my_main{"DFR_RES_MAX"}} = ( $new_main{"RESOLUTION"}[1] ) ;
	next ; 
    }
}

foreach $KEY ( sort keys (%column) )
{
    printf "UNUSED COLUMNS: %20s  ---> %4d\n", $KEY, $column{$KEY} ;
}

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

$conf_file = "main_config.data" ; 
main_config::write_main_config_file ( $conf_file, %my_main ) ; 

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

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

# print " DOOOOOOOOOOOOOOOOOOOOOOOOOOO IIIIIIIIITTTT\n" ;
if ( $A < 0.1 )
{
    $FILE = $my_main{"FILE_CELL"}[0] ;
    open ( TXT,  "< $FILE" ) || print "UNIT CELL FILE OPEN ERROR: >$FILE< \n" ;
    while ( <TXT> ) 
    {
	$record = $_ ; 
	print $record ;
    }
    chomp ( $record) ;
    close ( TXT ) ;
    @words = split(" ", $record) ;
#    print " cell record: $record \n" ;
    $A = $words[0] ;
    $B = $words[1] ;
    $C = $words[2] ;
    $AL = $words[3] ;
    $BE = $words[4] ;
    $GA = $words[5] ;
}
else
{
    $FILE = $my_main{"FILE_CELL"}[0] ;
    open ( TXT,  "> $FILE" ) || print "UNIT CELL FILE OPEN ERROR: >$FILE< \n" ;
    print TXT join (" ", ($A, $B, $C, $AL, $BE, $GA )), "\n" ;
    close ( TXT ) ;
}

my $fobs ;
$AL = $AL / 180. * 3.1415 ;
$BE = $BE / 180. * 3.1415 ;
$GA = $GA / 180. * 3.1415 ;
# print " cell: $A, $B, $C, $AL $BE $GA \n" ;
my $COAL = cos ( $AL ) ;
my $COBE = cos ( $BE ) ;
my $COGA = cos ( $GA ) ;
my $SIAL=sqrt(1. - $COAL*$COAL ) ;
my $SIBE=sqrt(1. - $COBE*$COBE ) ;
my $SIGA=sqrt(1. - $COGA*$COGA ) ;
my $VOL=$A*$B*$C*sqrt(1.-$COAL**2-$COBE**2-$COGA**2+2.*$COAL*$COBE*$COGA) ;

my $COALST=($COBE*$COGA-$COAL) / ($SIBE*$SIGA) ;
my $SIALST=sqrt(1. - $COALST*$COALST ) ;
my @tr ;

$tr[0] = 1 ;
$tr[1] = $COGA ;
$tr[2] = $COBE ;
$tr[3] = 0. ;
$tr[4] = $SIGA ;
$tr[5] = - $SIBE * $COALST ;
$tr[6] = 0. ;
$tr[7] = 0. ;
$tr[8] = $SIBE * $SIALST ;

my @aort ;
my @bort ;
my @cort ;
my @arep ;
my @brep ;
my @crep ;
# make the real space cell vectors
$aort[0] = $A*$tr[0] ; $aort[1] = $A*$tr[3] ; $aort[2] = $A*$tr[6] ; 
$bort[0] = $B*$tr[1] ; $bort[1] = $B*$tr[4] ; $bort[2] = $B*$tr[7] ;
$cort[0] = $C*$tr[2] ; $cort[1] = $C*$tr[5] ; $cort[2] = $C*$tr[8] ;

# print "AORT: ", @aort, "\n" ;
# print "BORT: ", @bort, "\n" ;
# print "CORT: ", @cort, "\n" ;
$VOL = 1.0 / $VOL ;
# make the reciprocal cell vectors
@crep = main_config::vec_prod( @aort, @bort ) ; @crep = main_config::sc_prod ( @crep,  $VOL ) ;
@arep = main_config::vec_prod( @bort, @cort ) ; @arep = main_config::sc_prod ( @arep,  $VOL ) ;
@brep = main_config::vec_prod( @cort, @aort ) ; @brep = main_config::sc_prod ( @brep,  $VOL ) ;

# $line= join ( " x ", @arep ) ; 
# print "AREP: ",  $line, "\n" ;
# $line= join ( " x ", @brep ) ;
# print "BREP: ",  $line, "\n" ;
# $line= join ( " x ", @crep ) ;
# print "CREP: ", $line, "\n" ;
my $rmin = -99999.0 ;
my $rmax = 99999.0 ;
my $rh_min = 99999 ;
my $rk_min = 99999 ;
my $rl_min = 99999 ;

my $ii = $line_beg ;
my $data_val ; my $data_list ; my $data_form ;
my $data_lab ; my $chrs ;
my $ICL2 ; my $sig ;
my $NO = 0; my $NAN=0 ;
my ( $rh, $rk, $rl, $dh2 ) ;


$FILE = $my_main{"FILE_REFL"}[0] ;
print " open file: $FILE\n" ;
open ( TXT,  "> $FILE" ) || print "FILE OPEN ERROR: >$FILE< \n" ;

my @str_fact_lines = () ;
my @x ;
my $lin ;
@x = split ( ' ', $sf_lines[$ii] ) ;
if ( $#x < $n_keys-1 ) 
{ 
    while ( $ii < $line_end )
    {
	my $lin = join ( " ", $sf_lines[$ii],  $sf_lines[$ii++] ) ;
	push ( @str_fact_lines, $lin ) ;
	$ii++ ; $ii++ ;
    }
}

while ( $ii <= $line_end )
{
    push ( @str_fact_lines, $sf_lines[$ii] ) ;
    $ii++ ;
}
#print 'xx:', $#x, ' keys:', $n_keys, " II", $ii, "\n" ;
my $my_fobs = 0 ;
my $n_extracted = 0 ;
foreach $lin ( @str_fact_lines )
{
    my @out_form = () ;
    push( @out_form, "IND" ) ;
    if ( length($lin) <= 0 ) { next } ;
    @x = split ( ' ', $lin ) ;
    if (  substr($x[0], 0, 4 ) eq "#END" ) { last } ;
#    print $ii, " ", $nn , ">", $lin, "<>", $x[0],  "<\n" ;
#    if ( $x[0] != m"[0-9]" ) { next } ;

#    $chrs = sprintf ( "%4d %4d %4d", $x[$column_list{"index_h"}], 
#		      $x[$column_list{"index_k"}], $x[$column_list{"index_l"}] ) ; 
#    push( @out_form, $chrs ) ;

    if ( length( $new_main{"CIF_IND_H"}[0]) >= 0 ) 
    {
	$data_lab = $my_main{"CIF_IND_H"}[0] ;
#	print ' ind h:', $data_lab, "\n" ;
	if ( exists ($column_list{$data_lab}) )
	     {
		 $ICL2 = $column_list{$data_lab} ;
#		 print $ICL2, " column list\n" ;
		 $data_val = $x[ $ICL2 - 1 ] ;
#		 print $data_val, " data val \n" ;
		 $chrs = sprintf ( "%4d", $data_val) ;
		 push( @out_form, $chrs ) ; 
		 $rh = $data_val ;
	     }
	else { $NO++; print "NO ind H \n" ; next ; }
    }

    if ( length( $new_main{"CIF_IND_K"}[0]) >= 0 ) 
    {
	$data_lab = $my_main{"CIF_IND_K"}[0] ;
#	print ' ind h:', $data_lab, "\n" ;
	if ( exists ($column_list{$data_lab}) )
	     {
		 $ICL2 = $column_list{$data_lab} ; 
		 $data_val = $x[ $ICL2 - 1 ] ;
		 $chrs = sprintf ( "%4d", $data_val) ;
		 push( @out_form, $chrs ) ; 
		 $rk = $data_val ;

	     }
	else { $NO++; print "NO ind K \n" ; next ; }
    }
    if ( length( $new_main{"CIF_IND_L"}[0]) >= 0 ) 
    {
	$data_lab = $my_main{"CIF_IND_L"}[0] ;
#	print ' ind h:', $data_lab, "\n" ;
	if ( exists ($column_list{$data_lab}) )
	     {
		 $ICL2 = $column_list{$data_lab} ; 
		 $data_val = $x[ $ICL2 - 1 ] ;
		 $chrs = sprintf ( "%4d", $data_val) ;
		 push( @out_form, $chrs ) ; 
		 $rl = $data_val ;

	     }
	else { $NO++; print "NO ind L \n" ; next ; }
    }
    my @t = () ;

#    print 'a=', @arep, '\n b=', @brep, '\n c=', @crep, "\n" ;
#    print $rh, $rk, $rl,  " indices\n" ;
    $t[0] = $arep[0] * $rh + $brep[0] * $rk + $crep[0] * $rl ;
    $t[1] = $arep[1] * $rh + $brep[1] * $rk + $crep[1] * $rl ;
    $t[2] = $arep[2] * $rh + $brep[2] * $rk + $crep[2] * $rl ;
    $dh2 = sqrt ( $t[0]*$t[0] + $t[1]*$t[1] + $t[2]*$t[2]  ) ;
    $dh2 = 1.0 / $dh2 ;

    if ( $dh2 < $rmax ) { $rmax = $dh2 } ;
    if ( $dh2 > $rmin ) { $rmin = $dh2 } ;
    if ( $rh < $rh_min ) { $rh_min = $rh } ;
    if ( $rk < $rk_min ) { $rk_min = $rk } ;
    if ( $rl < $rl_min ) { $rl_min = $rl } ;

    $my_fobs = 0 ;
    if ( length( $new_main{"CIF_FOBS"}[0]) > 0 ) 
    {
	$data_lab = $my_main{"CIF_FOBS"}[0] ;
#	print ' fob:>', $data_lab, "<\n" ;
	if ( exists ($column_list{$data_lab}) )
	{
	    $ICL2 = $column_list{$data_lab} ; 
	    $data_val = $x[ $ICL2 - 1 ] ;
#		 if ( defined ( $data_val ) ) { next ; }
#		 print $ii, " line:", $lin, "\n" ;
	    if ( $data_val =~ '\?' ) 
	    { 
#		     print " FOBS DATA VAL::  $data_val \n" ; 
		$NAN++ ; 
		next ; 
	    }
	    if ( $data_val < 999999 && $data_val >= 0.01 ) 
	    {  
		
		$chrs = sprintf ( "FOB %9.2f", $data_val) ;
		push( @out_form, $chrs ) ; 
		$my_fobs = $data_val ;
	    }
	    else
	    { $NAN++ ; next ; }
	}
    }
    elsif ( length( $new_main{"CIF_IOBS"}[0]) >= 0 ) 
    {
	$data_lab = $my_main{"CIF_IOBS"}[0] ;
#	print $ii, ' iobs lag:', $data_lab, "\n" ;
	if ( exists ($column_list{$data_lab}) )
	{
	    $ICL2 = $column_list{$data_lab} ; 
	    $data_val = $x[ $ICL2 - 1 ] ;
#	    print $ii, ' iobs lag:', $data_lab, $ICL2, $data_val, "\n" ;
#		 if ( defined ( $data_val ) ) { next ; }
#	    print $ii, " line:", $lin, "\n" ;
	    if ( $data_val =~ '\?' ) 
	    { 
#		     print " FOBS DATA VAL::  $data_val \n" ; 
		$NAN++ ; 
		next ; 
	    }
	    if ( $data_val < 99999999 && $data_val >= 0.01 ) 
	    {  
		$data_val = sqrt ( $data_val ) ;
		$my_fobs = $data_val ;
		$chrs = sprintf ( "FOB %9.2f", $data_val) ;
		push( @out_form, $chrs ) ; 
	    }
	    else
	    { $NAN++ ; next ; }

	}
    }
    else
    {
	$NO++; if ( $NO < 10 ) { print "NO fob \n" ; } next ; 
    }

    if ( length( $new_main{"CIF_SIGMA"}[0]) > 0 ) 
    {
	$data_lab = $my_main{"CIF_SIGMA"}[0] ;
#	print ' sigm:', $data_lab, "\n" ;
	if ( exists ($column_list{$data_lab}) )
	     {
		 $ICL2 = $column_list{$data_lab} ; 
		 $data_val = $x[ $ICL2 - 1 ] ;
		 if ( $data_val =~ '\?' ) 
		 { 
		     { $NAN++ ; next ; }
		 }
		 else
		 {
		 $chrs = sprintf ( "SIG %7.2f", $data_val) ;
		 push( @out_form, $chrs ) ; 
		 }
	     }
#	else { $NO++; print "NO sig \n" ; next ; }
    } 
    elsif ( length( $new_main{"CIF_ISIGMA"}[0]) >= 0 ) 
    {
	$data_lab = $my_main{"CIF_ISIGMA"}[0] ;
#	print ' sigm:', $data_lab, "\n" ;
	if ( exists ($column_list{$data_lab}) )
	     {
		 $ICL2 = $column_list{$data_lab} ; 
		 $data_val = $x[ $ICL2 - 1 ] ;
		 if ( $data_val =~ '\?' ) 
		 { 
		     $NAN++ ;
		     next ; 
		 }
		 else
		 {
		     if ( $my_fobs > 0 )
		     {
		     $data_val = $data_val*0.5/$my_fobs ;
		     $chrs = sprintf ( "SIG %7.2f", $data_val) ;
		     push( @out_form, $chrs ) ; 
		     }
		     else 
		     { $NAN++ ; next ; }
		     
		 }
	     }
    } 
#	else { $NO++; if ( $NO < 10 ) { print "NO sig \n" ; } next ; }

    if ( length( $new_main{"CIF_FCALC"}[0]) > 0 &&  length( $new_main{"CIF_FCALC_PHASE"}[0]) > 0) 
    {
	$data_lab = $my_main{"CIF_FCALC"}[0] ;
#	print ' fcalc:', $data_lab,  length( $new_main{"CIF_FCALC"}[0]), " phase:", length( $new_main{"CIF_FCALC_PHASE"}[0]), "\n" ;
	if ( exists ($column_list{$data_lab}) )
	     {
		 $ICL2 = $column_list{$data_lab} ; 
		 $data_val = $x[ $ICL2 - 1 ] ;
		 if ( $data_val =~ '\?' ) { next ; }
		 $chrs = sprintf ( "POLAR %9.2f", $data_val) ;
		 push( @out_form, $chrs ) ; 
	     }

	$data_lab = $my_main{"CIF_FCALC_PHASE"}[0] ;
#	print ' sigm:', $data_lab, "\n" ;
	if ( exists ($column_list{$data_lab}) )
	     {
		 $ICL2 = $column_list{$data_lab} ; 
		 $data_val = $x[ $ICL2 - 1 ] ;
		 if ( $data_val =~ '\?' ) { next ; }
		 $chrs = sprintf ( "%8.1f", $data_val) ;
		 push( @out_form, $chrs ) ; 
	     }


#	else { $NO++; print "NO sig \n" ; next ; }
    } 
    elsif ( length( $new_main{"CIF_FCALC"}[0]) > 0 )
    {
	$data_lab = $my_main{"CIF_FCALC"}[0] ;
	if ( exists ($column_list{$data_lab}) )
	     {
		 $ICL2 = $column_list{$data_lab} ; 
		 $data_val = $x[ $ICL2 - 1 ] ;
		 if ( $data_val =~ '\?' ) { next ; }
		 $chrs = sprintf ( "FCALC %9.2f", $data_val) ;
		 push( @out_form, $chrs ) ; 
	     }
    }

    if ( length( $new_main{"CIF_PHASE"}[0]) > 0 )
    {
	$data_lab = $my_main{"CIF_PHASE"}[0] ;
	if ( exists ($column_list{$data_lab}) )
	     {
		 $ICL2 = $column_list{$data_lab} ; 
		 $data_val = $x[ $ICL2 - 1 ] ;
		 if ( $data_val =~ '\?' ) { next ; }
		 $chrs = sprintf ( "PHASE %9.2f", $data_val) ;
		 push( @out_form, $chrs ) ; 
	     }
    }

    if ( length( $new_main{"CIF_TEST"}[0]) >= 0 ) 
    {
	$data_lab = $my_main{"CIF_TEST"}[0] ;
	if ( exists ($column_list{$data_lab}) )
	{
	    $ICL2 = $column_list{$data_lab}[0] ; 
	    $data_val = $x[ $ICL2 - 1 ] ;
	    if ( $data_val == 19 ) { $data_val=1; } else {$data_val=0; }
	}
	else
	{
	    $data_val = int (rand $RAND_FRACT) ;
	    if ( $data_val != 1 ) { $data_val = 0 ; }
	}
	$chrs = sprintf ( "TEST %d", $data_val) ;
	push( @out_form, $chrs ) ; 
    }
    else
    {
	$data_val = int (rand $RAND_FRACT) ;
	if ( $data_val != 1 ) { $data_val = 0 ; }
	$chrs = sprintf ( "TEST %d", $data_val) ;
	push( @out_form, $chrs ) ; 
    }


    $n_extracted++;

    $data_form = join( " ", @out_form, "\n" ) ;
#    print "MY DATA FORM> ", $data_form ;
    print TXT $data_form ; 

}

$my_main{"DFR_RES_MIN"}[0] = int(100*$rmin) / 100. ;
$my_main{"DFR_RES_MAX"}[0] = int(100*$rmax) / 100. ;
print " use_cif.pl> done: HKL limits $rh_min, $rk_min, $rk_min :: resolution range ", $my_main{"DFR_RES_MIN"}[0], " - ", $my_main{"DFR_RES_MAX"}[0], "\n" ;
printf ( " use_cif.pl> NN processed: $nn NN extracted $n_extracted NN failed: $NO undefined (not extracted) : $NAN \n" ) ;

@{$my_main{"DFR_LIMIT_H"}} = ($rh_min) ;
@{$my_main{"DFR_LIMIT_K"}} = ($rk_min) ;
@{$my_main{"DFR_LIMIT_L"}} = ($rl_min) ;

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

$conf_file = "main_config.data" ; 
main_config::write_main_config_file ( $conf_file, %my_main ) ; 

exit ;


