#! /bin/sh
#!perl -w # --*- Perl -*--
eval 'exec perl -x $0 ${1+"$@"}'
    if 0;
#------------------------------------------------------------------------------
#$Author: antanas $
#$Date: 2021-04-28 19:35:53 +0300 (Wed, 28 Apr 2021) $
#$Revision: 8738 $
#$URL: svn+ssh://www.crystallography.net/home/coder/svn-repositories/cod-tools/tags/v3.8.0/scripts/ssg3d $
#------------------------------------------------------------------------------
#*
#* Build a three-dimensional space group from (N+1) dimensional
#* superspace group operators.
#*
#* USAGE:
#*   $0 < input.symop
#*   $0 input.symop
#*   $0 input.symop additional*.symop
#**

use strict;
use warnings;
use COD::Spacegroups::Lookup::COD;
use COD::Spacegroups::Lookup qw( make_symop_hash make_symop_key );
use COD::Spacegroups::Symop::Parse qw( string_from_symop );
use COD::Spacegroups::Symop::SSGParse qw( symop_from_string
                                          symop_from_ssg_operator );
use COD::Spacegroups::Builder;
use COD::SOptions qw( getOptions );
use COD::SUsage qw( usage );
use COD::ToolsVersion qw( get_version_string );

#* OPTIONS:
#*   --help, --usage
#*                     Output a short usage message (this message) and exit.
#*   --version
#*                     Output version information and exit.
#**
@ARGV = getOptions(
    '--help,--usage' => sub { usage; exit },
    '--version'      => sub { print get_version_string(), "\n"; exit }
);

my $spacegroup = COD::Spacegroups::Builder->new;

while(<>) {
    next if /^#/;
    next if /^\s*$/;
    chomp;
    my $matrix = symop_from_string( $_ );
    print "# $_ -> ";
    ## print_matrix( $matrix );
    my $symop2d = symop_from_ssg_operator( $matrix );
    print string_from_symop( $symop2d ), "\n";
    ## print_matrix( $symop2d );
    $spacegroup->insert_symop( $symop2d );
}

$spacegroup->print();

my @symops = $spacegroup->all_symops();

my %symop_lookup_table = make_symop_hash( [
    \@COD::Spacegroups::Lookup::COD::table,
    \@COD::Spacegroups::Lookup::COD::extra_settings
] );
my $key = make_symop_key(
    [
      map { string_from_symop($_) } @symops
    ]
);

if( exists $symop_lookup_table{$key} ) {
    my $estimated_sg = $symop_lookup_table{$key};
    use COD::Serialise qw( serialiseRef );
    serialiseRef( $estimated_sg );
} else {
    print "$0: spacegroup could not be identified\n"
}

sub print_matrix
{
    my ($m) = @_;

    print "[\n";
    for (@$m) {
        print "   [ ";
        my $prefix = "";
        for (@$_) {
            printf "%s%2s", $prefix, $_;
            $prefix = ", ";
        }
        print " ]\n";
    }
    print "]\n\n";

    return;
}
