#!/usr/bin/perl

#  Perl script to create CIF files from *.xtl files
#  This version is not clever !!!  It does not worry about symmetry labels and only does O and Si atoms

use strict;
#use warnings;
use File::Basename;

my $infile = shift @ARGV;
my $outfile = shift @ARGV;

my ($name, $path, $suffix) = fileparse($infile, qr{\.xtl});

my $ok =0;
if($suffix =~ m/\.xtl/){
	$ok=0;
}else{
	die "Wrong file type, no XTL extension.\n";
}

# Make piping available
if (defined $infile) {
	open INFILE, $infile or die "Couldn't open file $infile: $!\n";
} else {
	*INFILE = *STDIN;
}
if (defined $outfile) {
	open OUTFILE, "> $outfile" or die "Can't write file $outfile: $!\n";
} else {
	*OUTFILE = *STDOUT;
}

		
	my $_2;
	# Start scanning.
	my (@cell, @atom,  $space, $setting);
	while (defined ($_2 = <INFILE>)){
		if ($_2 =~ m/^CELL/){
			$_2 = <INFILE>;
			$_2 =~ s/^\s+//;
			@cell = split ' ', $_2;
			for (my $A =0; $A<=$#cell; $A++){
				#print "cell[$A] = $cell[$A]\t";
			}
			#print "\n";	
		}
		if ($_2 =~ m/^ATOMS/){
			# Grab extra line
			$_2 = <INFILE>;
			$_2 = <INFILE>;
			my $A=0;
			while ($ok==0){
				chomp $_2;
				my @tmpatom = split ' ', $_2;	
				for (my $B =0; $B<=$#tmpatom; $B++){
					#print "A = $A atom[$B] = $tmpatom[$B]  ";
					$atom[$A][$B] = $tmpatom[$B];
				}
				#print "\n";
				$A++;
				$_2 = <INFILE>;
				if ($_2 =~ m/EOF/){
					$ok=1;
				}
			}
		}
	}
	#Now print CIF file
	print OUTFILE "# This CIF file was created from GASP xtl files\n";
	print OUTFILE "\ndata_$name\n\n";
	print OUTFILE "_cell_length_a           $cell[0]\n";
	print OUTFILE "_cell_length_b           $cell[1]\n";
	print OUTFILE "_cell_length_c           $cell[2]\n";
	print OUTFILE "_cell_angle_alpha        $cell[3]\n";
	print OUTFILE "_cell_angle_beta         $cell[4]\n";
	print OUTFILE "_cell_angle_gamma        $cell[5]\n";
      print OUTFILE "_symmetry_space_group_name_H-M   \'P 1\'\n";

	print OUTFILE "_symmetry_Int_Tables_number 1\n";

	print OUTFILE "\nloop_\n_atom_site_type_symbol\n_atom_site_label\n_atom_site_fract_x\n_atom_site_fract_y\n_atom_site_fract_z\n";

	my $n=1;
	for(my $A=0;$A<=$#atom;$A++){
		#print "A = $A $atom[$A][0] $atom[$A][1] $atom[$A][2] $atom[$A][3] $atom[$A][4]\n"; 
		print OUTFILE "$atom[$A][0] $atom[$A][0]_$n   $atom[$A][1] $atom[$A][2] $atom[$A][3]\n";
		$n++;
	}		


close INFILE;
close OUTFILE;
