#!/usr/bin/env python
# -*- coding: utf-8 -*-

#
# Generated Mon Jul  6 15:04:35 2015 by generateDS.py version 2.15b.
#
# Command line options:
#   ('--silence', '')
#   ('-o', '../sdminfoxml_parser.py')
#
# Command line arguments:
#   sdminfo.xsd
#
# Command line:
#   /usr/local/bin/generateDS.py --silence -o "../sdminfoxml_parser.py" sdminfo.xsd
#
# Current working directory (os.getcwd()):
#   schemata
#

import sys
import re as re_
import base64
import datetime as datetime_
import warnings as warnings_
from lxml import etree as etree_


Validate_simpletypes_ = True


def parsexml_(*args, **kwargs):
    if 'parser' not in kwargs:
        # Use the lxml ElementTree compatible parser so that, e.g.,
        #   we ignore comments.
        kwargs['parser'] = etree_.ETCompatXMLParser()
    doc = etree_.parse(*args, **kwargs)
    return doc

#
# User methods
#
# Calls to the methods in these classes are generated by generateDS.py.
# You can replace these methods by re-implementing the following class
#   in a module named generatedssuper.py.

try:
    from generatedssuper import GeneratedsSuper
except ImportError as exp:

    class GeneratedsSuper(object):
        tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$')
        class _FixedOffsetTZ(datetime_.tzinfo):
            def __init__(self, offset, name):
                self.__offset = datetime_.timedelta(minutes=offset)
                self.__name = name
            def utcoffset(self, dt):
                return self.__offset
            def tzname(self, dt):
                return self.__name
            def dst(self, dt):
                return None
        def gds_format_string(self, input_data, input_name=''):
            return input_data
        def gds_validate_string(self, input_data, node=None, input_name=''):
            if not input_data:
                return ''
            else:
                return input_data
        def gds_format_base64(self, input_data, input_name=''):
            return base64.b64encode(input_data)
        def gds_validate_base64(self, input_data, node=None, input_name=''):
            return input_data
        def gds_format_integer(self, input_data, input_name=''):
            return '%d' % input_data
        def gds_validate_integer(self, input_data, node=None, input_name=''):
            return input_data
        def gds_format_integer_list(self, input_data, input_name=''):
            return '%s' % ' '.join(input_data)
        def gds_validate_integer_list(
                self, input_data, node=None, input_name=''):
            values = input_data.split()
            for value in values:
                try:
                    int(value)
                except (TypeError, ValueError):
                    raise_parse_error(node, 'Requires sequence of integers')
            return values
        def gds_format_float(self, input_data, input_name=''):
            return ('%.15f' % input_data).rstrip('0')
        def gds_validate_float(self, input_data, node=None, input_name=''):
            return input_data
        def gds_format_float_list(self, input_data, input_name=''):
            return '%s' % ' '.join(input_data)
        def gds_validate_float_list(
                self, input_data, node=None, input_name=''):
            values = input_data.split()
            for value in values:
                try:
                    float(value)
                except (TypeError, ValueError):
                    raise_parse_error(node, 'Requires sequence of floats')
            return values
        def gds_format_double(self, input_data, input_name=''):
            return '%e' % input_data
        def gds_validate_double(self, input_data, node=None, input_name=''):
            return input_data
        def gds_format_double_list(self, input_data, input_name=''):
            return '%s' % ' '.join(input_data)
        def gds_validate_double_list(
                self, input_data, node=None, input_name=''):
            values = input_data.split()
            for value in values:
                try:
                    float(value)
                except (TypeError, ValueError):
                    raise_parse_error(node, 'Requires sequence of doubles')
            return values
        def gds_format_boolean(self, input_data, input_name=''):
            return ('%s' % input_data).lower()
        def gds_validate_boolean(self, input_data, node=None, input_name=''):
            return input_data
        def gds_format_boolean_list(self, input_data, input_name=''):
            return '%s' % ' '.join(input_data)
        def gds_validate_boolean_list(
                self, input_data, node=None, input_name=''):
            values = input_data.split()
            for value in values:
                if value not in ('true', '1', 'false', '0', ):
                    raise_parse_error(
                        node,
                        'Requires sequence of booleans '
                        '("true", "1", "false", "0")')
            return values
        def gds_validate_datetime(self, input_data, node=None, input_name=''):
            return input_data
        def gds_format_datetime(self, input_data, input_name=''):
            if input_data.microsecond == 0:
                _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % (
                    input_data.year,
                    input_data.month,
                    input_data.day,
                    input_data.hour,
                    input_data.minute,
                    input_data.second,
                )
            else:
                _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % (
                    input_data.year,
                    input_data.month,
                    input_data.day,
                    input_data.hour,
                    input_data.minute,
                    input_data.second,
                    ('%f' % (float(input_data.microsecond) / 1000000))[2:],
                )
            if input_data.tzinfo is not None:
                tzoff = input_data.tzinfo.utcoffset(input_data)
                if tzoff is not None:
                    total_seconds = tzoff.seconds + (86400 * tzoff.days)
                    if total_seconds == 0:
                        _svalue += 'Z'
                    else:
                        if total_seconds < 0:
                            _svalue += '-'
                            total_seconds *= -1
                        else:
                            _svalue += '+'
                        hours = total_seconds // 3600
                        minutes = (total_seconds - (hours * 3600)) // 60
                        _svalue += '{0:02d}:{1:02d}'.format(hours, minutes)
            return _svalue
        @classmethod
        def gds_parse_datetime(cls, input_data):
            tz = None
            if input_data[-1] == 'Z':
                tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC')
                input_data = input_data[:-1]
            else:
                results = GeneratedsSuper.tzoff_pattern.search(input_data)
                if results is not None:
                    tzoff_parts = results.group(2).split(':')
                    tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1])
                    if results.group(1) == '-':
                        tzoff *= -1
                    tz = GeneratedsSuper._FixedOffsetTZ(
                        tzoff, results.group(0))
                    input_data = input_data[:-6]
            time_parts = input_data.split('.')
            if len(time_parts) > 1:
                micro_seconds = int(float('0.' + time_parts[1]) * 1000000)
                input_data = '%s.%s' % (time_parts[0], micro_seconds, )
                dt = datetime_.datetime.strptime(
                    input_data, '%Y-%m-%dT%H:%M:%S.%f')
            else:
                dt = datetime_.datetime.strptime(
                    input_data, '%Y-%m-%dT%H:%M:%S')
            dt = dt.replace(tzinfo=tz)
            return dt
        def gds_validate_date(self, input_data, node=None, input_name=''):
            return input_data
        def gds_format_date(self, input_data, input_name=''):
            _svalue = '%04d-%02d-%02d' % (
                input_data.year,
                input_data.month,
                input_data.day,
            )
            try:
                if input_data.tzinfo is not None:
                    tzoff = input_data.tzinfo.utcoffset(input_data)
                    if tzoff is not None:
                        total_seconds = tzoff.seconds + (86400 * tzoff.days)
                        if total_seconds == 0:
                            _svalue += 'Z'
                        else:
                            if total_seconds < 0:
                                _svalue += '-'
                                total_seconds *= -1
                            else:
                                _svalue += '+'
                            hours = total_seconds // 3600
                            minutes = (total_seconds - (hours * 3600)) // 60
                            _svalue += '{0:02d}:{1:02d}'.format(hours, minutes)
            except AttributeError:
                pass
            return _svalue
        @classmethod
        def gds_parse_date(cls, input_data):
            tz = None
            if input_data[-1] == 'Z':
                tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC')
                input_data = input_data[:-1]
            else:
                results = GeneratedsSuper.tzoff_pattern.search(input_data)
                if results is not None:
                    tzoff_parts = results.group(2).split(':')
                    tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1])
                    if results.group(1) == '-':
                        tzoff *= -1
                    tz = GeneratedsSuper._FixedOffsetTZ(
                        tzoff, results.group(0))
                    input_data = input_data[:-6]
            dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d')
            dt = dt.replace(tzinfo=tz)
            return dt.date()
        def gds_validate_time(self, input_data, node=None, input_name=''):
            return input_data
        def gds_format_time(self, input_data, input_name=''):
            if input_data.microsecond == 0:
                _svalue = '%02d:%02d:%02d' % (
                    input_data.hour,
                    input_data.minute,
                    input_data.second,
                )
            else:
                _svalue = '%02d:%02d:%02d.%s' % (
                    input_data.hour,
                    input_data.minute,
                    input_data.second,
                    ('%f' % (float(input_data.microsecond) / 1000000))[2:],
                )
            if input_data.tzinfo is not None:
                tzoff = input_data.tzinfo.utcoffset(input_data)
                if tzoff is not None:
                    total_seconds = tzoff.seconds + (86400 * tzoff.days)
                    if total_seconds == 0:
                        _svalue += 'Z'
                    else:
                        if total_seconds < 0:
                            _svalue += '-'
                            total_seconds *= -1
                        else:
                            _svalue += '+'
                        hours = total_seconds // 3600
                        minutes = (total_seconds - (hours * 3600)) // 60
                        _svalue += '{0:02d}:{1:02d}'.format(hours, minutes)
            return _svalue
        def gds_validate_simple_patterns(self, patterns, target):
            # pat is a list of lists of strings/patterns.  We should:
            # - AND the outer elements
            # - OR the inner elements
            found1 = True
            for patterns1 in patterns:
                found2 = False
                for patterns2 in patterns1:
                    if re_.search(patterns2, target) is not None:
                        found2 = True
                        break
                if not found2:
                    found1 = False
                    break
            return found1
        @classmethod
        def gds_parse_time(cls, input_data):
            tz = None
            if input_data[-1] == 'Z':
                tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC')
                input_data = input_data[:-1]
            else:
                results = GeneratedsSuper.tzoff_pattern.search(input_data)
                if results is not None:
                    tzoff_parts = results.group(2).split(':')
                    tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1])
                    if results.group(1) == '-':
                        tzoff *= -1
                    tz = GeneratedsSuper._FixedOffsetTZ(
                        tzoff, results.group(0))
                    input_data = input_data[:-6]
            if len(input_data.split('.')) > 1:
                dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f')
            else:
                dt = datetime_.datetime.strptime(input_data, '%H:%M:%S')
            dt = dt.replace(tzinfo=tz)
            return dt.time()
        def gds_str_lower(self, instring):
            return instring.lower()
        def get_path_(self, node):
            path_list = []
            self.get_path_list_(node, path_list)
            path_list.reverse()
            path = '/'.join(path_list)
            return path
        Tag_strip_pattern_ = re_.compile(r'\{.*\}')
        def get_path_list_(self, node, path_list):
            if node is None:
                return
            tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag)
            if tag:
                path_list.append(tag)
            self.get_path_list_(node.getparent(), path_list)
        def get_class_obj_(self, node, default_class=None):
            class_obj1 = default_class
            if 'xsi' in node.nsmap:
                classname = node.get('{%s}type' % node.nsmap['xsi'])
                if classname is not None:
                    names = classname.split(':')
                    if len(names) == 2:
                        classname = names[1]
                    class_obj2 = globals().get(classname)
                    if class_obj2 is not None:
                        class_obj1 = class_obj2
            return class_obj1
        def gds_build_any(self, node, type_name=None):
            return None
        @classmethod
        def gds_reverse_node_mapping(cls, mapping):
            return dict(((v, k) for k, v in mapping.iteritems()))


