#!/usr/bin/env python
# coding: utf-8

# In[1]:


import glob
import math

# In[7]:


def xyz2mactempas(structure):
    lines = []
    file_read = open(structure, 'r')
    lines = file_read.readlines()

    structure = structure.split('.')[0]
    #structure = structure[-3:]
    #print(structure)
    #end
    

    file_write = open(f'{structure}.at', 'w')

    count = 0
    for line in lines:
        count += 1
        #print(f'line {count}: {line}')
        if count == 1:
            n_atoms = int(line)
            print(f'Number of atoms = {n_atoms}')
            #file_write.write(f'Number of atoms = {n_atoms}\n')
        elif count == 2:
            [x_lim, y_lim, z_lim] = [float(line.split()[0]), float(line.split()[1]), float(line.split()[2])]
            #print(f'Cell size = {x_lim}, {y_lim}, {z_lim}')
            #file_write.write(f'Cell size = {x_lim}, {y_lim}, {z_lim}\n')
            file_write.write(f'MacTempas Structure File\n')
            file_write.write(f'1\n')
            file_write.write(f'{math.ceil(x_lim + 10):.6f} {math.ceil(y_lim + 10):.6f} {math.ceil(z_lim + 10):.6f} 90.000000 90.000000 90.000000\n')
            #file_write.write(f'{x_lim + 10:.6f} {y_lim + 10:.6f} {z_lim + 10:.6f} 90.000000 90.000000 90.000000\n')
            file_write.write(f'1.969231\n')
            file_write.write(f'0 0 1\n')
            file_write.write(f'1 {math.ceil(z_lim + 10)} 0 0 0\n')
            file_write.write(f'{n_atoms} 1\n')
        else:
            [x_coord, y_coord, z_coord] = [float(line.split()[1]), float(line.split()[2]), float(line.split()[3])]
            #print(f'{x_coord} \t {y_coord} \t {z_coord}')
            file_write.write(f'1 C {x_coord/x_lim:.6f} {y_coord/y_lim:.6f} {z_coord/z_lim:.6f} 0.500000 1.000000\n')
            #file_write.write(f'1 C {x_coord:.6f} {y_coord:.6f} {z_coord:.6f} 0.500000 1.000000\n')
    #This is the footer of the MacTempas file            
    file_write.write(f'ARM120 0.6000 28.00 2.0000 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.0000 0.010000 0 0.00 0.010000\n')
    file_write.write(f'120.000000\n')
    file_write.write(f'0.000000 0.000000\n')
    file_write.write(f'{math.ceil(z_lim+10)}\n')
    file_write.write(f'NO\n')
    file_write.write(f'-600.000000,-500.000000,100.000000\n')
    file_write.write(f'1.500000 0.000000\n')
    file_write.write(f' 0.000000 0.000000 0.000000 0.000000\n')
    file_write.write(f'+x,+y,+z\n')
    file_write.write(f'1\n')
    file_write.write(f'0.000000 0.000000 0.000000\n')
    file_write.write(f'1\n')
    file_write.write(f'0 0.500000 0.500000 0.500000 0.500000 0.500000 0.500000 0.500000 0.500000 0.500000 0 4.000000 4.000000 4.000000\n')
    file_write.write(f'8.000000\n')
    #file_write.write(f'\n')        
    file_read.close()
    file_write.close()

# In[8]:


files = glob.glob('*.xyz')
for file in files:
    xyz2mactempas(file)


# In[ ]:




