#!/usr/bin/python
#
# arch-tag: 7310d551-512f-468f-9ba7-5b29669dee92
#
# Module to maintain calibration data for the various analog sensors.
#

__version__ = '1.1'

def _stripquotes(s):
    L = []
    for e in s:
        if not e in ('"', "'"):
            L.append(e)
    return ''.join(L)

class Calibration(object):
    """Instances of this class load sensor calibration data
    from a CSV file. Each line has the following format:

      name,c0,c1,...,units

    where cN are the calibration coefficients.
    
    """
    def __init__(self, file=None):
        self.cal = {}
        self.units = {}
        if file:
            self.update(file)

    def update(self, file):
        fd = open(file, 'r')
        for line in fd.readlines():
            if line[0] == '#':
                continue
            f = line.split(',')
            name = _stripquotes(f[0])
            self.cal[name] = [float(e) for e in f[1:-1]]
            self.units[name] = _stripquotes(f[-1].strip())
        fd.close()

    def __getitem__(self, name):
        return self.cal[name],self.units[name]

    def __len__(self):
        return len(self.cal)

    def keys(self):
        return self.cal.keys()

    def has_key(self, name):
        return self.cal.has_key(name)
    
