#!/usr/bin/env python

import sys
import sqlite3
import operator
import textwrap
import re
from pprint import pprint

__all__ = ['Logic']

_mitigation_device_enum = {
    'Pockels Cell': 'MPSMitigationDevicePockelsCell',
    'Mechanical Shutter': 'MPSMitigationDeviceMechanicalShutter',
    'BYKIK': 'MPSMitigationDeviceBykik',
    'Laser Heater Shutter': 'MPSMitigationDeviceFuture'
}

_rate_c_code_string = [
    'MPSRateInvalid',
    'MPSRate0Hz',
    'MPSRateSingleShot',
    'MPSRateBurstMode',
    'MPSRate1Hz',
    'MPSRate10Hz',
    'MPSRate30Hz',
    'MPSRate60Hz',
    'MPSRate120Hz',
    '\n\n#error: bad rate!!\n\n'
]

_rate_latex_string = [
    r'Invalid',
    r'\unit{0}{\hertz}',
    r'Single Shot',
    r'Burst Mode',
    r'\unit{1}{\hertz}',
    r'\unit{10}{\hertz}',
    r'\unit{30}{\hertz}',
    r'\unit{60}{\hertz}',
    r'\unit{120}{\hertz}',
    r'Unknown',
    r'--'
]

_rate_rst_string = [
    'Invalid',
    '0 Hz',
    'Single Shot',
    'Burst Mode',
    '1 Hz',
    '10 Hz',
    '30 Hz',
    '60 Hz',
    '120 Hz',
    '??????',
    '--'
]

rst_text = {
    'code_header': "The following code assigns the truth table's state "
                   "number to the ``unsigned int`` variable ``state``",
}

c_text = {
    'header':
        '''
        /* Initialize Max Rates to 120 Hz */
        setMaxRateAfterDevice(MPSRate120Hz, MPSMitigationDevicePockelsCell);
        setMaxRateAfterDevice(MPSRate120Hz, MPSMitigationDeviceMechanicalShutter);
        setMaxRateAfterDevice(MPSRate120Hz, MPSMitigationDeviceBykik);
        setMaxRateAfterDevice(MPSRate120Hz, MPSMitigationDeviceFuture);
        ''',
}

latex_text = {
    'header':
        r'''
        \documentclass[10pt, oneside]{{book}}
        \usepackage{{lcls-article}}
        \usepackage[usenames]{{color}}
        \usepackage{{listings}}
        \usepackage[titles]{{tocloft}}
        
        \cftsetindents{{section}}{{1.5em}}{{3.5em}}
        \definecolor{{CommentColor}}{{rgb}}{{0,0.5,0.1}}
        \definecolor{{BgColor}}{{rgb}}{{1,1,0.93}}
        
        \newcommand\code{{\begingroup \urlstyle{{tt}}\Url}}
        \renewcommand\revnum{{{doc_rev}}}
        
        \title{{MPS Logic:\\{doc_rev}}}
        \date{{}}
        
        \begin{{document}}
        
        \maketitle
        
        \setcounter{{page}}{{2}}
        
        \lstset{{language=C,frame=single,stringstyle=\ttfamily,commentstyle=\color{{CommentColor}},breaklines=true,morekeywords={{state}},frameround=tttt,backgroundcolor=\color{{BgColor}}}}
        
        \tableofcontents
        '''[1:],
    'code_header':
        r'''
        The following code assigns the truth table's state number to the \texttt{unsigned int} variable \texttt{state}.
        \begin{center}
        \begin{lstlisting}
        ''',
    'code_footer':
        r'''
        \end{lstlisting}
        \end{center}
        '''
}
 

def latex_escape(string):
    escaped = str(string)
    escaped = escaped.replace('\\', r'\textbackslash')
    escaped = escaped.replace(r'$', r'\$')
    escaped = escaped.replace(r'_', r'\_')
    escaped = escaped.replace(r'&', r'\&')
    escaped = escaped.replace(r'%', r'\%')
    return escaped    


def c_test(macro, state):
    state_number = state.number
    device_state_conditions = []
    for d in macro.devices:
        operator = ' ' if state_number & (0x01 << d['number']) else '!'
        device_state_conditions.insert(0, operator + d['info'].name)
    return '({0})'.format(' && '.join(device_state_conditions))


def indent(string, amount=4):
    line_start = re.compile(r'^', re.MULTILINE)
    return re.sub(line_start, ' ' * amount, string)


