""" Parser for bibtex files """

DEBUG = False

from os.path import dirname, join as pjoin
import sys

from .ply import lex
from .ply import yacc

# We are doing our own error recovery, and so don't allow post error tokens
# without further p_error calls.  This is a module global
yacc.error_count = 1

from .btlex import tokens, make_lexer, reset_lexer


class Macro(object):
    """ Class to encapsulate undefined macro references """
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return 'Macro("%s")' % self.name
    def __eq__(self, other):
        return self.name == other.name
    def __ne__(self, other):
        return self.name != other.name


def make_error(t):
    """ Create error marker token to signal read error to parser """
    tok = lex.LexToken()
    tok.type = 'ERRORMARKER'
    tok.value = 'error marker'
    tok.lineno = t.lineno
    tok.lexpos = t.lexpos
    return tok

tokens += ('ERRORMARKER',)

_MYPATH=dirname(__file__)


class BibTeXEntries(object):
    def __init__(self, entries = None,
                 preamble = None,
                 defined_macros = None,
                 undefined_macros = None):
        if entries is None:
            entries = {}
        if preamble is None:
            preamble = []
        if defined_macros is None:
            defined_macros = {}
        if undefined_macros is None:
            undefined_macros = {}
        self.entries = entries
        self.preamble = preamble
        self.defined_macros = defined_macros
        self.undefined_macros = undefined_macros

    def __eq__(self, other):
        return (self.entries == other.entries and
                self.preamble == other.preamble)


class BibTeXParser(object):
    def __init__(self,