"""
This module is designed for reading and writing of xyz files.
(C) Kai Sellschopp, TUHH Hamburg, Germany
"""
import os
import numpy as np


def readXYZ(filename):
    """
    """
    # open and read file
    with open(filename) as f:
        xyz_file = f.read()

    # split into lines
    xyz_lines = xyz_file.split('\n')

    # do something to read out information
    return


def writeXYZ(filename, numbers, symbols, coordinates, comments=[]):
    """
    This function takes a list of numbers, symbols, coordinates, and comments
    and creates an xyz file with name 'filename' from them.

    Note: the input variables have to be iterable and of the same length
          (except for comments, which is optional)
    """
    
    # check for same length of input
    if len(numbers)!=len(symbols) or len(numbers)!=len(coordinates):
        print "ERROR! Input must have same length!"
        return
    
    # handle empty comments
    if len(comments)==0 or len(comments)!=len(numbers):
        for i in range(len(numbers)):
            comments.append('')

    # initialize output
    output = []

    # iterate over steps
    for num, com, syms, coords in zip(numbers, comments, symbols, coordinates):

        # put number to output
        output.append('{:d}'.format(num))

        # put comment line to output
        output.append(com)

        # create coordinate lines
        for sym, xyz in zip(syms, coords):
            output.append('{:3s} {:14.8f} {:14.8f} {:14.8f}'.format(sym, xyz[0], xyz[1], xyz[2]))

    # print output to file
    output.append('')
    with open(filename, 'w') as f:
        f.write('\n'.join(output))

    return
