#!/usr/bin/env python
#
# MIGALE Input/Output
#
# Last rev: 10/07/2025
from __future__ import print_function, division

import numpy as np

from ..cr import cr


@cr('MigaleIO.readMesh')
def readMIGALEmesh(filename):
	'''
	Read the representation mesh output from MIGALE
	
	The file is already partitioned
	WARNING! each processor reads its own file
	thus a lot of file pointers are opened
	and the filesystem might get collapsed
	'''
	# Open file
	file = open(filename,'r')
	# Read header
	data  = np.genfromtxt(file,comments='#',max_rows=9)
	ndim  = int(data[2])
	nelem = int(data[7])
	nnod  = int(data[8])
	elty  = 12 if ndim == 2 else 37 # NOTE: here we hardcode 12 for quad and 37 for hexa
	# Read node values
	data  = np.genfromtxt(file,comments='#',max_rows=nnod)
	lninv = data[:,0].astype(np.int32) - 1 # because Python
	xyz   = data[:,1:(ndim+1)]
	# Read connectivity values
	data  = np.genfromtxt(file,comments='#',max_rows=nelem)
	leinv = data[:,0].astype(np.int32) - 1  # because Python
	conec = data[:,1:].astype(np.int32) - 1 # because Python
	ltype = elty*np.ones((nelem,),np.int32)
	# Close file
	file.close()
	# Return
	return xyz, conec, lninv, leinv, ltype

@cr('MigaleIO.readField')
def readMIGALEfield(filename,varList):
	'''
	Read the field output from MIGALE
	
	The file is already partitioned
	WARNING! each processor reads its own file
	thus a lot of file pointers are opened
	and the filesystem might get collapsed
	'''
	# Open file
	file = open(filename,'r')
	# Read header
	data  = np.genfromtxt(file,comments='#',max_rows=11)
	istep = int(data[6])
	tstep = data[7]
	nnod  = int(data[10])
	# Read node fields
	data  = np.genfromtxt(file,comments='#',max_rows=nnod)
	# Might need to refine this or not...
	varDict = {}
	for v in varList:
		if v == 'density':     varDict[v] = data[:,1].astype(np.double)
		if v == 'pressure':    varDict[v] = data[:,2].astype(np.double)
		if v == 'temperature': varDict[v] = data[:,3].astype(np.double)
		if v == 'velocity':    varDict[v] = data[:,4:].astype(np.double)
	# Close file
	file.close()
	return istep, tstep, varDict