#!/usr/bin/env python

import sys
import os
import string
import sqlite3

from . import mpsconfigquery
from . import format

def export(cursor, path, verbose):
    """
    Write substitution files to the folder specified by path
    """

    colsep   = "  , "
    colWidth = {}

    column_len = format.max_column_lengths(cursor)
    colWidth['PORT']            = max(len('PORT'),          36                               )
    colWidth['DEVICETYPE']      = max(len('DEVICETYPE'),    column_len['pv_device_type']     )
    colWidth['AREA']            = max(len('AREA'),          column_len['pv_area']            )
    colWidth['POSITION']        = max(len('POSITION'),      column_len['pv_position']        )
    colWidth['FAULTNUM']        = max(len('FAULTNUM'),      column_len['fault_number']       )
    colWidth['ZNAM']            = max(len('ZNAM'),          column_len['faulted_state_name'] )
    colWidth['ONAM']            = max(len('ONAM'),          column_len['ok_state_name']      )
    colWidth['DESC']            = max(len('DESC'),          column_len['device_name']        )
    colWidth['INDEX']           = max(len('INDEX'),         8                                )
    
    #
    # MPS Input State Buffers
    #

    file_path = os.path.join(path, 'mpsBufferStatus.substitutions')

    if verbose:
        print "Exporting MPS Buffer Status substitutions file to", file_path
    
    try:
        outfile = open(file_path, "w")
    except IOError, e:
        sys.stderr.write('Could not open "%s": %s\n' % (file_path, e.strerror))
        return 1
    
            
    ports = (
                #
                # Link Processor Faults
                #
                {
                    'query'             : mpsconfigquery.link_processor_faults + ' order by fault_number',
                    'template'          : "mpsBufferStatus.template",
                    'comment'           : '=' * 60 + "\n# Link Processor Fault Current Status",
                    'prefix'            : "",
                    'suffix'            : "_MPSC",
                    'portName'          : "devMpsStatusBufferReadback",
                    'nonDbStateNames'   : False
                },
                {
                    'query'             : mpsconfigquery.link_processor_faults + ' order by fault_number',
                    'template'          : "mpsBufferStatus.template",
                    'comment'           : '=' * 60 + "\n# Link Processor Fault Latched Status",
                    'prefix'            : "",
                    'suffix'            : "_MPS",
                    'portName'          : "devMpsLatchedBufferReadback",
                    'nonDbStateNames'   : False
                },
                {
                    'query'             : mpsconfigquery.link_processor_faults + ' order by fault_number',
                    'template'          : "mpsBypassStatus.template",
                    'comment'           : "Link Processor Fault Bypass Active State",
                    'prefix'            : "",
                    'suffix'            : "_BYPS",
                    'portName'          : "devMpsBypassActiveBufferReadback",
                    'nonDbStateNames'   : True,
                    'znam'              : '"Not Bypassed"',
                    'onam'              : "Bypassed"
                },
                #
                # External EPICS Faults
                #
                {
                    'query'             : mpsconfigquery.epics_faults + ' order by fault_number',
                    'template'          : "mpsBufferStatus.template",
                    'comment'           : '=' * 60 + "\n# External EPICS Fault Current Status",
                    'prefix'            : "",
                    'suffix'            : "_MPSC",
                    'portName'          : "devMpsStatusBufferReadback",
                    'nonDbStateNames'   : False
                },
                {
                    'query'             : mpsconfigquery.epics_faults + ' order by fault_number',
                    'template'          : "mpsBufferStatus.template",
                    'comment'           : '=' * 60 + "\n# External EPICS Fault Latched Status",
                    'prefix'            : "",
                    'suffix'            : "_MPS",
                    'portName'          : "devMpsLatchedBufferReadback",
                    'nonDbStateNames'   : False
                },
                {
                    'query'             : mpsconfigquery.epics_faults + ' order by fault_number',
                    'template'          : "mpsBypassStatus.template",
                    'comment'           : "External EPICS Fault Bypass Active State",
                    'prefix'            : "",
                    'suffix'            : "_BYPS",
                    'portName'          : "devMpsBypassActiveBufferReadback",
                    'nonDbStateNames'   : True,
                    'znam'              : '"Not Bypassed"',
                    'onam'              : "Bypassed"
                },
                #
                # Link Node Faults
                #
                {
                    'query'             : mpsconfigquery.link_node_faults + ' order by fault_number',
                    'template'          : "mpsBufferStatus.template",
                    'comment'           : '=' * 60 + "\n# Link Node Fault Current Status",
                    'prefix'            : "",
                    'suffix'            : "_MPSC",
                    'portName'          : "devMpsStatusBufferReadback",
                    'nonDbStateNames'   : False,
                    'isLinkNodeFault'   : True
                },
                {
                    'query'             : mpsconfigquery.link_node_faults + ' order by fault_number',
                    'template'          : "mpsBufferStatus.template",
                    'comment'           : '=' * 60 + "\n# Link Node Fault Latched Status",
                    'prefix'            : "",
                    'suffix'            : "_MPS",
                    'portName'          : "devMpsLatchedBufferReadback",
                    'nonDbStateNames'   : False,
                    'isLinkNodeFault'   : True
                },
                {
                    'query'             : mpsconfigquery.link_node_faults + ' order by fault_number',
                    'template'          : "mpsBypassStatus.template",
                    'comment'           : "Link Node Fault Bypass Active State",
                    'prefix'            : "",
                    'suffix'            : "_BYPS",
                    'portName'          : "devMpsBypassActiveBufferReadback",
                    'nonDbStateNames'   : True,
                    'znam'              : '"Not Bypassed"',
                    'onam'              : "Bypassed",
                    'isLinkNodeFault'   : True
                },
                #
                # Link Node Channel Faults
                #
                {
                    'query'             : mpsconfigquery.link_node_channel_faults + ' order by fault_number',
                    'template'          : "mpsBufferStatus.template",
                    'comment'           : '=' * 60 + "\n# Link Node Channel Fault Current Status",
                    'prefix'            : "",
                    'suffix'            : "_MPSC",
                    'portName'          : "devMpsStatusBufferReadback",
                    'nonDbStateNames'   : False
                },
                {
                    'query'             : mpsconfigquery.link_node_channel_faults + ' order by fault_number',
                    'template'          : "mpsBufferStatus.template",
                    'comment'           : '=' * 60 + "\n# Link Node Channel Fault Latched Status",
                    'prefix'            : "",
                    'suffix'            : "_MPS",
                    'portName'          : "devMpsLatchedBufferReadback",
                    'nonDbStateNames'   : False
                },
                {
                    'query'             : mpsconfigquery.link_node_channel_faults + ' order by fault_number',
                    'template'          : "mpsBypassStatus.template",
                    'comment'           : "Link Node Channel Fault Bypass Active State",
                    'prefix'            : "",
                    'suffix'            : "_BYPS",
                    'portName'          : "devMpsBypassActiveBufferReadback",
                    'nonDbStateNames'   : True,
                    'znam'              : '"Not Bypassed"',
                    'onam'              : "Bypassed"
                }
            )
    
    for port in ports:
        if verbose:
            print 'Exporting port {port[portName]} with template {port[template]}'.format(port=port)

        colWidth['ATTRIBUTE']   = max(len('ATTRIBUTE'),     column_len['pv_attribute'] + len(port['prefix']) + len(port['suffix']) + len("_LN") + 3)

        print >> outfile, "\n\n"
        print >> outfile, "#"
        print >> outfile, "#", port['comment']
        print >> outfile, "#"

        print >> outfile, "file", port['template']
            
        print >> outfile, "{"
        print >> outfile, "    pattern { ",
        print >> outfile, "PORT"          .ljust(     colWidth['PORT']         ) + colsep,
        print >> outfile, "DEVICETYPE"    .ljust(     colWidth['DEVICETYPE']   ) + colsep,
        print >> outfile, "AREA"          .ljust(     colWidth['AREA']         ) + colsep,
        print >> outfile, "POSITION"      .ljust(     colWidth['POSITION']     ) + colsep,
        print >> outfile, "ATTRIBUTE"     .rjust(     colWidth['ATTRIBUTE']    ) + colsep,
        print >> outfile, "DESC"          .ljust(     colWidth['DESC']         ) + colsep,
        print >> outfile, "ZNAM"          .ljust(     colWidth['ZNAM']         ) + colsep,
        print >> outfile, "ONAM"          .ljust(     colWidth['ONAM']         ) + colsep,
        print >> outfile, "FAULTNUM"      .ljust(     colWidth['FAULTNUM']     )         ,
        print >> outfile, " }"
        
        cursor.execute(port['query'])
        for row in cursor:
            if port.get('isLinkNodeFault'):
                attribute = port['prefix'] + row['pv_attribute'] + "_LN%d" % row['link_node_id'] + port['suffix']
            else:
                try:
                    attribute = port['prefix'] + row['pv_attribute'] + port['suffix']
                except TypeError:
                    print "(Prefix, PV Attribute, Suffix) = (", port['prefix'], row['pv_attribute'], port['suffix'], ")"
                    sys.exit(1)
                                
            print >> outfile, "            { ",

            print >> outfile, port['portName']              .ljust(     colWidth['PORT']       )  + colsep,
            print >> outfile, row['pv_device_type']         .ljust(     colWidth['DEVICETYPE'] )  + colsep,
            print >> outfile, row['pv_area']                .ljust(     colWidth['AREA']       )  + colsep,
            print >> outfile, row['pv_position']            .rjust(     colWidth['POSITION']   )  + colsep,
            print >> outfile, attribute                     .rjust(     colWidth['ATTRIBUTE']  )  + colsep,
            print >> outfile, row['device_name']            .ljust(     colWidth['DESC']       )  + colsep,
            if port['nonDbStateNames']:
                print >> outfile, port['znam']              .ljust(     colWidth['ZNAM']       )  + colsep,
                print >> outfile, port['onam']              .ljust(     colWidth['ONAM']       )  + colsep,
            else:
                print >> outfile, row['faulted_state_name'] .ljust(     colWidth['ZNAM']       )  + colsep,
                print >> outfile, row['ok_state_name']      .ljust(     colWidth['ONAM']       )  + colsep,
            print >> outfile, str(row['fault_number'])      .ljust(     colWidth['FAULTNUM']   )          ,

            print >> outfile, " }"

        print >> outfile, "}\n\n"

    outfile.close()


    #
    # MPS Input State Buffer Control
    #

    file_path = os.path.join(path, 'mpsBufferControl.substitutions')

    if verbose:
        print "Exporting MPS Buffer Control substitutions file to", file_path
    
    try:
        outfile = open(file_path, "w")
    except IOError, e:
        sys.stderr.write('Could not open "%s": %s\n' % (file_path, e.strerror))
        return 1
    
            
    ports = (
                #
                # Link Processor Faults
                #
                {
                    'query'             : mpsconfigquery.link_processor_faults + ' order by fault_number',
                    'template'          : "mpsBufferControl.template",
                    'comment'           : '=' * 60 + "\n# Link Processor Fault Bypass Value",
                    'prefix'            : "",
                    'suffix'            : "_BYPV",
                    'portName'          : "devMpsBypassValueBufferControl"
                },
                #
                # External EPICS Faults
                #
                {
                    'query'             : mpsconfigquery.epics_faults + ' order by fault_number',
                    'template'          : "mpsBufferControl.template",
                    'comment'           : '=' * 60 + "\n# External EPICS Fault Bypass Value",
                    'prefix'            : "",
                    'suffix'            : "_BYPV",
                    'portName'          : "devMpsBypassValueBufferControl"
                },
                #
                # Link Node Faults
                #
                {
                    'query'             : mpsconfigquery.link_node_faults + ' order by fault_number',
                    'template'          : "mpsBufferControl.template",
                    'comment'           : '=' * 60 + "\n# Link Node Fault Bypass Value",
                    'prefix'            : "",
                    'suffix'            : "_BYPV",
                    'portName'          : "devMpsBypassValueBufferControl"
                },
                #
                # Link Node Channel Faults
                #
                {
                    'query'             : mpsconfigquery.link_node_channel_faults + ' order by fault_number',
                    'template'          : "mpsBufferControl.template",
                    'comment'           : '=' * 60 + "\n# Link Node Channel Fault Bypass Value",
                    'prefix'            : "",
                    'suffix'            : "_BYPV",
                    'portName'          : "devMpsBypassValueBufferControl"
                }
            )
    
    column_len = format.max_column_lengths(cursor)
    colWidth['PORT']            = max(len('PORT'),          32                                  )
    colWidth['DEVICETYPE']      = max(len('DEVICETYPE'),    column_len['pv_device_type']     )
    colWidth['AREA']            = max(len('AREA'),          column_len['pv_area']            )
    colWidth['POSITION']        = max(len('POSITION'),      column_len['pv_position']        )
    colWidth['FAULTNUM']        = max(len('FAULTNUM'),      column_len['fault_number']       )
    colWidth['ZNAM']            = max(len('ZNAM'),          column_len['faulted_state_name'] )
    colWidth['ONAM']            = max(len('ONAM'),          column_len['ok_state_name']      )
    colWidth['DESC']            = max(len('DESC'),          column_len['device_name']        )
    colWidth['INDEX']           = max(len('INDEX'),         8                                   )

    for port in ports:
        colWidth['ATTRIBUTE']   = max(len('ATTRIBUTE'),     column_len['pv_attribute'] + len(port['prefix']) + len(port['suffix']) + len("_LN") + 3)

        print >> outfile, "\n\n"
        print >> outfile, "#"
        print >> outfile, "#",  port['comment']
        print >> outfile, "#"

        print >> outfile, "file " + port['template']
            
        print >> outfile, "{"
        print >> outfile, "    pattern { ",
        print >> outfile, "PORT"          .ljust(     colWidth['PORT']         ) + colsep,
        print >> outfile, "DEVICETYPE"    .ljust(     colWidth['DEVICETYPE']   ) + colsep,
        print >> outfile, "AREA"          .ljust(     colWidth['AREA']         ) + colsep,
        print >> outfile, "POSITION"      .ljust(     colWidth['POSITION']     ) + colsep,
        print >> outfile, "ATTRIBUTE"     .rjust(     colWidth['ATTRIBUTE']    ) + colsep,
        print >> outfile, "DESC"          .ljust(     colWidth['DESC']         ) + colsep,
        print >> outfile, "ZNAM"          .ljust(     colWidth['ZNAM']         ) + colsep,
        print >> outfile, "ONAM"          .ljust(     colWidth['ONAM']         ) + colsep,
        print >> outfile, "FAULTNUM"      .ljust(     colWidth['FAULTNUM']     )         ,
        print >> outfile, " }"
        
        cursor.execute(port['query'])
        for row in cursor:
            if port.get('isLinkNodeFault'):
                attribute = port['prefix'] + row['pv_attribute'] + "_LN%d" % row['link_node_id'] + port['suffix']
            else:
                attribute = port['prefix'] + row['pv_attribute'] + port['suffix']
                
            print >> outfile, "            { ",

            print >> outfile, port['portName']              .ljust(     colWidth['PORT']       )  + colsep,
            print >> outfile, row['pv_device_type']         .ljust(     colWidth['DEVICETYPE'] )  + colsep,
            print >> outfile, row['pv_area']                .ljust(     colWidth['AREA']       )  + colsep,
            print >> outfile, row['pv_position']            .rjust(     colWidth['POSITION']   )  + colsep,
            print >> outfile, attribute                     .rjust(     colWidth['ATTRIBUTE']  )  + colsep,
            print >> outfile, row['device_name']            .ljust(     colWidth['DESC']       )  + colsep,
            print >> outfile, row['faulted_state_name']     .ljust(     colWidth['ZNAM']       )  + colsep,
            print >> outfile, row['ok_state_name']          .ljust(     colWidth['ONAM']       )  + colsep,
            print >> outfile, str(row['fault_number'])      .ljust(     colWidth['FAULTNUM']   )          ,

            print >> outfile, " }"

        print >> outfile, "}\n\n"

    outfile.close()




    #
    # MPS Unlatch Control
    #

    file_path = os.path.join(path, 'mpsUnlatchControl.substitutions')

    if verbose:
        print "Exporting MPS Unlatch Control substitutions file to", file_path
    
    try:
        outfile = open(file_path, "w")
    except IOError, e:
        sys.stderr.write('Could not open "%s": %s\n' % (file_path, e.strerror))
        return 1
    
            
    ports = (
                #
                # Link Processor Faults
                #
                {
                    'query'             : mpsconfigquery.link_processor_faults + ' order by fault_number',
                    'template'          : "mpsUnlatchControl.template",
                    'comment'           : '=' * 60 + "\n# Link Processor Fault Unlatch",
                    'prefix'            : "",
                    'suffix'            : "_UNLH",
                    'portName'          : "devMpsUnlatchBufferControl"
                },
                #
                # External EPICS Faults
                #
                {
                    'query'             : mpsconfigquery.epics_faults + ' order by fault_number',
                    'template'          : "mpsUnlatchControl.template",
                    'comment'           : '=' * 60 + "\n# External EPICS Fault Unlatch",
                    'prefix'            : "",
                    'suffix'            : "_UNLH",
                    'portName'          : "devMpsUnlatchBufferControl"
                },
                #
                # Link Node Faults
                #
                {
                    'query'             : mpsconfigquery.link_node_faults + ' order by fault_number',
                    'template'          : "mpsUnlatchControl.template",
                    'comment'           : '=' * 60 + "\n# Link Node Fault Unlatch",
                    'prefix'            : "",
                    'suffix'            : "_UNLH",
                    'portName'          : "devMpsUnlatchBufferControl"
                },
                #
                # Link Node Channel Faults
                #
                {
                    'query'             : mpsconfigquery.link_node_channel_faults + ' order by fault_number',
                    'template'          : "mpsUnlatchControl.template",
                    'comment'           : '=' * 60 + "\n# Link Node Channel Fault Unlatch",
                    'prefix'            : "",
                    'suffix'            : "_UNLH",
                    'portName'          : "devMpsUnlatchBufferControl"
                }
            )
    
    unlatchZnam = "No"
    unlatchOnam = "Yes"

    column_len = format.max_column_lengths(cursor)
    colWidth['PORT']            = max(len('PORT'),        32                           )
    colWidth['DEVICETYPE']      = max(len('DEVICETYPE'),  column_len['pv_device_type'] )
    colWidth['AREA']            = max(len('AREA'),        column_len['pv_area']        )
    colWidth['POSITION']        = max(len('POSITION'),    column_len['pv_position']    )
    colWidth['FAULTNUM']        = max(len('FAULTNUM'),    column_len['fault_number']   )
    colWidth['ZNAM']            = max(len('ZNAM'),        len(unlatchZnam)             )
    colWidth['ONAM']            = max(len('ONAM'),        len(unlatchOnam)             )
    colWidth['DESC']            = max(len('DESC'),        column_len['device_name']    )
    colWidth['INDEX']           = max(len('INDEX'),       8                            )

    for port in ports:
        colWidth['ATTRIBUTE']   = max(len('ATTRIBUTE'),     column_len['pv_attribute'] + len(port['prefix']) + len(port['suffix']) + len("_LN") + 3)

        print >> outfile, "\n\n"
        print >> outfile, "#"
        print >> outfile, "#",  port['comment']
        print >> outfile, "#"

        print >> outfile, "file " + port['template']
            
        print >> outfile, "{"
        print >> outfile, "    pattern { ",
        print >> outfile, "PORT"          .ljust(     colWidth['PORT']         ) + colsep,
        print >> outfile, "DEVICETYPE"    .ljust(     colWidth['DEVICETYPE']   ) + colsep,
        print >> outfile, "AREA"          .ljust(     colWidth['AREA']         ) + colsep,
        print >> outfile, "POSITION"      .ljust(     colWidth['POSITION']     ) + colsep,
        print >> outfile, "ATTRIBUTE"     .rjust(     colWidth['ATTRIBUTE']    ) + colsep,
        print >> outfile, "DESC"          .ljust(     colWidth['DESC']         ) + colsep,
        print >> outfile, "ZNAM"          .ljust(     colWidth['ZNAM']         ) + colsep,
        print >> outfile, "ONAM"          .ljust(     colWidth['ONAM']         ) + colsep,
        print >> outfile, "FAULTNUM"      .ljust(     colWidth['FAULTNUM']     )         ,
        print >> outfile, " }"
        
        cursor.execute(port['query'])
        for row in cursor:
            if port.get('isLinkNodeFault'):
                attribute = port['prefix'] + row['pv_attribute'] + "_LN%d" % row['link_node_id'] + port['suffix']
            else:
                attribute = port['prefix'] + row['pv_attribute'] + port['suffix']
                
            print >> outfile, "            { ",

            print >> outfile, port['portName']              .ljust(     colWidth['PORT']       )  + colsep,
            print >> outfile, row['pv_device_type']         .ljust(     colWidth['DEVICETYPE'] )  + colsep,
            print >> outfile, row['pv_area']                .ljust(     colWidth['AREA']       )  + colsep,
            print >> outfile, row['pv_position']            .rjust(     colWidth['POSITION']   )  + colsep,
            print >> outfile, attribute                     .rjust(     colWidth['ATTRIBUTE']  )  + colsep,
            print >> outfile, row['device_name']            .ljust(     colWidth['DESC']       )  + colsep,
            print >> outfile, unlatchZnam                   .ljust(     colWidth['ZNAM']       )  + colsep,
            print >> outfile, unlatchOnam                   .ljust(     colWidth['ONAM']       )  + colsep,
            print >> outfile, str(row['fault_number'])      .ljust(     colWidth['FAULTNUM']   )          ,

            print >> outfile, " }"

        print >> outfile, "}\n\n"

    outfile.close()





    #
    # MPS Bypass Times
    #
    file_path = os.path.join(path, 'mpsBypassControl.substitutions')

    if verbose:
        print "Exporting MPS Bypass Control substitutions file to", file_path
    
    try:
        outfile = open(file_path, "w")
    except IOError, e:
        sys.stderr.write('Could not open "%s": %s\n' % (file_path, e.strerror))
        return 1
    
    ports = (
                {
                    'query'             : mpsconfigquery.link_processor_faults + ' order by device_name, fault_name',
                    'template'          : "mpsBypassControl.template",
                    'comment'           : "Bypass Control",
                    'prefix'            : "",
                    'suffix'            : "_BYPC"
                },
                {
                    'query'             : mpsconfigquery.epics_faults + ' order by device_name, fault_name',
                    'template'          : "mpsBypassControl.template",
                    'comment'           : "Bypass Control",
                    'prefix'            : "",
                    'suffix'            : "_BYPC"
                },
                {
                    'query'             : mpsconfigquery.link_node_faults + ' order by link_node_id, device_name, fault_name',
                    'template'          : "mpsBypassControl.template",
                    'comment'           : "Bypass Control",
                    'prefix'            : "",
                    'suffix'            : "_BYPC"
                },
                {
                    'query'             : mpsconfigquery.link_node_channel_faults + ' order by link_node_id, card, channel',
                    'template'          : "mpsBypassControl.template",
                    'comment'           : "Bypass Control",
                    'prefix'            : "",
                    'suffix'            : "_BYPC"
                },
            )

    for port in ports:
        colWidth['ATTRIBUTE']   = max(len('ATTRIBUTE'),     column_len['pv_attribute'] + len(port['prefix']) + len(port['suffix']))

        print >> outfile, "\n\n"
        print >> outfile, "#" + "-" * (len(port['comment']) + 15)
        print >> outfile, "#",  port['comment']
        print >> outfile, "#" + "-" * (len(port['comment']) + 15)
        print >> outfile, ""

        print >> outfile, "file " + port['template']
            
        print >> outfile, "{"
        print >> outfile, "    pattern { ",
        print >> outfile, "DEVICETYPE"    .ljust(     colWidth['DEVICETYPE']   ) + colsep,
        print >> outfile, "AREA"          .ljust(     colWidth['AREA']         ) + colsep,
        print >> outfile, "POSITION"      .ljust(     colWidth['POSITION']     ) + colsep,
        print >> outfile, "ATTRIBUTE"     .rjust(     colWidth['ATTRIBUTE']    ) + colsep,
        print >> outfile, "DESC"          .ljust(     colWidth['DESC']         ) + colsep,
        print >> outfile, "FAULTNUM"      .ljust(     colWidth['FAULTNUM']     )         ,
        print >> outfile, " }"
        
        cursor.execute(port['query'])
        for row in cursor:
            if port.get('isLinkNodeFault'):
                attribute = port['prefix'] + row['pv_attribute'] + "_LN%d" % row['link_node_id'] + port['suffix']
            else:
                attribute = port['prefix'] + row['pv_attribute'] + port['suffix']

            print >> outfile, "            { ",
            print >> outfile, row['pv_device_type']            .ljust(     colWidth['DEVICETYPE'] )  + colsep,
            print >> outfile, row['pv_area']                   .ljust(     colWidth['AREA']       )  + colsep,
            print >> outfile, row['pv_position']               .rjust(     colWidth['POSITION']   )  + colsep,
            print >> outfile, attribute                        .rjust(     colWidth['ATTRIBUTE']  )  + colsep,
            print >> outfile, row['device_name']               .ljust(     colWidth['DESC']       )  + colsep,            
            print >> outfile, str(row['fault_number'])         .rjust(     colWidth['FAULTNUM']   )          ,
            print >> outfile, " }"

        print >> outfile, "}\n\n"

    outfile.close()


    #
    # MPS Bypass Array Readback
    #
    file_path = os.path.join(path, 'mpsBypassReadbackArray.substitutions')

    if verbose:
        print "Exporting MPS Bypass Array Readback substitutions file to", file_path
    
    try:
        outfile = open(file_path, "w")
    except IOError, e:
        sys.stderr.write('Could not open "%s": %s\n' % (file_path, e.strerror))
        return 1
    

    try:
        cursor.execute(mpsconfigquery.fault_count)
        results = cursor.fetchone()
    except sqlite3.Error, e:
        print "export_snl_program:", e.args[0]
        sys.exit(1)

    numberOfFaults = results['count']

    print >> outfile, "\n\n"
    print >> outfile, "#" + "-" * (60)
    print >> outfile, "# MPS Bypass Array Readback"
    print >> outfile, "#" + "-" * (60)
    print >> outfile, ""

    print >> outfile, "file mpsBypassReadbackArray.template"
        
    print >> outfile, "{"
    print >> outfile, "    pattern { ",
    print >> outfile, "EVNTNUM"         .rjust(     len("EVNTNUM")        ) + colsep,
    print >> outfile, "FAULTCOUNT"      .rjust(     len("FAULTCOUNT")     )         ,
    print >> outfile, " }"
    
    print >> outfile, "            { ",
    print >> outfile, "101"                     .rjust(     len("EVNTNUM")      )  + colsep,
    print >> outfile, str(numberOfFaults)       .rjust(     len("FAULTCOUNT")   )          ,
    print >> outfile, " }"

    print >> outfile, "}\n\n"

    outfile.close()
            

