#!/usr/bin/python

#
# Simple, naive bibtex parser
#
# Vassilios Karakoidas (2008) - vassilios.karakoidas@gmail.com
#

# bib categories
#
# @Article{
# @Book{
# @Booklet{
# @InBook{
# @InCollection{
# @InProceedings{
# @Manual{
# @MastersThesis{
# @Misc{
# @PhDThesis{
# @Proceedings{
# @TechReport{
# @Unpublished{
#

import re
import os

from io import StringIO

class BibtexEntry:
	def __init__(self, bibfile):
		self.key = ''
		self.data = {}
		self.btype = ''
		self.data['filename'] = bibfile

	def getKey(self, key):
		if(key.lower().strip() == self.key.lower()):
			return True

		return False

	def search(self, keywords):
		for word in keywords:
			for (k, v) in self.data.items():
				try:
					v.lower().index(word.lower())
					return True
				except ValueError:
					continue

		return False

	def __get_pdf_name(self):
		if len(self.key) == 0:
			return None

		m = re.match('(.+/[^.]+)\\.bib', self.data['filename'])
		if m == None:
			return None

		filename = "%s/%s.pdf" % ( m.group(1).strip(), self.key.lower() )
		if os.access(filename, os.O_RDONLY) == 1:
			return filename

		return None

	def has_pdf(self):
		return (self.__get_pdf_name() != None)

	def export(self):
		return self.__str__()

	def totext(self):
		return

	def tohtml(self):
		return

	def __str__(self):
		result = StringIO()

		result.write("@%s{%s,\n" % ( self.btype.lower().strip(), self.key.strip() ))

		for k, v in self.data.items():
			result.write("\t%s = {%s},\n" % ( k.title().strip(), v.strip() ))

		filename =  self.__get_pdf_name()
		if filename != None:
			result.write("\tpdf-file = {%s},\n" % ( filename, ))

		result.write('}\n')

		return result.getvalue()

def parse_bib(bibfile):
	bibitems = {}
	bib_file = open(bibfile, "r")

	re_head = re.compile('@([a-zA-Z]+)[ ]*\{[ ]*(.*),')
	current = None

	for l in bib_file:
		mr = re_head.match(l.strip())
		if mr != None:
			if current == None:
				current = BibtexEntry(bibfile)
			else:
				bibitems[current.key] = current
				current = BibtexEntry(bibfile)
			current.key = mr.group(2).strip()
			current.btype = mr.group(1).strip().lower()
			continue
		try:
			l.index('=')
			kv_data = l.split('=')
			key = kv_data[0].strip()
			mr = re.search('["{](.+)["}]',kv_data[1].strip())
			if mr != None:
				current.data[key] = mr.group(1).strip()
		except (ValueError, AttributeError):
			continue

	bibitems[current.key] = current
	bib_file.close()

	return bibitems

@@ -1,58 +1,25 @@
 #
-!/usr/bin/python%0A%0A#%0A# Simple, naive bibtex parser%0A#%0A#
+ Copyright (c) 2012,
  Vas
@@ -41,16 +41,8 @@
 as (
-2008) - 
 vass
@@ -71,210 +71,1637 @@
 .com
+)
 %0A#
-%0A%0A# bib categories%0A#%0A# @Article%7B%0A# @Book%7B%0A# @Booklet%7B%0A# @InBook%7B%0A# @InCollection%7B%0A# @InProceedings%7B%0A# @Manual%7B%0A# @MastersThesis%7B%0A# @Misc%7B%0A# @PhDThesis%7B%0A# @Proceedings%7B%0A# @TechReport%7B%0A# @Unpublished%7B%0A#
+ All rights reserved.%0A#%0A# Redistribution and use in source and binary forms, with or without%0A# modification, are permitted provided that the following conditions are met:%0A#     * Redistributions of source code must retain the above copyright%0A#       notice, this list of conditions and the following disclaimer.%0A#     * Redistributions in binary form must reproduce the above copyright%0A#       notice, this list of conditions and the following disclaimer in the%0A#       documentation and/or other materials provided with the distribution.%0A#     * Neither the name of the %3Corganization%3E nor the%0A#       names of its contributors may be used to endorse or promote products%0A#       derived from this software without specific prior written permission.%0A#%0A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS %22AS IS%22%0A# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE%0A# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE%0A# DISCLAIMED. IN NO EVENT SHALL %3CCOPYRIGHT HOLDER%3E BE LIABLE FOR ANY%0A# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES%0A# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;%0A# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND%0A# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT%0A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS%0A# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.%0A%0A# based on bibparse.py from bibtex-py 0.8 by Vassilios Karakoidas%0A# small changes by Brecht Machiels for citeproc-py
 %0A%0Aim

include license for bibparse.py