#!/usr/bin/perl

if (system("findsym >& /dev/null")!=0) {
    print
	"Cannot find the findsym executable.\n" .
	"Please install it from https://stokes.byu.edu/iso/isotropy.php , name the executable findsym and make sure it is in your path.\n";
    exit;
}

my $mystdin = do { local $/; <STDIN> };
open (my $ih,">","input_${$}.tmp");
print $ih $mystdin;
close($ih);

open(my $fh,">","findsymin_${$}.tmp");
print $fh "title\n";
print $fh $ARGV[0],"\n";
print $fh "1\n";
open(my $ch,"-|","cellcvrt -cc < input_${$}.tmp");
my @convstr=<$ch>;
for (my $i=0; $i<3; $i++) {print $fh $convstr[$i];}
print $fh "1\n";
for (my $i=3; $i<6; $i++) {print $fh $convstr[$i];}
print $fh @convstr-6,"\n";
for (my $i=6; $i<@convstr; $i++) {chomp $convstr[$i]; my @atom=split /\s+/,$convstr[$i]; print $fh $atom[3],"_\n";}
print $fh "\n";
for (my $i=6; $i<@convstr; $i++) {my @atom=split /\s+/,$convstr[$i]; print $fh join(' ',@atom[0..2]),"\n";}
close($fh);
open(my $sh,"-|","findsym < findsymin_${$}.tmp > findsymout_${$}.tmp");
my @symout=<$sh>;
print @symout;
open(my $fo,"-|","getvalue _symmetry_Int_Tables_number < findsymout_${$}.tmp");
my $spcgrp=<$fo>;
chomp $spcgrp;
close($fo);
print $spcgrp . " ";
open(my $fo,"-|","getlines -jbt _atom_site_occupancy '^ *\$' < findsymout_${$}.tmp | awk '{print \$1,\$4}' | sort -k 2 -r");
my $wycks="";
my $labs="";
while (<$fo>) {
    chomp;
    my @col=split /\s+/,$_;
    $col[0] =~ s/_.*$//g;
    $labs=$labs . ":" . $col[0];
    $wycks=$wycks . $col[1];
}
$labs =~ s/^\://g;
print $wycks . " " . $labs;
print "\n";

unlink("input_${$}.tmp");
unlink("findsymin_${$}.tmp");
unlink("findsymout_${$}.tmp");
unlink("findsym.log");
