#!perl
#**********************************************************
#*                                                        *
#*     XTD2XYZ - Convert XTD files into XYZ ormat        *
#*                                                        *
#**********************************************************
# Version: 0.1
# Author: Andrea Minoia
# Date: 08/09/2010
#
# Corrected by HUASUAN-YANG on 01-09-2021
# Contact Wechat ID 13005427160 or Nininncole for help
# Convert MS trajectory xtd file into XYZ trajectory file.
#
# Backup of files that are about to be overwritten is managed
# by MS. The most recent file is that with higher index number (N)
# The script has to be in the same directory of the
# structure to modify and the user has to update the
# variable $doc (line 27) according to the name of the
# file containing the trajectory.
# The xmol trajectory is stored in trj.txt file and it is not
# possible to rename the file within MS, nor it is possible to
# automatically export it as xyz or car file. You should manage
# the new trajectory manually for further use (e.g. VMD)

use strict; 
use MaterialsScript qw(:all);

#open the multiframe trajectory structure file or die 
my $doc = $Documents{"./newdoc.xtd"}; 

if (!$doc) {die "no document";}

my $trajectory = $doc->Trajectory;

if ($trajectory->NumFrames>1) {
    # Open new report file
    my $report=Documents->New("xtd2xmol.txt");
    $report->Append("Found ".$trajectory->NumFrames." frames in the trajectory\n");
    $report->Close;
    # Open new xmol trajectory file
    my $xmolFile=Documents->New("trj.txt");
    
    #get atoms in the structure
    my $atoms = $doc->AsymmetricUnit->Atoms; #Corrected
    my $Natoms=@$atoms;

    # loops over the frames 
    for (my $frame=1; $frame<=$trajectory->NumFrames; ++$frame){
        $trajectory->CurrentFrame = $frame;
        #write header xyz
        $xmolFile->Append(sprintf "%i \n\n", $Natoms);
        foreach my $atom (@$atoms) {
            # write atom symbol and x-y-z- coordinates
            $xmolFile->Append(sprintf "%s %f  %f  %f \n",$atom->ElementSymbol, $atom->X, $atom->Y, $atom->Z); 
        }    
    } 
    #close trajectory file
    $xmolFile->Close;

} 
else { 
    print "The " . $doc->Name . " is not a multiframe trajectory file \n"; 
}