import xml.etree.ElementTree as ET
import string

class Mesh(object):
    def __init__(self,fname):
        self.fname = fname
        self.nodes = []
        self.elements = []
        self.rigidmatids = {}
        self.elasticmatids = {}
        self.rigidelms = {}
        self.elasticelms = {}
        self.__parse_feb()

    def __parse_feb(self):
        tree = ET.parse(self.fname)
        root = tree.getroot()
        geoblk = root.find('Geometry') 
        materialblk = root.find('Material')
        elementblk = geoblk.find('Elements')
        nodeblk = geoblk.find('Nodes')

        for child in materialblk:
            if 'rigid' in child.attrib['type']:
                self.rigidmatids[child.attrib['id']] = True
            elif 'biphasic' not in child.attrib['type']:
                self.elasticmatids[child.attrib['id']] = True

        for child in elementblk:
            etype = child.tag
            eid = int(child.attrib['id'])
            try:
                self.rigidmatids[child.attrib['mat']]
                self.rigidelms[eid] = True
            except:
                pass
            try:
                self.elasticmatids[child.attrib['mat']]
                self.elasticelms[eid] = True
            except:
                pass
            self.elements.append([etype,eid]+map(int,string.split(child.text,',')))
        
        for child in nodeblk:
            nid = int(child.attrib['id'])
            self.nodes.append([nid]+map(float,string.split(child.text,',')))