def starify(string):
    line_start = re.compile(r'^', re.MULTILINE)
    return re.sub(line_start, ' * ', string)


def case_insensitive_compare(x, y):
    return cmp(x.lower(), y.lower())


def format_block(str_list, commented=False):
    out = []
    if commented:
        out.append('/*')
        out.append(starify('\n'.join(str_list)))
        out.append(' */')
    else:
        out = str_list
    return '\n'.join(out)


class ReprObject(object):
    def __repr__(self):
        try:
            attr_val = ('{0}={1!r}'.format(a, getattr(self, a)) for a in self._repr_attr)
        except AttributeError:
            attr_val = tuple()
            
        return '{0}({1})'.format(self.__class__.__name__, ', '.join(attr_val))


class SqlTable(ReprObject):
    def __init__(self, **kwargs):
        for m in self.schema:
            try:
                raw_value = kwargs.get(m['attr'], m['default'])
                value = m['type'](raw_value)
                setattr(self, m['attr'], value)
            except TypeError as e:
                print self.table, kwargs

    @property
    def _repr_attr(self):
        return (s['attr'] for s in self.schema)
    
    @classmethod
    def readall_query(cls):
        where_list = ['{0[attr]} is not NULL'.format(s) for s in cls.schema if s.get('not_null')]
        if where_list:
            where = ' where {0}'.format(' and '.join(where_list))
        else:
            where = ''
        
        select = ', '.join('{0[col]} {0[attr]}'.format(s) for s in cls.schema)
        
        q = 'select {s} from {t}{w}'.format(
            s = select,
            t = cls.table,
            w = where,
        )
        
        return q

    def __repr__(self):        
        return super(SqlTable, self).__repr__()


class MacroNumber(SqlTable):
    table = 'macro_number'
    schema = (
        {'col':'macro_fk',     'attr':'pk',           'type':int, 'default':-1},
        {'col':'macro_number', 'attr':'macro_number', 'type':int, 'default':-1},
    )


class Macro(SqlTable):
    table = 'ZMACRO'
    schema = (
        {'col':'Z_PK',      'attr':'pk',          'type':int,  'default':-1},
        {'col':'ZISACTIVE', 'attr':'is_active',   'type':bool, 'default':True},
        {'col':'ZISCODE',   'attr':'is_code',     'type':bool, 'default':False},
        {'col':'ZCODE',     'attr':'code',        'type':str,  'default':''},
        {'col':'ZDESCRIPT', 'attr':'description', 'type':str,  'default':''},
        {'col':'ZNAME',     'attr':'name',        'type':str,  'default':''},
    )
    
    @property
    def code(self):
        return self._code
    
    @code.setter
    def code(self, value):
        self._code = textwrap.dedent(value)


class MacroOptOut(SqlTable):
    table = 'ZMACROOPTOUT'
    schema = (
        {'col':'Z_PK',         'attr':'pk',                'type':int, 'default':-1},
        {'col':'ZIGNOREMACRO', 'attr':'ignoring_macro_fk', 'type':int, 'default':-1, 'not_null': True},
        {'col':'ZMACRO',       'attr':'ignored_macro_fk',  'type':int, 'default':-1, 'not_null': True},
    )


class IgnoreMacro(SqlTable):
    table = 'ZIGNOREMACRO'
    schema = (
        {'col':'Z_PK',   'attr':'pk',       'type':int, 'default':-1},
        {'col':'ZMACRO', 'attr':'macro_fk', 'type':int, 'default':-1, 'not_null': True},
    )


class State(SqlTable):
    table = 'ZMACROSTATE'
    schema = (
        {'col':'Z_PK',       'attr':'pk',         'type':int,  'default':-1},
        {'col':'ZNUMBER',    'attr':'number',     'type':int,  'default':-1},
        {'col':'ZISDEFAULT', 'attr':'is_default', 'type':bool, 'default':False},
        {'col':'ZMACRO',     'attr':'macro_fk',   'type':int,  'default':-1, 'not_null': True},
        {'col':'ZNAME',      'attr':'name',       'type':str,  'default':''},
        {'col':'ZSOLUTION',  'attr':'solution',   'type':str,  'default':''},
    )


class StateRateAtDevice(SqlTable):
    table = 'ZMACROSTATERATEATDEVICE'
    schema = (
        {'col':'Z_PK',    'attr':'pk',        'type':int, 'default':-1},
        {'col':'ZSTATE',  'attr':'state_fk',  'type':int, 'default':-1, 'not_null': True},
        {'col':'ZDEVICE', 'attr':'device_fk', 'type':int, 'default':-1, 'not_null': True},
        {'col':'ZRATE',   'attr':'rate_fk',   'type':int, 'default':-1, 'not_null': True},
    )