#
# If you have installed IPython you can uncomment and use the following.
# IPython is available from http://ipython.scipy.org/.
#

## from IPython.Shell import IPShellEmbed
## args = ''
## ipshell = IPShellEmbed(args,
##     banner = 'Dropping into IPython',
##     exit_msg = 'Leaving Interpreter, back to program.')

# Then use the following line where and when you want to drop into the
# IPython shell:
#    ipshell('<some message> -- Entering ipshell.\nHit Ctrl-D to exit')

#
# Globals
#

ExternalEncoding = 'ascii'
Tag_pattern_ = re_.compile(r'({.*})?(.*)')
String_cleanup_pat_ = re_.compile(r"[\n\r\s]+")
Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)')
CDATA_pattern_ = re_.compile(r"<!\[CDATA\[.*?\]\]>", re_.DOTALL)

#
# Support/utility functions.
#


def showIndent(outfile, level, pretty_print=True):
    if pretty_print:
        for idx in range(level):
            outfile.write('    ')


def quote_xml(inStr):
    "Escape markup chars, but do not modify CDATA sections."
    if not inStr:
        return ''
    s1 = (isinstance(inStr, basestring) and inStr or
          '%s' % inStr)
    s2 = ''
    pos = 0
    matchobjects = CDATA_pattern_.finditer(s1)
    for mo in matchobjects:
        s3 = s1[pos:mo.start()]
        s2 += quote_xml_aux(s3)
        s2 += s1[mo.start():mo.end()]
        pos = mo.end()
    s3 = s1[pos:]
    s2 += quote_xml_aux(s3)
    return s2


