#!/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 @SPACE_GROUP = () ;
my @words ;
my $ICL = 0 ;
my $FILE ;

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

if ( !exists( $my_main{"FILE_MAIN"} ) ) { push ( @{$my_main{"FILE_MAIN"}}, "diffract.dat" )} ;
if ( !exists( $my_main{"REFL_TEST_FRACT"} ) ) { push ( @{$my_main{"REFL_TEST_FRACT"}}, 20 )} ;

my $KEY ;
foreach $KEY ( %my_main )
{
    if ($KEY =~ m"MTZ_" ) { @{$my_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 'f' || substr($keyword, 0,4) eq "file" ) { goto FILE }
    if ( $keyword eq 't' || substr($keyword, 0,4) eq "test" ) { goto TEST }
    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)    input file [$my_main{"FILE_REFL"}[0]]
  -t|--test)    TEST flag label fraction from the sca file [$my_main{"REFL_TEST_FRACT"}[0]]
     --doit)    save extracted data in "main_config.data" 
                write cell constants and symmetry operators file
END_OF_TEXT
    exit ;
FILE: @{$my_main{"FILE_MAIN"}} = shift ( @{$commands{$keyword}} ) ; next ;
TEST: @{$my_main{"REFL_TEST_FRACT"}} = shift ( @{$commands{$keyword}} ) ; next ;
}

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

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


#
# cell constants and space group line
#

my $INPUT_FILE = $my_main{"FILE_CELL"}[0] ;
open ( SCAPCK,  "< $INPUT_FILE" ) || die "FILE OPEN ERROR: >$INPUT_FILE< \n" ;
my @whole_file = () ;
@whole_file = ( <SCAPCK> ) ;
my $line = $whole_file[0] ;
chomp ($line) ;
@words = split(" ", $line) ;
$KEY =  "CELL_DATA" ;
$FILE = $my_main{"FILE_CELL"}[0] ;

my $A = $words[0] ;
my $B = $words[1] ;
my $C = $words[2] ;
my $AL = $words[3] ;
my $BE = $words[4] ;
my $GA = $words[5] ;

print " cell: $A $B $C $AL $BE $GA \n" ;
######################################

$INPUT_FILE = $my_main{"FILE_REFL"}[0] ;
print "reading diffraction file \"$INPUT_FILE\" \n" ;

open ( SCAPCK,  "< $INPUT_FILE" ) || die "FILE OPEN ERROR: >$INPUT_FILE< \n" ;
# binmode(SCAPCK); 


# $x = length($record); printf ( "$x \n");

@whole_file = () ;
@whole_file = ( <SCAPCK> ) ;
my $nc ;

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


# print " DOOOOOOOOOOOOOOOOOOOOOOOOOOO IIIIIIIIITTTT\n" ;

# cell data


my $RAND_FRACT = $my_main{"REFL_TEST_FRACT"}[0] ;

$KEY =  "CELL_DATA" ;
$FILE = $my_main{"FILE_REFL"}[0] ;
print "processing diffraction data \"$FILE\"\n" ;
#open ( TXT,  "> $FILE" ) || print "FILE OPEN ERROR: >$FILE< \n" ;
my $TEST ;
my $fobs ;
$AL = $AL / 180. * 3.1415 ;
$BE = $BE / 180. * 3.1415 ;
$GA = $GA / 180. * 3.1415 ;
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 = -999999.0 ;
my $rmax = 999999.0 ;
my $II ;
$II = 0 ;
while ( $II < scalar ( @whole_file ) )
{
    $line = $whole_file[$II] ;  chomp ( $line ) ;

    if ( uc(substr($line, 0,3)) ne "IND" ) { $II++ ; print "no ind line: $II> $line \n" ; next ; }
    @words = split ( " ", $line ) ;
    $TEST = int (rand $RAND_FRACT) ;
    if ( $TEST != 1 ) { $TEST = 0 ; }

    my ( $rh, $rk, $rl, $dh2 ) ;
    $rh = $words[1] ;
    $rk = $words[2] ;
    $rl = $words[3] ;
    my @t = () ;
#    print "INDX> $rh $rk $rl \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 } ;
##    print $II, '>', $line , " res:", 1./$dh2, "\n" ;
#
#    $fobs = $words[3] ; if ($fobs < 0. ) { $fobs = 0.0 ; } $fobs = sqrt($fobs);
##    printf "IND %5d %5d %5d FOBS %11.3f SIG %8.3f TEST %3d res: %8.3f\n", 
##    $rh, $rk, $rl, $fobs, $words[4]*0.5, $TEST, 1./$dh2 ;
#    printf TXT "IND %4d %4d %4d FOBS %10.3f SIG %8.3f TEST %2d\n", 
#    $rh, $rk, $rl, $fobs, $words[4]*0.5, $TEST ;
    $II++;
}
#close ( TXT ) ;
$my_main{"DFR_RES_MIN"}[0] = int(100*$rmin) / 100. ;
$my_main{"DFR_RES_MAX"}[0] = int(100*$rmax) / 100. ;

print "resolution range: <", $my_main{"DFR_RES_MIN"}[0], " ", $my_main{"DFR_RES_MAX"}[0], ">\n" ;
######################################
if ( $doit eq "FALSE" )  { exit ; }

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


exit ;

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




# sub find_space_group
# {
#     my $found = "NO" ;
# 
#     if ( $File::Find::name =~ m"symm" ) 
#     { 
# 	my $XX = $File::Find::name ; # $XX =~ s/_//g ;
# #	    print "file: $XX and $out \n" ; 
# 	if ( $XX =~ m"$out" ) 
# 	{
# 	    $found = "YES" ;
# 	    my @Y = split ('/', $File::Find::name ) ;
# 	    my $GROUP = $Y[scalar(@Y)-1] ;
# 	    substr( $GROUP, -5 ) = '' ;
# #	    print "comparison: $out $GROUP $File::Find::name \n" ;
# 	    if ( $GROUP eq $out )
# 	    {
# #		print "SUCESS: $out $GROUP $File::Find::name \n" ;
# 		@{$my_main{"SPACE_GROUP"}} = ( $GROUP ) ;
# 	    }
# 	}
#     }
#     if ( $found eq "NO" ) 
#     { 
# #	print "%WARNING: the space group $out not found in MAIN_SYMM\n\n" ;
# 	@{$my_main{"SPACE_GROUP"}} = ( $out ) ; 
#     }
# }
# 
# 
