# Copyright 2004,2005 Pierre Martineau <pmartino@users.sourceforge.net>
# This file is part of Bibus, a bibliographic database that can
# work together with OpenOffice.org to generate bibliographic indexes.
#
# Bibus is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Bibus is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Bibus; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA.
#
# Change-history: 	-(date, author) changes
#
#	-(Oct. 15 2004, Stefan Ukena)
#		Changed behavior of format() so that it will return an empty string if there is not author/editor.
#		(The original format() returns the value of the <sep5> field (that's the name of the field in the GUI, in
#		it is sep[4]) even i
#
def __remNull(li):
	while True:
		try: li.remove('')	# remove empty elements
		except ValueError: return li

def format(str1,str2,str3,uselocale,*sep):
	"""joining procedure. str1 = first author. str2 = list of middle authors, str3  = last author
	out = '<sep1>First<sep2>Middle1<sep3>Middle2<sep3>Middle3<sep4>Last<sep5>'
	<sep> = singular form | plural form
	sep6 = sep[5] = integer >=2 if we must abbreviate list after author n° sep6 included. =1 is stupid.
	sep7 = sep[6] = Abbreviation to use (et al.)
	we return (author,abbreviation) because format in citation of authors and 'et al.' may be different
	"""
	total = 0
	if str1: total = total+1
	if str2: total = total+ len(str2)
	if str3: total = total+1
	if total == 0:  return '' # return empty string if there is not author/editor. (Added by Stefan Ukena, Oct. 15 2004)
	form = 0
	if total >= 2:	form = 1 # there are at least 2 authors/Editors => plural form
	sepn=[]
	for i in range(5):
		if sep[i].find('|') != -1: sepn.append(sep[i].split('|')[form])
		else: sepn.append(sep[i])
	#
	if sep[5] > 0 and sep[5] < total:
		if str1: t=1
		str3=sep[6]
		sepn[3]=''	# no separator before last author = abbreviation
		str2 = str2[:sep[5]-t]
		tmp=list((str1,sepn[2].join(str2)))
		__remNull(tmp)
		return sepn[0] + sepn[1].join(tmp)+ sepn[4],str3
	else:
		tmp=list((str1,sepn[2].join(str2)))
		__remNull(tmp)
		tmp=list((sepn[1].join(tmp),str3))
		__remNull(tmp)
		return sepn[0] + sepn[3].join(tmp) + sepn[4],''		# no abbreviation