def quote_xml_aux(inStr):
    s1 = inStr.replace('&', '&amp;')
    s1 = s1.replace('<', '&lt;')
    s1 = s1.replace('>', '&gt;')
    return s1


def quote_attrib(inStr):
    s1 = (isinstance(inStr, basestring) and inStr or
          '%s' % inStr)
    s1 = s1.replace('&', '&amp;')
    s1 = s1.replace('<', '&lt;')
    s1 = s1.replace('>', '&gt;')
    if '"' in s1:
        if "'" in s1:
            s1 = '"%s"' % s1.replace('"', "&quot;")
        else:
            s1 = "'%s'" % s1
    else:
        s1 = '"%s"' % s1
    return s1


def quote_python(inStr):
    s1 = inStr
    if s1.find("'") == -1:
        if s1.find('\n') == -1:
            return "'%s'" % s1
        else:
            return "'''%s'''" % s1
    else:
        if s1.find('"') != -1:
            s1 = s1.replace('"', '\\"')
        if s1.find('\n') == -1:
            return '"%s"' % s1
        else:
            return '"""%s"""' % s1


def get_all_text_(node):
    if node.text is not None:
        text = node.text
    else:
        text = ''
    for child in node:
        if child.tail is not None:
            text += child.tail
    return text


def find_attr_value_(attr_name, node):
    attrs = node.attrib
    attr_parts = attr_name.split(':')
    value = None
    if len(attr_parts) == 1:
        value = attrs.get(attr_name)
    elif len(attr_parts) == 2:
        prefix, name = attr_parts
        namespace = node.nsmap.get(prefix)
        if namespace is not None:
            value = attrs.get('{%s}%s' % (namespace, name, ))
    return value


class GDSParseError(Exception):
    pass


def raise_parse_error(node, msg):
    if XMLParser_import_library == XMLParser_import_lxml:
        msg = '%s (element %s/line %d)' % (
            msg, node.tag, node.sourceline, )
    else:
        msg = '%s (element %s)' % (msg, node.tag, )
    raise GDSParseError(msg)


class MixedContainer:
    # Constants for category:
    CategoryNone = 0
    CategoryText = 1
    CategorySimple = 2
    CategoryComplex = 3
    # Constants for content_type:
    TypeNone = 0
    TypeText = 1
    TypeString = 2
    TypeInteger = 3
    TypeFloat = 4
    TypeDecimal = 5
    TypeDouble = 6
    TypeBoolean = 7
    TypeBase64 = 8
    def __init__(self, category, content_type, name, value):
        self.category = category
        self.content_type = content_type
        self.name = name
        self.value = value
    def getCategory(self):
        return self.category
    def getContenttype(self, content_type):
        return self.content_type
    def getValue(self):
        return self.value
    def getName(self):
        return self.name
    def export(self, outfile, level, name, namespace, pretty_print=True):
        if self.category == MixedContainer.CategoryText:
            # Prevent exporting empty content as empty lines.
            if self.value.strip():
                outfile.write(self.value)
        elif self.category == MixedContainer.CategorySimple:
            self.exportSimple(outfile, level, name)
        else:    # category == MixedContainer.CategoryComplex
            self.value.export(outfile, level, namespace, name, pretty_print)
    def exportSimple(self, outfile, level, name):
        if self.content_type == MixedContainer.TypeString:
            outfile.write('<%s>%s</%s>' % (
                self.name, self.value, self.name))
        elif self.content_type == MixedContainer.TypeInteger or \
                self.content_type == MixedContainer.TypeBoolean:
            outfile.write('<%s>%d</%s>' % (
                self.name, self.value, self.name))
        elif self.content_type == MixedContainer.TypeFloat or \
                self.content_type == MixedContainer.TypeDecimal:
            outfile.write('<%s>%f</%s>' % (
                self.name, self.value, self.name))
        elif self.content_type == MixedContainer.TypeDouble:
            outfile.write('<%s>%g</%s>' % (
                self.name, self.value, self.name))
        elif self.content_type == MixedContainer.TypeBase64:
            outfile.write('<%s>%s</%s>' % (
                self.name, base64.b64encode(self.value), self.name))
    def to_etree(self, element):
        if self.category == MixedContainer.CategoryText:
            # Prevent exporting empty content as empty lines.
            if self.value.strip():
                if len(element) > 0:
                    if element[-1].tail is None:
                        element[-1].tail = self.value
                    else:
                        element[-1].tail += self.value
                else:
                    if element.text is None:
                        element.text = self.value
                    else:
                        element.text += self.value
        elif self.category == MixedContainer.CategorySimple:
            subelement = etree_.SubElement(element, '%s' % self.name)
            subelement.text = self.to_etree_simple()
        else:    # category == MixedContainer.CategoryComplex
            self.value.to_etree(element)
    def to_etree_simple(self):
        if self.content_type == MixedContainer.TypeString:
            text = self.value
        elif (self.content_type == MixedContainer.TypeInteger or
                self.content_type == MixedContainer.TypeBoolean):
            text = '%d' % self.value
        elif (self.content_type == MixedContainer.TypeFloat or
                self.content_type == MixedContainer.TypeDecimal):
            text = '%f' % self.value
        elif self.content_type == MixedContainer.TypeDouble:
            text = '%g' % self.value
        elif self.content_type == MixedContainer.TypeBase64:
            text = '%s' % base64.b64encode(self.value)
        return text
    def exportLiteral(self, outfile, level, name):
        if self.category == MixedContainer.CategoryText:
            showIndent(outfile, level)
            outfile.write(
                'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % (
                    self.category, self.content_type, self.name, self.value))
        elif self.category == MixedContainer.CategorySimple:
            showIndent(outfile, level)
            outfile.write(
                'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % (
                    self.category, self.content_type, self.name, self.value))
        else:    # category == MixedContainer.CategoryComplex
            showIndent(outfile, level)
            outfile.write(
                'model_.MixedContainer(%d, %d, "%s",\n' % (
                    self.category, self.content_type, self.name,))
            self.value.exportLiteral(outfile, level + 1)
            showIndent(outfile, level)
            outfile.write(')\n')


