#!/usr/bin/env python
import math, os, sys
import numpy as np

def load_hessian(file):
    result = []
    with open(file, "r") as input_file:
        for line in input_file:
            result.extend(line.replace('/n','').split())
    return result

def calculate_dimention(matrix_len):
    determinant = math.sqrt(1 + 2 * 4 * matrix_len)
    return int((determinant - 1)/2)

def make_new_hessian(matrix):
    matrix_dimension = calculate_dimention(len(matrix))
    iterable = iter(matrix)
    result = np.zeros((matrix_dimension, matrix_dimension))
    for i in range(matrix_dimension):
        for j in range(i, matrix_dimension):
            value = next(iterable)
            result[i, j] = float(value)
            result[j, i] = result[i, j]

    return result

def save_hessian(file, matrix):
    if os.path.isfile(file):
        os.remove(file)
    with open(file, "w") as write_file:
        accum = 0
        line = ""
        for i in range(matrix.shape[0]):
            for j in range(matrix.shape[1]):
                if accum < 5:
                    line = line + "{:10.7f}".format(matrix[i, j]) + " "
                    accum = accum + 1
                elif accum == 5:
                    line = line + "\n"
                    write_file.write(line)
                    line = ""
                    line = line + "{:10.7f}".format(matrix[i, j]) + " "
                    accum = 1
        line = line + "\n"
        write_file.write(line)


if __name__ == '__main__':
    if len(sys.argv) > 1:
        file_name = sys.argv[1]
        matrix = load_hessian(file_name)
        matrix = make_new_hessian(matrix)
        save_hessian(file_name, matrix)
    else:
        print("Please write file name")