class MitigationDevice(SqlTable):
    table = 'ZMITIGATIONDEVICE'
    schema = (
        {'col':'Z_PK',  'attr':'pk',   'type':int, 'default':-1},
        {'col':'ZENUM', 'attr':'enum', 'type':int, 'default':-1},
        {'col':'ZNAME', 'attr':'name', 'type':str, 'default':''},
    )


class Rate(SqlTable):
    table = 'ZRATE'
    schema = (
        {'col':'Z_PK',  'attr':'pk',   'type':int, 'default':-1},
        {'col':'ZENUM', 'attr':'enum', 'type':int, 'default':-1},
        {'col':'ZNAME', 'attr':'name', 'type':str, 'default':''},
    )


class MacroInput(SqlTable):
    table = 'ZMACROINPUT'
    schema = (
        {'col':'Z_PK',      'attr':'pk',            'type':int, 'default':-1},
        {'col':'ZPOSITION', 'attr':'position',      'type':int, 'default':-1},
        {'col':'ZMACRO',    'attr':'macro_fk',      'type':int, 'default':-1, 'not_null': True},
        {'col':'ZDEVICE',   'attr':'mps_device_fk', 'type':int, 'default':-1, 'not_null': True},
    )


class MpsDevice(SqlTable):
    table = 'ZDEVICE'
    schema = (
        {'col':'Z_PK',  'attr':'pk',   'type':int, 'default':-1},
        {'col':'ZNAME', 'attr':'name', 'type':str, 'default':''},
    )


class Contact(SqlTable):
    table = 'ZCONTACT'
    schema = (
        {'col':'Z_PK',   'attr':'pk',    'type':int, 'default':-1},
        {'col':'ZEMAIL', 'attr':'email', 'type':str, 'default':'@slac.stanford.edu'},
        {'col':'ZNAME',  'attr':'name',  'type':str, 'default':''},
    )


class MacroContact(SqlTable):
    table = 'ZMACROCONTACT'
    schema = (
        {'col':'Z_PK',     'attr':'pk',         'type':int, 'default':-1},
        {'col':'ZCONTACT', 'attr':'contact_fk', 'type':int, 'default':-1, 'not_null': True},
        {'col':'ZMACRO',   'attr':'macro_fk',   'type':int, 'default':-1, 'not_null': True},
    )

