#!/bin/python
# Writes the common binaryMatrixFile format from a python numpy array
from numpy import fromfile, array, int32
from os.path import getsize

def binRead(fileName) :
	fLen = getsize(fileName);

	f = open(fileName,"rb");

	sizeData = fromfile(f, dtype='>i4', count=2);

	nRows = sizeData[0];
	nCols = sizeData[1];	

	if (fLen-8) != nRows*nCols*8 : 
		# number of /complete/ rows in file
		nRowsInFile = int((fLen-8)/nCols/8);

		print("WARNING: binRead("+fileName+"): File reported " + \
			str(nRows) + " rows, but only have "+str(nRowsInFile)+" in file.")
		
		nRows = nRowsInFile;

	data = fromfile(f, dtype='>f8', count=nRows*nCols);

	f.close();

	return data.reshape(nRows,nCols);


def binWrite(fileName, data) :
	f = open(fileName, "wb");

	nRows = data.shape[0];
	nCols = data.shape[1];

	sizeData = array(data.shape, dtype=int32).byteswap();

	sizeData.tofile(f);

	if data.dtype.name == "float64" and data.dtype.byteorder == '>' :
		#can write as-is
		data.tofile(f);
	else :
		#have to convert
		reorderedData = array(data, dtype='>f8', order='C');
		reorderedData.tofile(f);

	f.close();


				

	
