#!/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 as 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("\n\n", file=outfile)
        print("#", file=outfile)
        print("#", port['comment'], file=outfile)
        print("#", file=outfile)

        print("file", port['template'], file=outfile)
            
        print("{", file=outfile)
        print("    pattern { ", file=outfile)
        print("PORT"          .ljust(     colWidth['PORT']         ) + colsep, file=outfile)
        print("DEVICETYPE"    .ljust(     colWidth['DEVICETYPE']   ) + colsep, file=outfile)
        print("AREA"          .ljust(     colWidth['AREA']         ) + colsep, file=outfile)
        print("POSITION"      .ljust(     colWidth['POSITION']     ) + colsep, file=outfile)
        print("ATTRIBUTE"     .rjust(     colWidth['ATTRIBUTE']    ) + colsep, file=outfile)
        print("DESC"          .ljust(     colWidth['DESC']         ) + colsep, file=outfile)
        print("ZNAM"          .ljust(     colWidth['ZNAM']         ) + colsep, file=outfile)
        print("ONAM"          .ljust(     colWidth['ONAM']         ) + colsep, file=outfile)
        print("FAULTNUM"      .ljust(     colWidth['FAULTNUM']     )         , file=outfile)
        print(" }", file=outfile)
        
        try:
            cursor.execute(port['query'])
        except Exception as e:
            print(e)
        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("            { ", file=outfile)

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

            print(" }", file=outfile)

        print("}\n\n", file=outfile)

    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 as 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("\n\n", file=outfile)
        print("#", file=outfile)
        print("#",  port['comment'], file=outfile)
        print("#", file=outfile)

        print("file " + port['template'], file=outfile)
            
        print("{", file=outfile)
        print("    pattern { ", file=outfile)
        print("PORT"          .ljust(     colWidth['PORT']         ) + colsep, file=outfile)
        print("DEVICETYPE"    .ljust(     colWidth['DEVICETYPE']   ) + colsep, file=outfile)
        print("AREA"          .ljust(     colWidth['AREA']         ) + colsep, file=outfile)
        print("POSITION"      .ljust(     colWidth['POSITION']     ) + colsep, file=outfile)
        print("ATTRIBUTE"     .rjust(     colWidth['ATTRIBUTE']    ) + colsep, file=outfile)
        print("DESC"          .ljust(     colWidth['DESC']         ) + colsep, file=outfile)
        print("ZNAM"          .ljust(     colWidth['ZNAM']         ) + colsep, file=outfile)
        print("ONAM"          .ljust(     colWidth['ONAM']         ) + colsep, file=outfile)
        print("FAULTNUM"      .ljust(     colWidth['FAULTNUM']     )         , file=outfile)
        print(" }", file=outfile)
        try:
            cursor.execute(port['query'])
        except Exception as e:
            print(e)
        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("            { ", file=outfile)

            print(port['portName']              .ljust(     colWidth['PORT']       )  + colsep, file=outfile)
            print(row['pv_device_type']         .ljust(     colWidth['DEVICETYPE'] )  + colsep, file=outfile)
            print(row['pv_area']                .ljust(     colWidth['AREA']       )  + colsep, file=outfile)
            print(row['pv_position']            .rjust(     colWidth['POSITION']   )  + colsep, file=outfile)
            print(attribute                     .rjust(     colWidth['ATTRIBUTE']  )  + colsep, file=outfile)
            print(row['device_name']            .ljust(     colWidth['DESC']       )  + colsep, file=outfile)
            if isinstance(row['faulted_state_name'], bytes):
                temp = row['faulted_state_name'].decode('utf-8')
                print(temp .ljust(     colWidth['ZNAM']       )  + colsep, file=outfile)
            else:
                print(row['faulted_state_name'] .ljust(     colWidth['ZNAM']       )  + colsep, file=outfile)
            if isinstance(row['faulted_state_name'], bytes):
                temp = row['ok_state_name'].decode('utf-8')
                print(temp .ljust(     colWidth['ONAM']       )  + colsep, file=outfile)
            else:
                print(row['ok_state_name'] .ljust(     colWidth['ONAM']       )  + colsep, file=outfile)
            print(str(row['fault_number'])      .ljust(     colWidth['FAULTNUM']   )          , file=outfile)

            print(" }", file=outfile)

        print("}\n\n", file=outfile)

    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 as 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("\n\n", file=outfile)
        print("#", file=outfile)
        print("#",  port['comment'], file=outfile)
        print("#", file=outfile)

        print("file " + port['template'], file=outfile)
            
        print("{", file=outfile)
        print("    pattern { ", file=outfile)
        print("PORT"          .ljust(     colWidth['PORT']         ) + colsep, file=outfile)
        print("DEVICETYPE"    .ljust(     colWidth['DEVICETYPE']   ) + colsep, file=outfile)
        print("AREA"          .ljust(     colWidth['AREA']         ) + colsep, file=outfile)
        print("POSITION"      .ljust(     colWidth['POSITION']     ) + colsep, file=outfile)
        print("ATTRIBUTE"     .rjust(     colWidth['ATTRIBUTE']    ) + colsep, file=outfile)
        print("DESC"          .ljust(     colWidth['DESC']         ) + colsep, file=outfile)
        print("ZNAM"          .ljust(     colWidth['ZNAM']         ) + colsep, file=outfile)
        print("ONAM"          .ljust(     colWidth['ONAM']         ) + colsep, file=outfile)
        print("FAULTNUM"      .ljust(     colWidth['FAULTNUM']     )         , file=outfile)
        print(" }", file=outfile)
        
        try:
            cursor.execute(port['query'])
        except Exception as e:
            print(e)

        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("            { ", file=outfile)

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

            print(" }", file=outfile)

        print("}\n\n", file=outfile)

    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 as 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("\n\n", file=outfile)
        print("#" + "-" * (len(port['comment']) + 15), file=outfile)
        print("#",  port['comment'], file=outfile)
        print("#" + "-" * (len(port['comment']) + 15), file=outfile)
        print("", file=outfile)

        print("file " + port['template'], file=outfile)
            
        print("{", file=outfile)
        print("    pattern { ", file=outfile)
        print("DEVICETYPE"    .ljust(     colWidth['DEVICETYPE']   ) + colsep, file=outfile)
        print("AREA"          .ljust(     colWidth['AREA']         ) + colsep, file=outfile)
        print("POSITION"      .ljust(     colWidth['POSITION']     ) + colsep, file=outfile)
        print("ATTRIBUTE"     .rjust(     colWidth['ATTRIBUTE']    ) + colsep, file=outfile)
        print("DESC"          .ljust(     colWidth['DESC']         ) + colsep, file=outfile)
        print("FAULTNUM"      .ljust(     colWidth['FAULTNUM']     )         , file=outfile)
        print(" }", file=outfile)
        try:
            cursor.execute(port['query'])
        except Exception as e:
            print(e)
        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("            { ", file=outfile)
            print(row['pv_device_type']            .ljust(     colWidth['DEVICETYPE'] )  + colsep, file=outfile)
            print(row['pv_area']                   .ljust(     colWidth['AREA']       )  + colsep, file=outfile)
            print(row['pv_position']               .rjust(     colWidth['POSITION']   )  + colsep, file=outfile)
            print(attribute                        .rjust(     colWidth['ATTRIBUTE']  )  + colsep, file=outfile)
            print(row['device_name']               .ljust(     colWidth['DESC']       )  + colsep, file=outfile)
            print(str(row['fault_number'])         .rjust(     colWidth['FAULTNUM']   )          , file=outfile)
            print(" }", file=outfile)

        print("}\n\n", file=outfile)

    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 as 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 as e:
        print("export_snl_program:", e.args[0])
        sys.exit(1)

    numberOfFaults = results['count']

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

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

    print("}\n\n", file=outfile)

    outfile.close()
            