class Logic(ReprObject):
    _repr_attr = (
        'macro',
        'macro_opt_out',
        'ignore_macro',
        'state',
        'state_rate_at_device',
        'mitigation_device',
        'rate',
        'macro_input',
        'mps_device',
        'macro_contact',
        'contact',
        'macro_number'
    )
    
    def __init__(self, path=None, cursor=None, **kwargs):
        self.path = path
        self.cursor = cursor
        self._cached_ignore_groups = None
        self.revision = '--'
        
        for a in self._repr_attr:
            setattr(self, a, kwargs.get(a, {}))

        if cursor:
            self.init_with_cursor(cursor)
        elif path:
            self.init_with_path(path)

    def init_with_cursor(self, cursor=None):
        tables = (
            {
                'class': Macro,
                'attr': self.macro,
            },
            {
                'class': MacroOptOut,
                'attr': self.macro_opt_out,
            },
            {
                'class': IgnoreMacro,
                'attr': self.ignore_macro,
            },
            {
                'class': State,
                'attr': self.state,
            },
            {
                'class': StateRateAtDevice,
                'attr': self.state_rate_at_device,
            },
            {
                'class': MacroInput,
                'attr': self.macro_input,
            },
            {
                'class': MpsDevice,
                'attr': self.mps_device,
            },
            {
                'class': MitigationDevice,
                'attr': self.mitigation_device,
            },
            {
                'class': Rate,
                'attr': self.rate,
            },
            {
                'class': Contact,
                'attr': self.contact,
            },
            {
                'class': MacroContact,
                'attr': self.macro_contact,
            },
            {
                'class': MacroNumber,
                'attr': self.macro_number,
            },
        )
        
        for table in tables:
            query = table['class'].readall_query()
            cursor.execute(query)
            
            for row in cursor:
                tmp = table['class'](**row)
                table['attr'][tmp.pk] = tmp

    def init_with_path(self, path=None):
        self.path = path
    
        connection             = sqlite3.connect(self.path)
        connection.row_factory = sqlite3.Row
        cursor                 = connection.cursor()
        
        self.init_with_cursor(cursor)
        
        connection.close()

    def _sort_and_title_ignore_set(self, ignore_macro_fks):
        if not ignore_macro_fks:
            return ('Always Evaluated Logic and Ignore Logic', None)
        
        macros = (self.macro[self.ignore_macro[igm_fk].macro_fk] for igm_fk in ignore_macro_fks)
        macros = sorted(macros, key=operator.attrgetter('name'), cmp=case_insensitive_compare)
        
        macro_names = [m.name for m in macros]
                
        if len(macro_names) <= 2:
            title = 'Ignored when {0}'.format(' or '.join(macro_names))
        else:
            title = 'Ignored when {0}, or {1}'.format(
                ', '.join(macro_names[:-1]),
                macro_names[-1]
            )
        return (title, macros)

    @property
    def _ignore_groups(self):
        if self._cached_ignore_groups:
            return self._cached_ignore_groups
        
        ign_grp = {}
        for m in self.macro.itervalues():
            m.devices = self._devices_for_macro(m.pk)
            m.states = self._states_for_macro(m.pk)
            
            for s in m.states:
                s.rates = self._rates_for_state(s.pk)
            
            fs = frozenset(v.ignoring_macro_fk for v in self.macro_opt_out.itervalues() if v.ignored_macro_fk == m.pk)
            if fs not in ign_grp:
                ign_grp[fs] = {}
                ign_grp[fs]['macros'] = []
                ign_grp[fs]['title'], ign_grp[fs]['ignore_macros'] = self._sort_and_title_ignore_set(fs)
            ign_grp[fs]['macros'].append(m)
        
        sorted_groups = sorted(
            ign_grp.itervalues(),
            key=operator.itemgetter('title'),
            cmp=case_insensitive_compare
        )

        always_eval_and_ign_grps = filter(lambda x: x['ignore_macros'] is None, sorted_groups)[0]
        sorted_groups.remove(always_eval_and_ign_grps)

        ign_macro_fks = [ign_macro.macro_fk for ign_macro in self.ignore_macro.itervalues()]
        ign_macro_grp = [m for m in always_eval_and_ign_grps['macros'] if m.pk in ign_macro_fks]
        alwy_eval_grp = [m for m in always_eval_and_ign_grps['macros'] if m.pk not in ign_macro_fks]
        
        sorted_groups.append({'title': 'Always Evaluated',
                              'macros': alwy_eval_grp})

        sorted_groups.append({'title': 'Ignore Logic',
                              'macros': ign_macro_grp,
                              'is_ignore_logic': True})

        for ignore_group in sorted_groups:
            ignore_group['macros'] = sorted(
                ignore_group['macros'],
                key=operator.attrgetter('name'),
                cmp=case_insensitive_compare
            )
        
        self._cached_ignore_groups = sorted_groups 
        return self._cached_ignore_groups
        
    def _rates_for_state(self, state_pk):
        rates = (v for k, v in self.state_rate_at_device.iteritems() if v.state_fk == state_pk)
        rate_dict = dict((self.mitigation_device[r.device_fk].name, self.rate[r.rate_fk].enum) for r in rates)
        return rate_dict
    
    def _devices_for_macro(self, macro_pk):
        inputs = [(v.position, v.mps_device_fk) for k, v in self.macro_input.iteritems() if v.macro_fk == macro_pk]
        inputs.sort()
        devices_info = ((i, chr(i + ord('A')), self.mps_device[inp[1]]) for i, inp in enumerate(inputs))
        devices = [dict(zip(('number', 'variable', 'info'), d)) for d in devices_info]
        
        return devices
    
    def _states_for_macro(self, macro_pk):        
        states = (v for k, v in self.state.iteritems() if v.macro_fk == macro_pk)
        states = sorted(states, key=operator.attrgetter('number'))
        
        return states
    
    def export_rst(self, out_file=sys.stdout):
        self._export(out_file=out_file)
    
    def export_c_code(self, out_file=sys.stdout):
        self._export(as_c_code=True, out_file=out_file)
    
    def export_latex(self, out_file=sys.stdout):
        self._export(as_latex=True, out_file=out_file)
    
    def _export(self, as_c_code=False, as_latex=False, out_file=sys.stdout):
        if as_c_code and as_latex:
            raise Exception("can't format c code and latex at the same time")
    
        if as_c_code:
            print >> out_file, textwrap.dedent(c_text['header'])
            
        if as_latex:
            print >> out_file, textwrap.dedent(latex_text['header'].format(doc_rev=latex_escape(self.revision)))
        
        for g in self._ignore_groups:
            if as_latex:
                doc_out = []
                doc_out.append(r'\chapter{{{0}}}'.format(latex_escape(g['title'])))
            else:
                doc_out = []
                doc_out.append(g['title'])
                doc_out.append('=' * len(g['title']))

            print >> out_file, format_block(doc_out, as_c_code)
            print >> out_file, ''
            indent_base = 0

            if as_c_code and 'ignore_macros' in g:
                indent_base = 4
                tests = []
                for m in g.get('ignore_macros', tuple()):
                    tests.append(c_test(m, m.states[0]))
                print >> out_file, 'if ({0})'.format(' ||\n    '.join(tests))
                print >> out_file, '{'
                
                for m in g['macros']:
                    print >> out_file, indent('/* Ignore {0} */'.format(m.name), indent_base)
                    print >> out_file, indent('setNewTruthTableState({0}, MPSTruthTableStateIgnored);'.format(self.macro_number[m.pk].macro_number), indent_base)
                    print >> out_file, ''
                print >> out_file, '}'
                print >> out_file, 'else'
                print >> out_file, '{'

            for m in g['macros']:
                if as_latex:
                    doc_out = []
                    doc_out.append(r'\section{{{0}}}'.format(latex_escape(m.name)))
                    
                    if m.is_code:
                        doc_out.append(textwrap.dedent(latex_text['code_header']))
                        doc_out.append(textwrap.dedent(m.code))
                        doc_out.append(textwrap.dedent(latex_text['code_footer']))
                else:
                    doc_out = []
                    doc_out.append(m.name)
                    doc_out.append('-' * len(m.name))
                    
                    if not as_c_code and m.is_code:
                        doc_out.append(rst_text['code_header'])
                        doc_out.append('\n::\n')
                        doc_out.append(indent(m.code))
                
                state_name_title = 'Name'
                max_state_name_width = max(len(s.name) for s in m.states)
                max_state_name_width = max(max_state_name_width, len(state_name_title))
                state_name_header = (state_name_title, max_state_name_width)

                rate_key_order = (
                    'Pockels Cell',
                    'Mechanical Shutter',
                    'BYKIK',
                    'Laser Heater Shutter',
                )
                
                rate_width = max(len(h) for h in rate_key_order)

                if as_latex:
                    rate_headers = (
                        'PC',
                        'MS',
                        'BYKIK',
                        'LHS',
                    )
                else:
                    rate_headers = rate_key_order
                    
                rate_headers = zip(rate_headers, (rate_width,) * len(rate_headers))

                if m.is_code:
                    state_title = 'State'
                    state_width = len(state_title)
                    state_headers = [(state_title, state_width)]
                else:
                    if as_latex:
                        style = '${0}$'
                    else:
                        style = '{0}'
                    device_vars = [style.format(d['variable']) for d in m.devices]
                    device_vars.reverse()
                    state_headers = zip(device_vars, (1,) * len(device_vars))

                headers = []
                headers.append(state_name_header)
                headers.extend(state_headers)
                headers.extend(rate_headers)
                
                if as_latex:
                    doc_out.append(
                        textwrap.dedent(
                            r'''
                            \begin{{center}}
                            \begin{{tabular}}{{@{{}}l{align}@{{}}}}
                            \toprule
                            {h} \\
                            \midrule
                            '''.format(
                                align='c' * (len(headers) - 1),
                                h=' & '.join(h[0] for h in headers)
                            )
                        )
                    )
                else:
                    table_rules = ' '.join('=' * h[1] for h in headers)
                    table_headers = ' '.join('{0[0]:^{0[1]}}'.format(h) for h in headers)
        
                    doc_out.append(table_rules)
                    doc_out.append(table_headers)
                    doc_out.append(table_rules)
                
                if as_c_code:
                    c_state_out = []

                for s in m.states:
                    state_out = []
                    rate_string = {}
                    
                    if as_latex:
                        enum_to_str = _rate_latex_string
                    else:
                        enum_to_str = _rate_rst_string
                        
                    for k, v in s.rates.iteritems():
                        rate_string[k] = enum_to_str[v]
                    
                    if as_latex:
                        escape = latex_escape
                    else:
                        escape = lambda x: x
                    
                    state_out.append('{0:{1}}'.format(escape(s.name), max_state_name_width))
                    if m.is_code:
                        state_out.append('{0:>{1}}'.format(s.number, state_width))
                    else:
                        for i in xrange(len(m.devices), 0, -1):
                            state_out.append('T' if s.number & (0x01 << (i - 1)) else 'F')
                    
                    for key in rate_key_order:
                        state_out.append('{0:>{1}}'.format(rate_string[key], rate_width))
                    
                    if as_latex:
                        separator = ' & '
                    else:
                        separator = ' '
                    
                    if as_latex:
                        line_format = '{0} \\\\'
                    else:
                        line_format = '{0}'

                    doc_out.append(line_format.format(separator.join(state_out)))
                    
                    if as_c_code:
                        c_state_out.append('/* {0} */'.format(s.name))
                        if m.is_code:
                            c_state_out.append('case {0}:'.format(s.number))
                            if s.is_default:
                                c_state_out.append('default:')
                        else:
                            c_state_out.append('if {0}\n{{'.format(c_test(m, s)))
                        if g.get('is_ignore_logic'):
                            c_state_out.append(indent('setNewTruthTableState({0}, MPSTruthTableIgnoreIgnoring);'.format(self.macro_number[m.pk].macro_number, s.number), 4))
                            c_state_out.append('}\nelse\n{')
                            c_state_out.append(indent('setNewTruthTableState({0}, MPSTruthTableIgnoreNotIgnoring);'.format(self.macro_number[m.pk].macro_number, s.number), 4))
                        else:
                            for device in ('Pockels Cell', 'Mechanical Shutter', 'BYKIK', 'Laser Heater Shutter'):
                                if s.rates[device] > 0:
                                    c_code = indent(
                                        'setMaxRateAfterDevice({0}, {1});'.format(
                                            _rate_c_code_string[s.rates[device]],
                                            _mitigation_device_enum[device]
                                        ),
                                        4                                    
                                    )
                                    c_state_out.append(c_code)
                            c_state_out.append(indent('setNewTruthTableState({0}, {1});'.format(self.macro_number[m.pk].macro_number, s.number), 4))
                        if m.is_code:
                            c_state_out.append(indent('break;\n', 4))
                        else:
                            c_state_out.append('}\n')

                if as_latex:
                    doc_out.append(
                        textwrap.dedent(
                            r'''
                            \bottomrule
                            \end{tabular}
                            \end{center}
                            '''
                        )
                    )
                else:
                    doc_out.append(table_rules)
                
                if not m.is_code:
                    device_text = []                    
                    if as_latex:
                        where = r'Where\newline'
                        device_style = r'${0} = \texttt{{{1}}}$'
                        separator = ',\\newline\n'
                        escape = latex_escape
                    else:
                        where = '\nWhere::\n'
                        device_style = indent('{0} = {1}', 4)
                        separator = '\n'
                        escape = lambda x: x

                    for d in m.devices:
                        device_text.append(device_style.format(escape(d['variable']), escape(d['info'].name)))
                        
                    doc_out.append(where)
                    doc_out.append(separator.join(device_text))
                
                if as_c_code and m.is_code:
                    doc_out.append('')
                    doc_out.append(rst_text['code_header'])
                
                print >> out_file, indent(format_block(doc_out, as_c_code), indent_base)
                print >> out_file, ''
                if as_c_code:
                    if m.is_code:
                        print >> out_file, indent('state = (unsigned int) -1; /* Initialize to an unlikely state number */\n{', indent_base)
                        print >> out_file, indent(m.code, indent_base + 4)
                        print >> out_file, indent('}\nswitch(state)\n{', indent_base)
                        print >> out_file, indent(format_block(c_state_out), indent_base + 4)
                        print >> out_file, indent('}', indent_base)
                    else:
                        print >> out_file, indent(format_block(c_state_out), indent_base)
                print >> out_file, ''

            if as_c_code and 'ignore_macros' in g:
                print >> out_file, '}'
                print >> out_file, ''
            print >> out_file, ''
        if as_latex:
            print >> out_file, r'\end{document}'


def main(argv=None):
    
    keys = ('path',)
    args = dict(zip(keys, argv))
    
    logic = Logic(args['path'])
    
    logic.export_rst()
    logic.export_c_code(as_c_code=True)
    logic.export_latex(as_latex=True)

    return 0

    
if __name__ == "__main__":
    argv = sys.argv[1:]
    if not argv:
        argv = ['MpsLogic.mpl']

    status = main(argv)
    sys.exit(status)
