"""
Python access to RTC-Tools B-Spline caches.

Author:  Jorn Baayen
Date  :  September 15, 2015
"""

import numpy as np
import struct
import io

def splread(filename):
	"""
	Construct a FITPACK spline in scipy representation from the RTC-Tools spline data in the given file.
	"""

	# Load file
	tck = None
	with io.open(filename, 'rb') as f:
		# Parse data
		buf = f.read(4)
		nx = struct.unpack('i', buf)[0]
		tx = np.fromstring(f.read(8 * nx), dtype='f8')
	
		buf = f.read(4)
		nc = struct.unpack('i', buf)[0]
		c = np.fromstring(f.read(8 * nc), dtype='f8')	

		buf = f.read(4)
		k = struct.unpack('i', buf)[0]

		tck = (tx, c, k)

	# Done
	return tck

def bisplread(filename):
	"""
	Construct a FITPACK spline in scipy representation from the RTC-Tools spline data in the given file.
	"""

	# Load file
	tck = None
	with io.open(filename, 'rb') as f:
		# Parse data
		buf = f.read(4)
		nx = struct.unpack('i', buf)[0]
		tx = np.fromstring(f.read(8 * nx), dtype='f8')

		buf = f.read(4)
		ny = struct.unpack('i', buf)[0]
		ty = np.fromstring(f.read(8 * ny), dtype='f8')
	
		buf = f.read(4)
		nc = struct.unpack('i', buf)[0]
		c = np.fromstring(f.read(8 * nc), dtype='f8')	

		buf = f.read(4)
		k = struct.unpack('i', buf)[0]

		tck = (tx, ty, c, k, k)

	# Done
	return tck