"""datafile.py

This module provides functions for working with Extracto data files.

Functions:
open    Open a handle to a data file.
load    Load a data file.
find    Find a data file.
make    Make a full path name for a data file.

"""
import os

import comments

if hasattr(__builtins__, 'file'):
    _open = file  # file is the type for open
else:
    _open = open
def open(name, *args):
    """open(name, ...) -> handle"""
    p, f = os.path.split(__file__)
    path = os.path.join(p, "data")
    filename = os.path.join(path, name)
    return _open(filename, *args)

def load(name, path=None, clean=1, delimiter=None):
    """load(name[, path][, clean][, delimiter]) -> lines

    Load a datafile into a list of lines.  path is an optional path to
    search for this file.  If clean is true (default), then I will
    clean up the lines by removing the comments.  delimiter is an
    optional parameter specifying a column delimiter.  If delimiter is
    set, then will split each line by this character.

    """
    filename = find(name, path=path)
    if not filename:
        raise IOError, "Could not file data file %s" % name
    lines = _open(filename).readlines()
    if clean:
        lines = comments.remove_many(lines)
    if delimiter is not None:
        lines = [x.split(delimiter) for x in lines]
    return lines

def find(name, path=None):
    """find(name[, path]) -> filename or None

    Find the full path of a datafile named name.  Returns None if not
    found.

    """
    if not path:
        p, f = os.path.split(__file__)
        path = [os.path.join(p, "data")]
    for p in path:
        filename = os.path.join(p, name)
        if os.path.exists(filename):
            return filename
    return None

def make(name, path=None):
    """make(name[, path]) -> filename

    Make the full path for a datafile named name.

    """
    # Make sure name is not a full path already.
    head, tail = os.path.split(name)
    if head:
        raise ValueError, "name %s is already full path" % name
    if not path:
        p, f = os.path.split(__file__)
        path = os.path.join(p, "data")
    return os.path.join(path, name)


