#!/usr/bin/env python
# Python version of MPM (MikTeX Package Manager)

from xml.parsers import expat
# import codecs

# fields=[u'Name', u'Title', u'TimePackaged', u'Description', u'MD5'
#         , u'RunFiles', u'SourceFiles', u'Creator', u'DocFiles']
  

#Define a search class that will handle 
#elements and search character data 
class PackageXML(object): 
  """ Class used to create a dict from a *.tpm file in a MikTeX distribution"""
  element = u"TPM:" 
  fields=[u'name', u'title', u'size', u'timepackaged', u'description', u'md5'
          , u'runfiles', u'sourcefiles', u'creator', u'docfiles']
  
  def __init__ (self,filename): 
    self.pack={}
    for s in self.fields:
      self.pack[s]=""
    self.key=None
    self.pack['size']=0
    self.fName=filename

  def StartElement(self, name, attributes): 
    if name.find(self.element) != -1:
      self.key= name.replace(self.element,'').lower().strip()
      if self.key == "":
        self.key= None
      if attributes.has_key('size'):
        self.pack['size']= self.pack['size'] + int(attributes['size'])

  def EndElement(self, name): 
    self.key= None

  def CharacterData(self, data): 
    if data.strip():
#       if self.pack['name']=='acrotex':
#         print repr(data)
      try:
        self.pack[self.key] += data
      except:
        self.pack[self.key]= data

  def Parse(self):
    xmlParser = expat.ParserCreate()   #Create the expat parser object 
    xmlParser.StartElementHandler = self.StartElement   #Override the handler methods 
    xmlParser.EndElementHandler = self.EndElement 
    xmlParser.CharacterDataHandler = self.CharacterData 
    # Parse the XML file
    try:
#       fi=codecs.open(self.fName,'r')
      fi= open(self.fName,'r')
      xmlParser.Parse(fi.read(), 1) 
      fi.close()
      return self.pack
    except:
      return self.pack


#####################################################################
#####################################################################   
#####################################################################
#####################################################################   

# If the program is run directly or passed as an argument to the python
# interpreter then create a gMPMwnd instance and show it
if __name__ == "__main__":

  xmlFile = "/usr/local/share/texmf/tpm/packages/abstract.tpm" 
#Create search class 
  package = PackageXML(xmlFile).Parse()
#Invoke the search objects Parse method 
  print package
  print type(package), package



