#!/usr/bin/env python
# -*- coding: utf-8 -*-

""" CREATED: 7/2012
    AUTHOR: TOMÁŠ ODSTRČIL
"""

from numpy import *
from string import find
from pygolem_lite.modules import save_adv_par

import os



#This function loads the binary data from a Tektronix ".ISF"
#file.  The ISF file format is used by newer Tektronix
#TDS-series oscilloscopes.

#USAGE

#(v,t,h) = isf_read('ch1.isf.gz', 'gzip')

#INPUT

#filename - name of Tektronix ISF file, or gziped ISF file

#OUTPUT

#x - evenly spaced column-vector of x-values
#y - corresponding column-vector of y-values
#head -  header record of file

def getfloat(string,pattern):
    ii = find(string,pattern) + len(pattern)
    z = string[ii:].split(';')[0]
    return float(z)
    
def getint(string,pattern):
    ii = find(string,pattern) + len(pattern)
    z = string[ii:].split(';')[0]
    return int(z)
    
def getstr(string,pattern):
    ii = find(string,pattern) + len(pattern) + 1
    z = string[ii:].split(';')[0]
    return z

    
def getquotedstr(string,pattern):
    ii = find(string,pattern) + len(pattern) + 1
    z = string[ii:].split('"')[1]
    return z

def isf_read(filename):

    if not os.path.exists(filename):
	raise IOError, "Missing .isf file"
    if os.path.getsize(filename) == 0:
	raise IOError, "Empty .isf file"

    f = open(filename, "rb")
    offset = 0
    
    #offset
    f.seek(offset,0)

    hdata = f.read(511)

    class HeadFile:
	def __init__(self):
	    pass
    
    head = HeadFile()
    

    
    head.byte_num = getint(hdata,'BYT_N')
    head.bit_num = getint(hdata,'BIT_N')
    head.encoding = getstr(hdata,'ENC')
    head.bin_format = getstr(hdata,'BN_F')
    head.byte_order = getstr(hdata,'BYT_O')
    head.setting = getquotedstr(hdata,'WFI')
    head.point_format = getstr(hdata,'PT_F')
    head.x_unit = getquotedstr(hdata,'XUN')
    head.x_zero = getfloat(hdata,'XZE')
    head.x_increment = getfloat(hdata,'XIN')
    head.pt_off = getfloat(hdata,'PT_O')
    head.y_unit = getquotedstr(hdata,'YUN')
    head.y_multipt_const = getfloat(hdata,'YMU')
    head.y_zero = getfloat(hdata,'YZE')
    head.y_offset = getfloat(hdata,'YOF')
    head.n_samples = getint(hdata,'NR_P')
    
    # nevím jestli jsou potřebné
    head.vscale = getfloat(hdata,'VSCALE')
    head.hscale = getfloat(hdata,'HSCALE')
    head.vpos = getfloat(hdata,'VPOS')
    head.voffset = getfloat(hdata,'VOFFSET')
    head.hdelay = getfloat(hdata,'HDELAY')
    
    print  head.setting 
    
    if  head.encoding !='BIN' or head.bin_format != 'RI' or head.point_format != 'Y':
	f.close()
	print 'Unable to process IFS file.'




    if head.byte_order == 'MSB': # Big Endian encoding
	machineformat = '<'
	
    elif head.byte_order == 'LSB':  # little-endian encoding 
	machineformat = '>'
    else:
	print 'Unrecognized byte order.'


    
    ii = find(hdata,'#')
    f.seek(ii+1+offset,0)
    skip= int(f.read(1))+1
    f.seek(skip,1)
    
    data_type = machineformat+'i'+str(head.byte_num)  
    
    data = fromstring(f.read(), dtype= data_type,count = head.n_samples )
    f.close()
    
    v = head.y_zero + head.y_multipt_const*(data - head.y_offset)

    #v = v.astype('float32')
    
    t = head.x_zero + head.x_increment*arange( head.n_samples)
    
    save_adv_par(filename[:-4],t,data, scale = head.y_multipt_const) 

    return single(v),single(t),head

def isf2array(filename,  compression = None):
  v,t,h = isf_read(filename, compression)
  return    vstack([t,v]).T

  
  
#(v,t,h) = isf_read('ch1.isf')

#from matplotlib.pyplot import *

#plot(t,v)
#show()
