##############################################################################
# msbase.py Version 0.1.3
# (c) by Michael Stroeder <michael@stroeder.com>
##############################################################################
# This module is distributed under the terms of the
# GPL (GNU GENERAL PUBLIC LICENSE) Version 2
# (see http://www.gnu.org/copyleft/gpl.html)
##############################################################################

import sys, string, UserDict


# Alle Vorkommen aller Elemente von removelist in l loeschen
# Kein Fehler, falls ein Element aus removelist nicht in l enthalten ist.
def listremove(l,removelist,ignorecase=0):
  if ignorecase:
    searchlist = map(string.lower,l)
    removelist = map(string.lower,removelist)
  else:
    searchlist = l
  indexlist = filter(
    lambda x,l1=searchlist,l2=removelist:l1[x] in l2,
    range(len(searchlist)-1,-1,-1)
  )
  for i in indexlist:
    del l[i]
  return l
    
# Schnelle Schnittmenge
def intersection(a,b,ignorecase=0):
  if ignorecase:
    temp = CaseinsensitiveStringKeyDict()
  else:
    temp = {}
  result = []
  for elt in a:
    temp[elt] = 1
  for elt in b:
    if temp.has_key(elt):
      result.append(elt)
  return result

# Schnelle Vereinigungsmenge
def union(a,b,ignorecase=0):
  if ignorecase:
    temp = CaseinsensitiveStringKeyDict()
  else:
    temp = {}
  for elt in a:
    temp[elt] = 1
  for elt in b:
    temp[elt] = 1
  return temp.keys()


# Dictionary-Klasse, die bei nicht vorhandenem
# Key einen Default-Wert ausgibt
class DefaultDict(UserDict.UserDict):

  def __init__(self,default=None):
    self.__default__ = default
    UserDict.UserDict.__init__(self)

  def __getitem__(self,key):
    return self.data.get(key, self.__default__)


# Class for grabbing the string-formatting keys out of a string
class GrabKeys:

    def __init__(self,s):
        self.keys = []
	s % self

    def __call__(self):
      return self.keys

    def __getitem__(self, name):
        self.keys.append(name)
        return 0 # 0 is apparently compatible with all % format characters


# Dictionary class for case-insensitive string-keyed dictionaries
class CaseinsensitiveStringKeyDict(UserDict.UserDict):

  def __init__(self,dict={},default=None):
    UserDict.UserDict.__init__(self)
    self.__default__ = default
    if dict:
      for i in dict.keys():
        i_lowercase = string.lower(i)
        self.data[i_lowercase] = dict[i]

  def __setitem__(self,key,data):
    key_lowercase = string.lower(key)
    self.data[key_lowercase] = data

  def __getitem__(self,key):
    if self.__default__ is None:
      return self.data[string.lower(key)]
    else:
      return self.data.get(string.lower(key), self.__default__)

  def keys(self):
    return self.data.keys()

  def has_key(self,key):
    return self.data.has_key(string.lower(key))

  def get(self,key,default=None):
    if default is None:
      default=self.default
    return self.data.get(string.lower(key), default)