class MemberSpec_(object):
    def __init__(self, name='', data_type='', container=0):
        self.name = name
        self.data_type = data_type
        self.container = container
    def set_name(self, name): self.name = name
    def get_name(self): return self.name
    def set_data_type(self, data_type): self.data_type = data_type
    def get_data_type_chain(self): return self.data_type
    def get_data_type(self):
        if isinstance(self.data_type, list):
            if len(self.data_type) > 0:
                return self.data_type[-1]
            else:
                return 'xs:string'
        else:
            return self.data_type
    def set_container(self, container): self.container = container
    def get_container(self): return self.container


def _cast(typ, value):
    if typ is None or value is None:
        return value
    return typ(value)

#
# Data representation classes.
#


class SdmInfo(GeneratedsSuper):
    subclass = None
    superclass = None
    def __init__(self, timestamp=None, sender=None, seqNo=None, sdmVersion=None, sdmLocation=None, bdfLocation=None, scanNumber=None, subscanNumber=None, scanIntents=None, datasetID=None, datasetId=None, numIntegrations=None, dataSize=None, finalMessage=None, state=None, calReduction=None):
        self.original_tagname_ = None
        self.timestamp = _cast(float, timestamp)
        self.sender = _cast(None, sender)
        self.seqNo = _cast(int, seqNo)
        self.sdmVersion = sdmVersion
        self.sdmLocation = sdmLocation
        self.bdfLocation = bdfLocation
        self.scanNumber = scanNumber
        self.subscanNumber = subscanNumber
        self.scanIntents = scanIntents
        self.datasetID = datasetID
        self.datasetId = datasetId
        self.numIntegrations = numIntegrations
        self.dataSize = dataSize
        self.finalMessage = finalMessage
        self.state = state
        self.calReduction = calReduction
    def factory(*args_, **kwargs_):
        if SdmInfo.subclass:
            return SdmInfo.subclass(*args_, **kwargs_)
        else:
            return SdmInfo(*args_, **kwargs_)
    factory = staticmethod(factory)
    def get_sdmVersion(self): return self.sdmVersion
    def set_sdmVersion(self, sdmVersion): self.sdmVersion = sdmVersion
    def get_sdmLocation(self): return self.sdmLocation
    def set_sdmLocation(self, sdmLocation): self.sdmLocation = sdmLocation
    def get_bdfLocation(self): return self.bdfLocation
    def set_bdfLocation(self, bdfLocation): self.bdfLocation = bdfLocation
    def get_scanNumber(self): return self.scanNumber
    def set_scanNumber(self, scanNumber): self.scanNumber = scanNumber
    def get_subscanNumber(self): return self.subscanNumber
    def set_subscanNumber(self, subscanNumber): self.subscanNumber = subscanNumber
    def get_scanIntents(self): return self.scanIntents
    def set_scanIntents(self, scanIntents): self.scanIntents = scanIntents
    def get_datasetID(self): return self.datasetID
    def set_datasetID(self, datasetID): self.datasetID = datasetID
    def get_datasetId(self): return self.datasetId
    def set_datasetId(self, datasetId): self.datasetId = datasetId
    def get_numIntegrations(self): return self.numIntegrations
    def set_numIntegrations(self, numIntegrations): self.numIntegrations = numIntegrations
    def get_dataSize(self): return self.dataSize
    def set_dataSize(self, dataSize): self.dataSize = dataSize
    def get_finalMessage(self): return self.finalMessage
    def set_finalMessage(self, finalMessage): self.finalMessage = finalMessage
    def get_state(self): return self.state
    def set_state(self, state): self.state = state
    def get_calReduction(self): return self.calReduction
    def set_calReduction(self, calReduction): self.calReduction = calReduction
    def get_timestamp(self): return self.timestamp
    def set_timestamp(self, timestamp): self.timestamp = timestamp
    def get_sender(self): return self.sender
    def set_sender(self, sender): self.sender = sender
    def get_seqNo(self): return self.seqNo
    def set_seqNo(self, seqNo): self.seqNo = seqNo
    def hasContent_(self):
        if (
            self.sdmVersion is not None or
            self.sdmLocation is not None or
            self.bdfLocation is not None or
            self.scanNumber is not None or
            self.subscanNumber is not None or
            self.scanIntents is not None or
            self.datasetID is not None or
            self.datasetId is not None or
            self.numIntegrations is not None or
            self.dataSize is not None or
            self.finalMessage is not None or
            self.state is not None or
            self.calReduction is not None
        ):
            return True
        else:
            return False
    def export(self, outfile, level, namespace_='', name_='SdmInfo', namespacedef_='', pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        if self.original_tagname_ is not None:
            name_ = self.original_tagname_
        showIndent(outfile, level, pretty_print)
        outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
        already_processed = set()
        self.exportAttributes(outfile, level, already_processed, namespace_, name_='SdmInfo')
        if self.hasContent_():
            outfile.write('>%s' % (eol_, ))
            self.exportChildren(outfile, level + 1, namespace_='', name_='SdmInfo', pretty_print=pretty_print)
            showIndent(outfile, level, pretty_print)
            outfile.write('</%s%s>%s' % (namespace_, name_, eol_))
        else:
            outfile.write('/>%s' % (eol_, ))
    def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='SdmInfo'):
        if self.timestamp is not None and 'timestamp' not in already_processed:
            already_processed.add('timestamp')
            outfile.write(' timestamp="%s"' % self.gds_format_double(self.timestamp, input_name='timestamp'))
        if self.sender is not None and 'sender' not in already_processed:
            already_processed.add('sender')
            outfile.write(' sender=%s' % (self.gds_format_string(quote_attrib(self.sender).encode(ExternalEncoding), input_name='sender'), ))
        if self.seqNo is not None and 'seqNo' not in already_processed:
            already_processed.add('seqNo')
            outfile.write(' seqNo="%s"' % self.gds_format_integer(self.seqNo, input_name='seqNo'))
    def exportChildren(self, outfile, level, namespace_='', name_='SdmInfo', fromsubclass_=False, pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        if self.sdmVersion is not None:
            showIndent(outfile, level, pretty_print)
            outfile.write('<%ssdmVersion>%s</%ssdmVersion>%s' % (namespace_, self.gds_format_string(quote_xml(self.sdmVersion).encode(ExternalEncoding), input_name='sdmVersion'), namespace_, eol_))
        if self.sdmLocation is not None:
            showIndent(outfile, level, pretty_print)
            outfile.write('<%ssdmLocation>%s</%ssdmLocation>%s' % (namespace_, self.gds_format_string(quote_xml(self.sdmLocation).encode(ExternalEncoding), input_name='sdmLocation'), namespace_, eol_))
        if self.bdfLocation is not None:
            showIndent(outfile, level, pretty_print)
            outfile.write('<%sbdfLocation>%s</%sbdfLocation>%s' % (namespace_, self.gds_format_string(quote_xml(self.bdfLocation).encode(ExternalEncoding), input_name='bdfLocation'), namespace_, eol_))
        if self.scanNumber is not None:
            showIndent(outfile, level, pretty_print)
            outfile.write('<%sscanNumber>%s</%sscanNumber>%s' % (namespace_, self.gds_format_integer(self.scanNumber, input_name='scanNumber'), namespace_, eol_))
        if self.subscanNumber is not None:
            showIndent(outfile, level, pretty_print)
            outfile.write('<%ssubscanNumber>%s</%ssubscanNumber>%s' % (namespace_, self.gds_format_integer(self.subscanNumber, input_name='subscanNumber'), namespace_, eol_))
        if self.scanIntents is not None:
            showIndent(outfile, level, pretty_print)
            outfile.write('<%sscanIntents>%s</%sscanIntents>%s' % (namespace_, self.gds_format_string(quote_xml(self.scanIntents).encode(ExternalEncoding), input_name='scanIntents'), namespace_, eol_))
        if self.datasetID is not None:
            showIndent(outfile, level, pretty_print)
            outfile.write('<%sdatasetID>%s</%sdatasetID>%s' % (namespace_, self.gds_format_string(quote_xml(self.datasetID).encode(ExternalEncoding), input_name='datasetID'), namespace_, eol_))
        if self.datasetId is not None:
            showIndent(outfile, level, pretty_print)
            outfile.write('<%sdatasetId>%s</%sdatasetId>%s' % (namespace_, self.gds_format_string(quote_xml(self.datasetId).encode(ExternalEncoding), input_name='datasetId'), namespace_, eol_))
        if self.numIntegrations is not None:
            showIndent(outfile, level, pretty_print)
            outfile.write('<%snumIntegrations>%s</%snumIntegrations>%s' % (namespace_, self.gds_format_integer(self.numIntegrations, input_name='numIntegrations'), namespace_, eol_))
        if self.dataSize is not None:
            showIndent(outfile, level, pretty_print)
            outfile.write('<%sdataSize>%s</%sdataSize>%s' % (namespace_, self.gds_format_integer(self.dataSize, input_name='dataSize'), namespace_, eol_))
        if self.finalMessage is not None:
            showIndent(outfile, level, pretty_print)
            outfile.write('<%sfinalMessage>%s</%sfinalMessage>%s' % (namespace_, self.gds_format_boolean(self.finalMessage, input_name='finalMessage'), namespace_, eol_))
        if self.state is not None:
            showIndent(outfile, level, pretty_print)
            outfile.write('<%sstate>%s</%sstate>%s' % (namespace_, self.gds_format_integer(self.state, input_name='state'), namespace_, eol_))
        if self.calReduction is not None:
            self.calReduction.export(outfile, level, namespace_, name_='calReduction', pretty_print=pretty_print)
    def exportLiteral(self, outfile, level, name_='SdmInfo'):
        level += 1
        already_processed = set()
        self.exportLiteralAttributes(outfile, level, already_processed, name_)
        if self.hasContent_():
            self.exportLiteralChildren(outfile, level, name_)
    def exportLiteralAttributes(self, outfile, level, already_processed, name_):
        if self.timestamp is not None and 'timestamp' not in already_processed:
            already_processed.add('timestamp')
            showIndent(outfile, level)
            outfile.write('timestamp=%e,\n' % (self.timestamp,))
        if self.sender is not None and 'sender' not in already_processed:
            already_processed.add('sender')
            showIndent(outfile, level)
            outfile.write('sender="%s",\n' % (self.sender,))
        if self.seqNo is not None and 'seqNo' not in already_processed:
            already_processed.add('seqNo')
            showIndent(outfile, level)
            outfile.write('seqNo=%d,\n' % (self.seqNo,))
    def exportLiteralChildren(self, outfile, level, name_):
        if self.sdmVersion is not None:
            showIndent(outfile, level)
            outfile.write('sdmVersion=%s,\n' % quote_python(self.sdmVersion).encode(ExternalEncoding))
        if self.sdmLocation is not None:
            showIndent(outfile, level)
            outfile.write('sdmLocation=%s,\n' % quote_python(self.sdmLocation).encode(ExternalEncoding))
        if self.bdfLocation is not None:
            showIndent(outfile, level)
            outfile.write('bdfLocation=%s,\n' % quote_python(self.bdfLocation).encode(ExternalEncoding))
        if self.scanNumber is not None:
            showIndent(outfile, level)
            outfile.write('scanNumber=%d,\n' % self.scanNumber)
        if self.subscanNumber is not None:
            showIndent(outfile, level)
            outfile.write('subscanNumber=%d,\n' % self.subscanNumber)
        if self.scanIntents is not None:
            showIndent(outfile, level)
            outfile.write('scanIntents=%s,\n' % quote_python(self.scanIntents).encode(ExternalEncoding))
        if self.datasetID is not None:
            showIndent(outfile, level)
            outfile.write('datasetID=%s,\n' % quote_python(self.datasetID).encode(ExternalEncoding))
        if self.datasetId is not None:
            showIndent(outfile, level)
            outfile.write('datasetId=%s,\n' % quote_python(self.datasetId).encode(ExternalEncoding))
        if self.numIntegrations is not None:
            showIndent(outfile, level)
            outfile.write('numIntegrations=%d,\n' % self.numIntegrations)
        if self.dataSize is not None:
            showIndent(outfile, level)
            outfile.write('dataSize=%d,\n' % self.dataSize)
        if self.finalMessage is not None:
            showIndent(outfile, level)
            outfile.write('finalMessage=%s,\n' % self.finalMessage)
        if self.state is not None:
            showIndent(outfile, level)
            outfile.write('state=%d,\n' % self.state)
        if self.calReduction is not None:
            showIndent(outfile, level)
            outfile.write('calReduction=model_.calReductionType(\n')
            self.calReduction.exportLiteral(outfile, level, name_='calReduction')
            showIndent(outfile, level)
            outfile.write('),\n')
    def build(self, node):
        already_processed = set()
        self.buildAttributes(node, node.attrib, already_processed)
        for child in node:
            nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
            self.buildChildren(child, node, nodeName_)
        return self
    def buildAttributes(self, node, attrs, already_processed):
        value = find_attr_value_('timestamp', node)
        if value is not None and 'timestamp' not in already_processed:
            already_processed.add('timestamp')
            try:
                self.timestamp = float(value)
            except ValueError as exp:
                raise ValueError('Bad float/double attribute (timestamp): %s' % exp)
        value = find_attr_value_('sender', node)
        if value is not None and 'sender' not in already_processed:
            already_processed.add('sender')
            self.sender = value
        value = find_attr_value_('seqNo', node)
        if value is not None and 'seqNo' not in already_processed:
            already_processed.add('seqNo')
            try:
                self.seqNo = int(value)
            except ValueError as exp:
                raise_parse_error(node, 'Bad integer attribute: %s' % exp)
    def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
        if nodeName_ == 'sdmVersion':
            sdmVersion_ = child_.text
            sdmVersion_ = self.gds_validate_string(sdmVersion_, node, 'sdmVersion')
            self.sdmVersion = sdmVersion_
        elif nodeName_ == 'sdmLocation':
            sdmLocation_ = child_.text
            sdmLocation_ = self.gds_validate_string(sdmLocation_, node, 'sdmLocation')
            self.sdmLocation = sdmLocation_
        elif nodeName_ == 'bdfLocation':
            bdfLocation_ = child_.text
            bdfLocation_ = self.gds_validate_string(bdfLocation_, node, 'bdfLocation')
            self.bdfLocation = bdfLocation_
        elif nodeName_ == 'scanNumber':
            sval_ = child_.text
            try:
                ival_ = int(sval_)
            except (TypeError, ValueError) as exp:
                raise_parse_error(child_, 'requires integer: %s' % exp)
            ival_ = self.gds_validate_integer(ival_, node, 'scanNumber')
            self.scanNumber = ival_
        elif nodeName_ == 'subscanNumber':
            sval_ = child_.text
            try:
                ival_ = int(sval_)
            except (TypeError, ValueError) as exp:
                raise_parse_error(child_, 'requires integer: %s' % exp)
            ival_ = self.gds_validate_integer(ival_, node, 'subscanNumber')
            self.subscanNumber = ival_
        elif nodeName_ == 'scanIntents':
            scanIntents_ = child_.text
            scanIntents_ = self.gds_validate_string(scanIntents_, node, 'scanIntents')
            self.scanIntents = scanIntents_
        elif nodeName_ == 'datasetID':
            datasetID_ = child_.text
            datasetID_ = self.gds_validate_string(datasetID_, node, 'datasetID')
            self.datasetID = datasetID_
        elif nodeName_ == 'datasetId':
            datasetId_ = child_.text
            datasetId_ = self.gds_validate_string(datasetId_, node, 'datasetId')
            self.datasetId = datasetId_
        elif nodeName_ == 'numIntegrations':
            sval_ = child_.text
            try:
                ival_ = int(sval_)
            except (TypeError, ValueError) as exp:
                raise_parse_error(child_, 'requires integer: %s' % exp)
            ival_ = self.gds_validate_integer(ival_, node, 'numIntegrations')
            self.numIntegrations = ival_
        elif nodeName_ == 'dataSize':
            sval_ = child_.text
            try:
                ival_ = int(sval_)
            except (TypeError, ValueError) as exp:
                raise_parse_error(child_, 'requires integer: %s' % exp)
            ival_ = self.gds_validate_integer(ival_, node, 'dataSize')
            self.dataSize = ival_
        elif nodeName_ == 'finalMessage':
            sval_ = child_.text
            if sval_ in ('true', '1'):
                ival_ = True
            elif sval_ in ('false', '0'):
                ival_ = False
            else:
                raise_parse_error(child_, 'requires boolean')
            ival_ = self.gds_validate_boolean(ival_, node, 'finalMessage')
            self.finalMessage = ival_
        elif nodeName_ == 'state':
            sval_ = child_.text
            try:
                ival_ = int(sval_)
            except (TypeError, ValueError) as exp:
                raise_parse_error(child_, 'requires integer: %s' % exp)
            ival_ = self.gds_validate_integer(ival_, node, 'state')
            self.state = ival_
        elif nodeName_ == 'calReduction':
            obj_ = calReductionType.factory()
            obj_.build(child_)
            self.calReduction = obj_
            obj_.original_tagname_ = 'calReduction'
# end class SdmInfo


class calReductionType(GeneratedsSuper):
    subclass = None
    superclass = None
    def __init__(self, messages=None, softwareVersion=None, timeReduced=None, software=None, referenceAntennaList=None, pointingSubbandIndices=None):
        self.original_tagname_ = None
        self.messages = _cast(None, messages)
        self.softwareVersion = _cast(None, softwareVersion)
        self.timeReduced = _cast(float, timeReduced)
        self.software = _cast(None, software)
        self.referenceAntennaList = referenceAntennaList
        self.validate_referenceAntennaListType(self.referenceAntennaList)
        self.pointingSubbandIndices = pointingSubbandIndices
        self.validate_pointingSubbandIndicesType(self.pointingSubbandIndices)
    def factory(*args_, **kwargs_):
        if calReductionType.subclass:
            return calReductionType.subclass(*args_, **kwargs_)
        else:
            return calReductionType(*args_, **kwargs_)
    factory = staticmethod(factory)
    def get_referenceAntennaList(self): return self.referenceAntennaList
    def set_referenceAntennaList(self, referenceAntennaList): self.referenceAntennaList = referenceAntennaList
    def get_pointingSubbandIndices(self): return self.pointingSubbandIndices
    def set_pointingSubbandIndices(self, pointingSubbandIndices): self.pointingSubbandIndices = pointingSubbandIndices
    def get_messages(self): return self.messages
    def set_messages(self, messages): self.messages = messages
    def get_softwareVersion(self): return self.softwareVersion
    def set_softwareVersion(self, softwareVersion): self.softwareVersion = softwareVersion
    def get_timeReduced(self): return self.timeReduced
    def set_timeReduced(self, timeReduced): self.timeReduced = timeReduced
    def get_software(self): return self.software
    def set_software(self, software): self.software = software
    def validate_referenceAntennaListType(self, value):
        # Validate type referenceAntennaListType, a restriction on xs:string.
        pass
    def validate_pointingSubbandIndicesType(self, value):
        # Validate type pointingSubbandIndicesType, a restriction on xs:int.
        pass
    def hasContent_(self):
        if (
            self.referenceAntennaList is not None or
            self.pointingSubbandIndices is not None
        ):
            return True
        else:
            return False
    def export(self, outfile, level, namespace_='', name_='calReductionType', namespacedef_='', pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        if self.original_tagname_ is not None:
            name_ = self.original_tagname_
        showIndent(outfile, level, pretty_print)
        outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
        already_processed = set()
        self.exportAttributes(outfile, level, already_processed, namespace_, name_='calReductionType')
        if self.hasContent_():
            outfile.write('>%s' % (eol_, ))
            self.exportChildren(outfile, level + 1, namespace_='', name_='calReductionType', pretty_print=pretty_print)
            showIndent(outfile, level, pretty_print)
            outfile.write('</%s%s>%s' % (namespace_, name_, eol_))
        else:
            outfile.write('/>%s' % (eol_, ))
    def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='calReductionType'):
        if self.messages is not None and 'messages' not in already_processed:
            already_processed.add('messages')
            outfile.write(' messages=%s' % (self.gds_format_string(quote_attrib(self.messages).encode(ExternalEncoding), input_name='messages'), ))
        if self.softwareVersion is not None and 'softwareVersion' not in already_processed:
            already_processed.add('softwareVersion')
            outfile.write(' softwareVersion=%s' % (self.gds_format_string(quote_attrib(self.softwareVersion).encode(ExternalEncoding), input_name='softwareVersion'), ))
        if self.timeReduced is not None and 'timeReduced' not in already_processed:
            already_processed.add('timeReduced')
            outfile.write(' timeReduced="%s"' % self.gds_format_double(self.timeReduced, input_name='timeReduced'))
        if self.software is not None and 'software' not in already_processed:
            already_processed.add('software')
            outfile.write(' software=%s' % (self.gds_format_string(quote_attrib(self.software).encode(ExternalEncoding), input_name='software'), ))
    def exportChildren(self, outfile, level, namespace_='', name_='calReductionType', fromsubclass_=False, pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        if self.referenceAntennaList is not None:
            showIndent(outfile, level, pretty_print)
            outfile.write('<%sreferenceAntennaList>%s</%sreferenceAntennaList>%s' % (namespace_, self.gds_format_string(quote_xml(' '.join(self.referenceAntennaList)).encode(ExternalEncoding), input_name='referenceAntennaList'), namespace_, eol_))
        if self.pointingSubbandIndices is not None:
            showIndent(outfile, level, pretty_print)
            outfile.write('<%spointingSubbandIndices>%s</%spointingSubbandIndices>%s' % (namespace_, self.gds_format_integer_list(self.pointingSubbandIndices, input_name='pointingSubbandIndices'), namespace_, eol_))
    def exportLiteral(self, outfile, level, name_='calReductionType'):
        level += 1
        already_processed = set()
        self.exportLiteralAttributes(outfile, level, already_processed, name_)
        if self.hasContent_():
            self.exportLiteralChildren(outfile, level, name_)
    def exportLiteralAttributes(self, outfile, level, already_processed, name_):
        if self.messages is not None and 'messages' not in already_processed:
            already_processed.add('messages')
            showIndent(outfile, level)
            outfile.write('messages="%s",\n' % (self.messages,))
        if self.softwareVersion is not None and 'softwareVersion' not in already_processed:
            already_processed.add('softwareVersion')
            showIndent(outfile, level)
            outfile.write('softwareVersion="%s",\n' % (self.softwareVersion,))
        if self.timeReduced is not None and 'timeReduced' not in already_processed:
            already_processed.add('timeReduced')
            showIndent(outfile, level)
            outfile.write('timeReduced=%e,\n' % (self.timeReduced,))
        if self.software is not None and 'software' not in already_processed:
            already_processed.add('software')
            showIndent(outfile, level)
            outfile.write('software="%s",\n' % (self.software,))
    def exportLiteralChildren(self, outfile, level, name_):
        if self.referenceAntennaList is not None:
            showIndent(outfile, level)
            if self.referenceAntennaList:
                outfile.write('referenceAntennaList=%s,\n' % quote_python(' '.join(self.referenceAntennaList)).encode(ExternalEncoding)) 
            else:
                outfile.write('referenceAntennaList=None,\n')
        if self.pointingSubbandIndices is not None:
            showIndent(outfile, level)
            outfile.write('pointingSubbandIndices=%d,\n' % self.pointingSubbandIndices)
    def build(self, node):
        already_processed = set()
        self.buildAttributes(node, node.attrib, already_processed)
        for child in node:
            nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
            self.buildChildren(child, node, nodeName_)
        return self
    def buildAttributes(self, node, attrs, already_processed):
        value = find_attr_value_('messages', node)
        if value is not None and 'messages' not in already_processed:
            already_processed.add('messages')
            self.messages = value
        value = find_attr_value_('softwareVersion', node)
        if value is not None and 'softwareVersion' not in already_processed:
            already_processed.add('softwareVersion')
            self.softwareVersion = value
        value = find_attr_value_('timeReduced', node)
        if value is not None and 'timeReduced' not in already_processed:
            already_processed.add('timeReduced')
            try:
                self.timeReduced = float(value)
            except ValueError as exp:
                raise ValueError('Bad float/double attribute (timeReduced): %s' % exp)
        value = find_attr_value_('software', node)
        if value is not None and 'software' not in already_processed:
            already_processed.add('software')
            self.software = value
    def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
        if nodeName_ == 'referenceAntennaList':
            referenceAntennaList_ = child_.text
            self.referenceAntennaList = referenceAntennaList_
            # validate type referenceAntennaListType
            self.validate_referenceAntennaListType(self.referenceAntennaList)
        elif nodeName_ == 'pointingSubbandIndices':
            pointingSubbandIndices_ = child_.text
            pointingSubbandIndices_ = self.gds_validate_integer_list(pointingSubbandIndices_, node, 'pointingSubbandIndices')
            self.pointingSubbandIndices = pointingSubbandIndices_
            # validate type pointingSubbandIndicesType
            self.validate_pointingSubbandIndicesType(self.pointingSubbandIndices)
# end class calReductionType


GDSClassesMapping = {
    'calReduction': calReductionType,
}


USAGE_TEXT = """
Usage: python <Parser>.py [ -s ] <in_xml_file>
"""


def usage():
    print(USAGE_TEXT)
    sys.exit(1)


def get_root_tag(node):
    tag = Tag_pattern_.match(node.tag).groups()[-1]
    rootClass = GDSClassesMapping.get(tag)
    if rootClass is None:
        rootClass = globals().get(tag)
    return tag, rootClass


def parse(inFileName, silence=False):
    doc = parsexml_(inFileName)
    rootNode = doc.getroot()
    rootTag, rootClass = get_root_tag(rootNode)
    if rootClass is None:
        rootTag = 'SdmInfo'
        rootClass = SdmInfo
    rootObj = rootClass.factory()
    rootObj.build(rootNode)
    # Enable Python to collect the space used by the DOM.
    doc = None
##     if not silence:
##         sys.stdout.write('<?xml version="1.0" ?>\n')
##         rootObj.export(
##             sys.stdout, 0, name_=rootTag,
##             namespacedef_='',
##             pretty_print=True)
    return rootObj


def parseEtree(inFileName, silence=False):
    doc = parsexml_(inFileName)
    rootNode = doc.getroot()
    rootTag, rootClass = get_root_tag(rootNode)
    if rootClass is None:
        rootTag = 'SdmInfo'
        rootClass = SdmInfo
    rootObj = rootClass.factory()
    rootObj.build(rootNode)
    # Enable Python to collect the space used by the DOM.
    doc = None
    mapping = {}
    rootElement = rootObj.to_etree(None, name_=rootTag, mapping_=mapping)
    reverse_mapping = rootObj.gds_reverse_node_mapping(mapping)
##     if not silence:
##         content = etree_.tostring(
##             rootElement, pretty_print=True,
##             xml_declaration=True, encoding="utf-8")
##         sys.stdout.write(content)
##         sys.stdout.write('\n')
    return rootObj, rootElement, mapping, reverse_mapping


def parseString(inString, silence=False):
    from StringIO import StringIO
    doc = parsexml_(StringIO(inString))
    rootNode = doc.getroot()
    rootTag, rootClass = get_root_tag(rootNode)
    if rootClass is None:
        rootTag = 'SdmInfo'
        rootClass = SdmInfo
    rootObj = rootClass.factory()
    rootObj.build(rootNode)
    # Enable Python to collect the space used by the DOM.
    doc = None
##     if not silence:
##         sys.stdout.write('<?xml version="1.0" ?>\n')
##         rootObj.export(
##             sys.stdout, 0, name_=rootTag,
##             namespacedef_='')
    return rootObj


def parseLiteral(inFileName, silence=False):
    doc = parsexml_(inFileName)
    rootNode = doc.getroot()
    rootTag, rootClass = get_root_tag(rootNode)
    if rootClass is None:
        rootTag = 'SdmInfo'
        rootClass = SdmInfo
    rootObj = rootClass.factory()
    rootObj.build(rootNode)
    # Enable Python to collect the space used by the DOM.
    doc = None
##     if not silence:
##         sys.stdout.write('#from sdminfoxml_parser import *\n\n')
##         sys.stdout.write('import sdminfoxml_parser as model_\n\n')
##         sys.stdout.write('rootObj = model_.rootClass(\n')
##         rootObj.exportLiteral(sys.stdout, 0, name_=rootTag)
##         sys.stdout.write(')\n')
    return rootObj


def main():
    args = sys.argv[1:]
    if len(args) == 1:
        parse(args[0])
    else:
        usage()


if __name__ == '__main__':
    #import pdb; pdb.set_trace()
    main()


__all__ = [
    "SdmInfo",
    "calReductionType"
]
