# -*- coding: cp1252 -*-

# This is the code for handling the database connection and the populating of the Revision List.

# Import python standard modules (2.7)
import os
import sys
import types
import datetime
import _winreg
import getpass

# Import third party modules
import win32com.client as win32
import odbc
import dateutil.parser as dparser
import dateutil.relativedelta as rdelta
import numpy as np
import scipy.integrate as integrate
try:
    from osgeo import gdal
    from osgeo import ogr
except Exception, e:
    print 'failed to import gdal and/or gdal: ', e

# Import application-specific modules
from autoPermit_wdr import *
import ShapeLogic
from ap_connections import get_odbc_connection_string


# Set odbc connection strings by first trying to get them from ap_connections
try:
    WaterQuality = get_odbc_connection_string("WaterQuality")
except Exception, e:
    print e
    WaterQuality = "WaterQuality"

try:
    DMMESDEConnection = get_odbc_connection_string("DMMESDEConnection")
except Exception, e:
    print e
    DMMESDEConnection = "DMMESDEConnection"

try:
    Dmlr_DB = get_odbc_connection_string("Dmlr_DB")
except Exception, e:
    print e
    Dmlr_DB = "Dmlr_DB"



##try:
##    enviroList = ['GDAL','GDAL_DATA','GDAL_DRIVER_PATH']
##    y = str(os.getcwd())
##    for each in enviroList:
##        os.environ[each] = y
##except:
##    print 'failed setting enviro'




def WriteFileString(TS):
    try:
        fwrite = open('tempFile', 'w')
        fwrite.write(TS)
        fwrite.close()
    except:
        pass


def GetOrderedPermits(CurrentPermit):
    try:
        conn = odbc.odbc(Dmlr_DB)
    except:
        conn = odbc.odbc(Dmlr_DB)
    cursor = conn.cursor()  #cursor for dmlr database

    OrderedPermits = []
    searchpermit = CurrentPermit
    i = True
    while i:
        sqlSearch = str("select PeTransferFrom from DmlrPermits where PeNo = '" + str(searchpermit) + "'")
        cursor.execute(sqlSearch)
        result = cursor.fetchone()
        if type(result) is not types.NoneType:
            if len(result) > 0:
                OrderedPermits.append(str(result[0]))
                searchpermit = result[0]
            else:
                i = False
        else:
            i = False
    OrderedPermits.reverse()
    return OrderedPermits


def GOApps(PermitNo, OldPermitNoList):
    try:
        wqConn = odbc.odbc(WaterQuality)
        cursor = wqConn.cursor()
    except:
        wqConn = odbc.odbc(WaterQuality)
        cursor = wqConn.cursor()
    PreviousAppsList = []
    i = 0
    while i < len(OldPermitNoList):
        if OldPermitNoList[i].rstrip() != "" and str(OldPermitNoList[i]) != "None":
            sqlSearch = str("select SessionNo,AppNo from FinalPermitsTable where PermitNo = '" + str(
                OldPermitNoList[i]) + "' order by ABS(RecordNo) desc")
            cursor.execute(sqlSearch)
            result = cursor.fetchall()
            if type(result) is not types.NoneType:
                if len(result) > 0:
                    for each in result:
                        PreviousAppsList.append([each[1], each[0]])
        i += 1
    sqlSearch = str("select SessionNo,AppNo from FinalPermitsTable where PermitNo = '" + str(
        PermitNo) + "' order by ABS(RecordNo) desc")
    cursor.execute(sqlSearch)
    result = cursor.fetchall()
    if type(result) is not types.NoneType:
        if len(result) > 0:
            for each in result:
                PreviousAppsList.append([each[1], each[0]])
    return PreviousAppsList


def OrganizeOldSessions(AppNo, SessionNoInput):
    try:
        wqConn = odbc.odbc(WaterQuality)
        cursor = wqConn.cursor()
    except:
        wqConn = odbc.odbc(WaterQuality)
        cursor = wqConn.cursor()
    sqlSearch = str(
        "select LineageNo, OrderNo from SessionsTable where AppNo = '" + str(AppNo) + "' and SessionNo = '" + str(
            SessionNoInput) + "'")
    cursor.execute(sqlSearch)
    r = cursor.fetchone()
    LineageNo = r[0]
    OrderNo = r[1]
    sqlSearch = str(
        "select SessionNo,ParentNo from SessionsTable where AppNo = '" + str(AppNo) + "' and LineageNo = '" + str(
            LineageNo) + "' and ABS(OrderNo) <= ABS(" + str(OrderNo) + ") and ABS(SessionNo) <= ABS(" + str(
            SessionNoInput) + ") order by ABS(SessionNo) desc")
    cursor.execute(sqlSearch)
    result = cursor.fetchall()
    OrderedSessions = []
    OrderedSessions.append(SessionNoInput)
    searchSession = result[0][1]
    i = int(searchSession)
    while i > 0:
        for each in result:
            if each[0] == searchSession:
                OrderedSessions.append(each[0])
                searchSession = each[1]
                i = int(searchSession)
    return OrderedSessions


def MakeConnection():
    try:
        strKeyPath = "SOFTWARE\ODBC\ODBC.INI\ODBC Data Sources"
        odbckey = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, strKeyPath)
    except Exception as e:
        pass
    try:
        strValueName = "Dmlr_DB"
        strValue = "SQL Server"
        _winreg.SetValueEx(odbckey, strValueName, 0, _winreg.REG_SZ, strValue)
    except:
        pass
    try:
        strKeyPath = "SOFTWARE\ODBC\ODBC.INI\Dmlr_DB"
        valKey = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, strKeyPath)
        strValueName = "Database"
        strValue = "dmlr"
        _winreg.SetValueEx(valKey, strValueName, 0, _winreg.REG_SZ, strValue)
        strValueName = "Driver"
        strValue = "C:\WINDOWS\System32\SQLSRV32.dll"
        _winreg.SetValueEx(valKey, strValueName, 0, _winreg.REG_SZ, strValue)
        strValueName = "Server"
        strValue = "wsq00796"
        _winreg.SetValueEx(valKey, strValueName, 0, _winreg.REG_SZ, strValue)
        strValueName = "Trusted_Connection"
        strValue = "Yes"
        _winreg.SetValueEx(valKey, strValueName, 0, _winreg.REG_SZ, strValue)
    except:
        pass
    try:
        _winreg.CloseKey(valKey)
    except:
        pass
    try:
        strValueName = "DMMESDEConnection"
        strValue = "SQL Server"
        _winreg.SetValueEx(odbckey, strValueName, 0, _winreg.REG_SZ, strValue)
    except:
        pass
    try:
        strKeyPath = "SOFTWARE\ODBC\ODBC.INI\DMMESDEConnection"
        valKey = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, strKeyPath)
        strValueName = "Database"
        strValue = "Ep"
        _winreg.SetValueEx(valKey, strValueName, 0, _winreg.REG_SZ, strValue)
        strValueName = "Driver"
        strValue = "C:\WINDOWS\System32\SQLSRV32.dll"
        _winreg.SetValueEx(valKey, strValueName, 0, _winreg.REG_SZ, strValue)
        strValueName = "Server"
        strValue = "wsq00796"
        _winreg.SetValueEx(valKey, strValueName, 0, _winreg.REG_SZ, strValue)
        strValueName = "Trusted_Connection"
        strValue = "Yes"
        _winreg.SetValueEx(valKey, strValueName, 0, _winreg.REG_SZ, strValue)
    except:
        pass
    try:
        _winreg.CloseKey(valKey)
    except:
        pass
    try:
        strValueName = "WaterQuality"
        strValue = "SQL Server"
        _winreg.SetValueEx(odbckey, strValueName, 0, _winreg.REG_SZ, strValue)
    except:
        pass
    try:
        strKeyPath = "SOFTWARE\ODBC\ODBC.INI\WaterQuality"
        valKey = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, strKeyPath)
        strValueName = "Database"
        strValue = "WaterQuality"
        _winreg.SetValueEx(valKey, strValueName, 0, _winreg.REG_SZ, strValue)
        strValueName = "Driver"
        strValue = "C:\WINDOWS\System32\SQLSRV32.dll"
        _winreg.SetValueEx(valKey, strValueName, 0, _winreg.REG_SZ, strValue)
        strValueName = "Server"
        strValue = "DMMESDE"
        _winreg.SetValueEx(valKey, strValueName, 0, _winreg.REG_SZ, strValue)
        strValueName = "Trusted_Connection"
        strValue = "Yes"
        _winreg.SetValueEx(valKey, strValueName, 0, _winreg.REG_SZ, strValue)
    except:
        pass
    try:
        _winreg.CloseKey(valKey)
    except:
        pass
    try:
        strValueName = "H2O"
        strValue = "SQL Server"
        _winreg.SetValueEx(odbckey, strValueName, 0, _winreg.REG_SZ, strValue)
    except:
        pass
    try:
        strKeyPath = "SOFTWARE\ODBC\ODBC.INI\H2O"
        valKey = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, strKeyPath)
        strValueName = "Database"
        strValue = "H2OSpatial"
        _winreg.SetValueEx(valKey, strValueName, 0, _winreg.REG_SZ, strValue)
        strValueName = "Driver"
        strValue = "C:\WINDOWS\System32\SQLSRV32.dll"
        _winreg.SetValueEx(valKey, strValueName, 0, _winreg.REG_SZ, strValue)
        strValueName = "Server"
        strValue = "DMMESDE"
        _winreg.SetValueEx(valKey, strValueName, 0, _winreg.REG_SZ, strValue)
        strValueName = "Trusted_Connection"
        strValue = "Yes"
        _winreg.SetValueEx(valKey, strValueName, 0, _winreg.REG_SZ, strValue)
    except:
        pass
    try:
        _winreg.CloseKey(valKey)
    except:
        pass
    try:
        _winreg.CloseKey(odbckey)
    except:
        pass
    try:
        conn = odbc.odbc(Dmlr_DB)
        conn2 = odbc.odbc(WaterQuality)
        conn3 = odbc.odbc(DMMESDEConnection)
    except:
        try:
            conn = odbc.odbc(Dmlr_DB)
            conn2 = odbc.odbc(WaterQuality)
            conn3 = odbc.odbc(DMMESDEConnection)
        except:
            conn = 1
            conn2 = 1
            conn3 = 1
    connList = [conn, conn2, conn3]
    return connList


def MPIDUpdate(parent, app, session, mpid, locno, facloc, north, east, mpidtype, atype, streamtier, repoutfall, repwet,
               acidalk, drngcat, disclass, mlevel, fclass):
    conn = odbc.odbc(WaterQuality)
    cursor = conn.cursor()
    sqlSearch = str("select AppNo from MPIDTable")
    cursor.execute(sqlSearch)
    result = cursor.fetchall()
    if type(result) is not types.NoneType:
        RecordNo = len(result) + 1
    else:
        RecordNo = 1
    cursor.execute("insert into MPIDTable (RecordNo,AppNo,SessionNo,MpidNo,LocNo,FacLoc,Northing,Easting,MpidType,ActionType,Tier,CRep,WRep,AcidAlk,DrngCat,DisClass,MLevel,FClass,ModDate) VALUES\
('" + str(RecordNo) + "','" + str(app) + "','" + str(session) + "','" + str(mpid) + "','" + str(locno) + "','" + str(
        facloc) + "','" + str(north) + "','" + str(east) + "','" + str(mpidtype) +
                   "','" + str(atype) + "','" + str(streamtier) + "','" + str(repoutfall) + "','" + str(
        repwet) + "','" + str(acidalk) + "','" + str(drngcat) + "','" +
                   str(disclass) + "','" + str(mlevel) + "','" + str(fclass) + "','" + str(
        datetime.datetime.today()) + "')")


def ParameterUpdate(parent, app, session, mpid, locno, facloc, north, east, mpidtype, actiontype, parameter, units,
                    monthlim, weeklim, minlim, maxlim, freq, interval, method, load, exempt, acutecrit, chroncrit,
                    monreqd, loadunits, loadlimits, loadint):
    conn = odbc.odbc(WaterQuality)
    cursor = conn.cursor()
    sqlSearch = str("select AppNo from ParameterTable")
    cursor.execute(sqlSearch)
    result = cursor.fetchall()
    if type(result) is not types.NoneType:
        RecordNo = len(result) + 1
    else:
        RecordNo = 1
    cursor.execute("insert into ParameterTable (RecordNo,AppNo,SessionNo,MpidNo,LocNo,FacLoc,Northing,Easting,MpidType,ActionType,Parameter,Units,MonthLim,WeekLim,MinLim,MaxLim,Freq,Interval,Method,PLoad,Exempt,AcuteCrit,ChronCrit,MonReqd,ModDate,PLoadUnit,PLoadLimit,PLoadInt) VALUES\
('" + str(RecordNo) + "','" + str(app) + "','" + str(session) + "','" + str(mpid) + "','" + str(locno) + "','" + str(
        facloc) + "','" + str(north) + "','" + str(east) + "','" +
                   str(mpidtype) + "','" + str(actiontype) + "','" + str(parameter) + "','" + str(units) + "','" + str(
        monthlim) + "','" + str(weeklim) +
                   "','" + str(minlim) + "','" + str(maxlim) + "','" + str(freq) + "','" + str(interval) + "','" + str(
        method) + "','" + str(load) + "','" + str(exempt) + "','" +
                   str(acutecrit) + "','" + str(chroncrit) + "','" + str(monreqd) + "','" + str(
        datetime.datetime.today()) + "','" + str(loadunits) + "','" + str(loadlimits) + "','" + str(loadint) + "')")


def GetComments(parent, MPID, Permit):
    conn = odbc.odbc(WaterQuality)
    cursor = conn.cursor()
    sqlSearch = str(
        "select cType,OldC,NewC,Date from CommentsTable where MPIDNo = '" + str(MPID) + "'and Permit = '" + str(
            Permit) + "'")
    cursor.execute(sqlSearch)
    records = cursor.fetchall()
    dComments = []
    cComments = []
    aComments = []
    try:
        for each in records:
            if each[0] == "DELETE":
                dComments.append(each[1])
            elif each[0] == "CHANGE":
                cComments.append([each[1], each[2]])
            elif each[0] == "ADD":
                aComments.append([each[2], each[3]])
    except:
        pass
    return dComments, cComments, aComments


def LoadMPIDData(GetApp, parent, AppNumber, SessionList, NPMPIDList, NPLocNoList, NPFacLocList, NPNorthingList,
                 NPEastingList, NPBigList, NPTierDesList,
                 NPRepChem, NPRepWET, NPAcidList, NPDrainCatList, NPDischargeType, NPAgeList, NPTblSrNameList,
                 StressorListDictionary, RevLabelDict,
                 ISMPIDList, ISLocNoList, ISFacLocList, ISNorthingList, ISEastingList, ISBigList, ISTierDesList,
                 ISDischargeType, StreamIndexList,
                 StreamTierDictionary, ISTblSrNameList, ISTypeLabel, StreamsFlowClass, ISLabelDict, LabelDict,
                 GWMPIDList, GWBigList, GWFacLocList,
                 GWLocNoList, GWNorthingList, GWEastingList, GWLabelDict):
    conn = odbc.odbc(WaterQuality)
    cursor = conn.cursor()
    OldAcidityList = []
    OldDrainCategoryList = []
    for i in range(0, len(NPAcidList)):
        OldAcidityList.append(NPAcidList[i])
        OldDrainCategoryList.append(NPDrainCatList[i])
    for each in SessionList:
        MPIDUpdateList = []
        ParameterUpdateList = []
        ModDateDict = {}
        ModDateListTemp = []
        sqlSearch = str(
            "select MpidNo,LocNo,FacLoc,Northing,Easting,Tier,CRep,WRep,AcidAlk,DrngCat,DisClass,ModDate from MPIDTable where AppNo = '" + str(
                AppNumber) + "' and SessionNo = '" + str(
                each) + "' and MpidType = 'NPDES' and ActionType = 'CHANGE' order by ABS(RecordNo) asc")
        cursor.execute(sqlSearch)
        result = cursor.fetchall()
        if type(result) is not types.NoneType:
            if len(result) > 0:
                for r in result:
                    MPIDUpdateList.append(r)
                    if type(r) is not types.NoneType:
                        ModDateDict[str(r[11])] = r
                        ModDateListTemp.append(str(r[11]))
        sqlSearch = str(
            "select MpidNo,LocNo,FacLoc,Northing,Easting,Parameter,Units,MonthLim,WeekLim,MinLim,MaxLim,Freq,Interval,Method,Exempt,ModDate,PLoadUnit,PLoadLimit,PLoadInt from ParameterTable where AppNo = '" + str(
                AppNumber) + "' and SessionNo = '" + str(
                each) + "' and MpidType = 'NPDES' and ActionType = 'CHANGE' order by ABS(RecordNo) asc")
        cursor.execute(sqlSearch)
        result = cursor.fetchall()
        if type(result) is not types.NoneType:
            if len(result) > 0:
                for r in result:
                    ParameterUpdateList.append(r)
                    if type(r) is not types.NoneType:
                        ModDateDict[str(r[15])] = r
                        ModDateListTemp.append(str(r[15]))
        if len(ModDateListTemp) > 0 and 'None' not in ModDateListTemp:
            ModDateListTemp.sort()
            for each in ModDateListTemp:
                r = ModDateDict[str(each)]
                if len(r) == 19:
                    indexnum = int(LabelDict[str(r[5])])
                    for j in range(0, len(NPMPIDList)):
                        if r[0] == NPMPIDList[j] and str(r[0]).upper() != "NONE" and str(r[0]).rstrip() != "":
                            NPBigList[j][indexnum][0] = str(r[6])
                            NPBigList[j][indexnum][1] = str(r[7])
                            NPBigList[j][indexnum][2] = str(r[8])
                            NPBigList[j][indexnum][6] = str(r[9])
                            NPBigList[j][indexnum][8] = str(r[10])
                            NPBigList[j][indexnum][10] = str(r[11])
                            NPBigList[j][indexnum][11] = str(r[12])
                            NPBigList[j][indexnum][12] = str(r[13])
                            NPBigList[j][indexnum][13] = str(r[16])
                            NPBigList[j][indexnum][14] = str(r[17])
                            NPBigList[j][indexnum][15] = str(r[18])
                            NPBigList[j][indexnum][17] = str(r[14])
                            break;
                        elif ((r[1] == NPLocNoList[j] and r[2] == NPFacLocList[j]) or (
                                r[1] == NPLocNoList[j] and r[3] == NPNorthingList[j]) or (
                                r[1] == NPLocNoList[j] and r[4] == NPEastingList[j]) or (
                                r[2] == NPFacLocList[j] and r[3] == NPNorthingList[j]) or (
                                r[2] == NPFacLocList[j] and r[4] == NPEastingList[j]) or (
                                r[3] == NPNorthingList[j] and r[4] == NPEastingList[j])):
                            NPBigList[j][indexnum][0] = str(r[6])
                            NPBigList[j][indexnum][1] = str(r[7])
                            NPBigList[j][indexnum][2] = str(r[8])
                            NPBigList[j][indexnum][6] = str(r[9])
                            NPBigList[j][indexnum][8] = str(r[10])
                            NPBigList[j][indexnum][10] = str(r[11])
                            NPBigList[j][indexnum][11] = str(r[12])
                            NPBigList[j][indexnum][12] = str(r[13])
                            NPBigList[j][indexnum][13] = str(r[16])
                            NPBigList[j][indexnum][14] = str(r[17])
                            NPBigList[j][indexnum][15] = str(r[18])
                            NPBigList[j][indexnum][17] = str(r[14])
                            break;
                elif len(r) == 12:
                    for i in range(0, len(NPMPIDList)):
                        if (r[0] == NPMPIDList[i] and str(r[0]).upper() != "NONE" and str(r[0]).rstrip() != "") or (
                                            (r[1] == NPLocNoList[i] and r[2] == NPFacLocList[i]) or (
                                                r[1] == NPLocNoList[i] and r[3] == NPNorthingList[i]) or (
                                            r[1] == NPLocNoList[i] and r[4] == NPEastingList[i]) or (
                                        r[2] == NPFacLocList[i] and r[3] == NPNorthingList[i]) or (
                                    r[2] == NPFacLocList[i] and r[4] == NPEastingList[i]) or (
                                r[3] == NPNorthingList[i] and r[4] == NPEastingList[i])):
                            NPTierDesList[i] = r[5]
                            NPRepChem[i] = r[6]
                            NPRepWET[i] = r[7]
                            NPAcidList[i] = r[8]
                            NPDrainCatList[i] = r[9]
                            NPDischargeType[i] = r[10]
                            if NPRepChem[i] == "Yes":
                                for j in range(8, 43):
                                    if j != 10 and j != 11:
                                        NPBigList[i][j][1] = "RMR"
                                        NPBigList[i][j][11] = "Permit Term"
                            if NPRepWET[i] != "No":
                                for j in range(10, 12):
                                    if j == 10 and (NPRepWET[i] == "Acute" or NPRepWET[i] == "Both"):
                                        NPBigList[i][j][1] = "RWETMR"
                                    if j == 11 and (NPRepWET[i] == "Chronic" or NPRepWET[i] == "Both"):
                                        NPBigList[i][j][1] = "RWETMR"
                            if NPAcidList[i] == "Alkaline":
                                NPBigList[i][7][8] = "NA"
                                NPBigList[i][7][8] = "NA"
                            if NPAcidList[i] == "Acid":
                                NPBigList[i][7][1] = str(2.0)
                                NPBigList[i][7][8] = str(4.0)
                            Stream = NPTblSrNameList[i]
                            Stressors = StressorListDictionary[Stream].split(",")
                            if NPDrainCatList[i] == "5":
                                if NPBigList[i][9][8] == "NA":
                                    NPBigList[i][9][8] = "0.5"
                                if NPBigList[i][4][1] == "35":
                                    NPBigList[i][4][1] = "NL"
                                if NPBigList[i][4][8] == "70":
                                    NPBigList[i][4][8] = "NL"
                            else:
                                if NPBigList[i][9][8] == "0.5":
                                    NPBigList[i][9][8] = "NA"
                                if NPBigList[i][4][1] == "NA" or NPBigList[i][4][1] == "NL":
                                    NPBigList[i][4][1] = "35"
                                if NPBigList[i][4][8] == "NA" or NPBigList[i][4][8] == "NL":
                                    NPBigList[i][4][8] = "70"
                            for j in range(0, len(NPBigList[i])):
                                if str(RevLabelDict[str(j)]) not in Stressors:
                                    if NPDrainCatList[i] == "1":
                                        NPBigList[i][j][17] = "0.2 In"
                                    elif NPDrainCatList[i] == "2":
                                        NPBigList[i][j][17] = "10Y/24H"
                                    elif NPDrainCatList[i] == "3":
                                        NPBigList[i][j][17] = "NA"
                                    elif NPDrainCatList[i] == "4":
                                        NPBigList[i][j][17] = "1Y/24H"
                                    elif NPDrainCatList[i] == "5":
                                        NPBigList[i][j][17] = "NA"
        else:
            for r in MPIDUpdateList:
                for i in range(0, len(NPMPIDList)):
                    if (r[0] == NPMPIDList[i] and str(r[0]).upper() != "NONE" and str(r[0]).rstrip() != "") or (
                                        (r[1] == NPLocNoList[i] and r[2] == NPFacLocList[i]) or (
                                            r[1] == NPLocNoList[i] and r[3] == NPNorthingList[i]) or (
                                        r[1] == NPLocNoList[i] and r[4] == NPEastingList[i]) or (
                                    r[2] == NPFacLocList[i] and r[3] == NPNorthingList[i]) or (
                                r[2] == NPFacLocList[i] and r[4] == NPEastingList[i]) or (
                            r[3] == NPNorthingList[i] and r[4] == NPEastingList[i])):
                        NPTierDesList[i] = r[5]
                        NPRepChem[i] = r[6]
                        NPRepWET[i] = r[7]
                        NPAcidList[i] = r[8]
                        NPDrainCatList[i] = r[9]
                        NPDischargeType[i] = r[10]
            for r in ParameterUpdateList:
                indexnum = int(LabelDict[str(r[5])])
                for j in range(0, len(NPMPIDList)):
                    if r[0] == NPMPIDList[j] and str(r[0]).upper() != "NONE" and str(r[0]).rstrip() != "":
                        NPBigList[j][indexnum][0] = str(r[6])
                        NPBigList[j][indexnum][1] = str(r[7])
                        NPBigList[j][indexnum][2] = str(r[8])
                        NPBigList[j][indexnum][6] = str(r[9])
                        NPBigList[j][indexnum][8] = str(r[10])
                        NPBigList[j][indexnum][10] = str(r[11])
                        NPBigList[j][indexnum][11] = str(r[12])
                        NPBigList[j][indexnum][12] = str(r[13])
                        NPBigList[j][indexnum][13] = str(r[16])
                        NPBigList[j][indexnum][14] = str(r[17])
                        NPBigList[j][indexnum][15] = str(r[18])
                        NPBigList[j][indexnum][17] = str(r[14])
                        break;
                    elif ((r[1] == NPLocNoList[j] and r[2] == NPFacLocList[j]) or (
                            r[1] == NPLocNoList[j] and r[3] == NPNorthingList[j]) or (
                            r[1] == NPLocNoList[j] and r[4] == NPEastingList[j]) or (
                            r[2] == NPFacLocList[j] and r[3] == NPNorthingList[j]) or (
                            r[2] == NPFacLocList[j] and r[4] == NPEastingList[j]) or (
                            r[3] == NPNorthingList[j] and r[4] == NPEastingList[j])):
                        NPBigList[j][indexnum][0] = str(r[6])
                        NPBigList[j][indexnum][1] = str(r[7])
                        NPBigList[j][indexnum][2] = str(r[8])
                        NPBigList[j][indexnum][6] = str(r[9])
                        NPBigList[j][indexnum][8] = str(r[10])
                        NPBigList[j][indexnum][10] = str(r[11])
                        NPBigList[j][indexnum][11] = str(r[12])
                        NPBigList[j][indexnum][12] = str(r[13])
                        NPBigList[j][indexnum][13] = str(r[16])
                        NPBigList[j][indexnum][14] = str(r[17])
                        NPBigList[j][indexnum][15] = str(r[18])
                        NPBigList[j][indexnum][17] = str(r[14])
                        break;
            for i in range(0, len(NPMPIDList)):
                if NPRepChem[i] == "Yes":
                    for j in range(8, 43):
                        if j != 10 and j != 11:
                            if NPBigList[i][j][1] == "NA" and NPBigList[i][j][2] == "NA" and NPBigList[i][j][
                                6] == "NA" and NPBigList[i][j][8] == "NA":
                                NPBigList[i][j][1] = "RMR"
                                NPBigList[i][j][11] = "Permit Term"
                elif NPRepChem[i] == "No":
                    for j in range(8, 43):
                        if j != 10 and j != 11:
                            if NPBigList[i][j][1] == "RMR" and NPBigList[i][j][2] == "NA" and NPBigList[i][j][
                                6] == "NA" and NPBigList[i][j][8] == "NA":
                                NPBigList[i][j][1] = "NA"
                                NPBigList[i][j][11] = "Month"
                if NPRepWET[i] != "No":
                    for j in range(10, 12):
                        if NPBigList[i][j][1] == "NA":
                            if j == 10 and (NPRepWET[i] == "Acute" or NPRepWET[i] == "Both"):
                                NPBigList[i][j][1] = "RWETMR"
                            if j == 11 and (NPRepWET[i] == "Chronic" or NPRepWET[i] == "Both"):
                                NPBigList[i][j][1] = "RWETMR"
                elif NPRepWET[i] == "No":
                    for j in range(10, 12):
                        if NPBigList[i][j][1] == "RMWETMR":
                            if j == 10 and (NPRepWET[i] == "Acute" or NPRepWET[i] == "Both"):
                                NPBigList[i][j][1] = "NA"
                            if j == 11 and (NPRepWET[i] == "Chronic" or NPRepWET[i] == "Both"):
                                NPBigList[i][j][1] = "NA"

                AA = OldAcidityList[i]
                AcidAlk = NPAcidList[i]
                NewOld = NPAgeList[i]
                if AA == "Acid":
                    if NewOld == "New":
                        if NPBigList[i][6][1] == str(3.0) and NPBigList[i][6][8] == str(6.0):
                            if AcidAlk == "Acid":
                                NPBigList[i][6][1] = str(3.0)
                                NPBigList[i][6][8] = str(6.0)
                            elif AcidAlk == "Alkaline":
                                NPBigList[i][6][1] = str(3.0)
                                NPBigList[i][6][8] = str(6.0)
                        if NPBigList[i][7][1] == str(2.0) and NPBigList[i][7][8] == str(4.0):
                            if AcidAlk == "Acid":
                                NPBigList[i][7][1] = str(2.0)
                                NPBigList[i][7][8] = str(4.0)
                            elif AcidAlk == "Alkaline":
                                NPBigList[i][7][8] = "NA"
                                NPBigList[i][7][8] = "NA"
                    elif NewOld == "Old":
                        if NPBigList[i][6][1] == str(3.5) and NPBigList[i][6][8] == str(7.0):
                            if AcidAlk == "Acid":
                                NPBigList[i][6][1] = str(3.5)
                                NPBigList[i][6][8] = str(7.0)
                            elif AcidAlk == "Alkaline":
                                NPBigList[i][6][1] = str(3.5)
                                NPBigList[i][6][8] = str(7.0)
                        if NPBigList[i][7][1] == str(2.0) and NPBigList[i][7][8] == str(4.0):
                            if AcidAlk == "Acid":
                                NPBigList[i][7][1] = str(2.0)
                                NPBigList[i][7][8] = str(4.0)
                            elif AcidAlk == "Alkaline":
                                NPBigList[i][7][1] = "NA"
                                NPBigList[i][7][8] = "NA"
                elif AA == "Alkaline":
                    if NewOld == "New":
                        if NPBigList[i][6][1] == str(3.0) and NPBigList[i][6][8] == str(6.0):
                            if AcidAlk == "Acid":
                                NPBigList[i][6][1] = str(3.0)
                                NPBigList[i][6][8] = str(6.0)
                            elif AcidAlk == "Alkaline":
                                NPBigList[i][6][1] = str(3.0)
                                NPBigList[i][6][8] = str(6.0)
                        if NPBigList[i][7][1] == "2.0" and NPBigList[i][7][8] == "NA":
                            if AcidAlk == "Acid":
                                NPBigList[i][7][1] = str(2.0)
                                NPBigList[i][7][8] = str(4.0)
                            elif AcidAlk == "Alkaline":
                                NPBigList[i][7][1] = "NA"
                                NPBigList[i][7][8] = "NA"
                    elif NewOld == "Old":
                        if NPBigList[i][6][1] == str(3.5) and NPBigList[i][6][8] == str(7.0):
                            if AcidAlk == "Acid":
                                NPBigList[i][6][1] = str(3.5)
                                NPBigList[i][6][8] = str(7.0)
                            elif AcidAlk == "Alkaline":
                                NPBigList[i][6][1] = str(3.5)
                                NPBigList[i][6][8] = str(7.0)
                        if NPBigList[i][7][1] == "2.0" and NPBigList[i][7][8] == "NA":
                            if AcidAlk == "Acid":
                                NPBigList[i][7][1] = str(2.0)
                                NPBigList[i][7][8] = str(4.0)
                            elif AcidAlk == "Alkaline":
                                NPBigList[i][7][1] = "NA"
                                NPBigList[i][7][8] = "NA"
                Stream = NPTblSrNameList[i]
                Stressors = StressorListDictionary[Stream].split(",")
                DrainCat = NPDrainCatList[i]
                DC = OldDrainCategoryList[i]
                if DrainCat == "5":
                    if NPBigList[i][9][8] == "NA":
                        NPBigList[i][9][8] = "0.5"
                    if NPBigList[i][4][1] == "35":
                        NPBigList[i][4][1] = "NL"
                    if NPBigList[i][4][8] == "70":
                        NPBigList[i][4][8] = "NL"
                else:
                    if NPBigList[i][9][8] == "0.5":
                        NPBigList[i][9][8] = "NA"
                    if NPBigList[i][4][1] == "NA" or NPBigList[i][4][1] == "NL":
                        NPBigList[i][4][1] = "35"
                    if NPBigList[i][4][8] == "NA" or NPBigList[i][4][8] == "NL":
                        NPBigList[i][4][8] = "70"
                if DC == "1":
                    for j in range(0, len(NPBigList[i])):
                        if NPBigList[i][j][17] == "0.2 In" and str(RevLabelDict[str(j)]) not in Stressors:
                            if DrainCat == "1":
                                NPBigList[i][j][17] = "0.2 In"
                            elif DrainCat == "2":
                                NPBigList[i][j][17] = "10Y/24H"
                            elif DrainCat == "3":
                                NPBigList[i][j][17] = "NA"
                            elif DrainCat == "4":
                                NPBigList[i][j][17] = "1Y/24H"
                            elif DrainCat == "5":
                                NPBigList[i][j][17] = "NA"
                elif DC == "2":
                    for j in range(0, len(NPBigList[i])):
                        if NPBigList[i][j][17] == "10Y/24H" and str(RevLabelDict[str(j)]) not in Stressors:
                            if DrainCat == "1":
                                NPBigList[i][j][17] = "0.2 In"
                            elif DrainCat == "2":
                                NPBigList[i][j][17] = "10Y/24H"
                            elif DrainCat == "3":
                                NPBigList[i][j][17] = "NA"
                            elif DrainCat == "4":
                                NPBigList[i][j][17] = "1Y/24H"
                            elif DrainCat == "5":
                                NPBigList[i][j][17] = "NA"
                elif DC == "3" or DC == "5":
                    for j in range(0, len(NPBigList[i])):
                        if NPBigList[i][j][17] == "NA" and str(RevLabelDict[str(j)]) not in Stressors:
                            if DrainCat == "1":
                                NPBigList[i][j][17] = "0.2 In"
                            elif DrainCat == "2":
                                NPBigList[i][j][17] = "10Y/24H"
                            elif DrainCat == "3":
                                NPBigList[i][j][17] = "NA"
                            elif DrainCat == "4":
                                NPBigList[i][j][17] = "1Y/24H"
                            elif DrainCat == "5":
                                NPBigList[i][j][17] = "NA"
                elif DC == "4":
                    for j in range(0, len(NPBigList[i])):
                        if NPBigList[i][j][17] == "1Y/24H" and str(RevLabelDict[str(j)]) not in Stressors:
                            if DrainCat == "1":
                                NPBigList[i][j][17] = "0.2 In"
                            elif DrainCat == "2":
                                NPBigList[i][j][17] = "10Y/24H"
                            elif DrainCat == "3":
                                NPBigList[i][j][17] = "NA"
                            elif DrainCat == "4":
                                NPBigList[i][j][17] = "1Y/24H"
                            elif DrainCat == "5":
                                NPBigList[i][j][17] = "NA"
    #Groundwater Updates
    for each in SessionList:
        MPIDUpdateList = []
        ParameterUpdateList = []
        ModDateDict = {}
        ModDateListTemp = []
        sqlSearch = str(
            "select MpidNo,LocNo,FacLoc,Northing,Easting,Parameter,Units,Freq,Interval,Method,AcuteCrit,ChronCrit,MonReqd,ModDate from ParameterTable where AppNo = '" + str(
                AppNumber) + "' and SessionNo = '" + str(
                each) + "' and MpidType = 'GROUNDWATER' and ActionType = 'CHANGE' order by ABS(RecordNo) asc")
        cursor.execute(sqlSearch)
        result = cursor.fetchall()
        if type(result) is not types.NoneType:
            if len(result) > 0:
                for r in result:
                    ParameterUpdateList.append(r)
                    if type(r) is not types.NoneType:
                        ModDateDict[str(r[13])] = r
                        ModDateListTemp.append(str(r[13]))
        if len(ModDateListTemp) > 0 and 'None' not in ModDateListTemp:
            ModDateListTemp.sort()
            for each in ModDateListTemp:
                r = ModDateDict[str(each)]
                if len(r) == 14:
                    j = 0
                    while j < len(GWMPIDList):
                        if r[0] == GWMPIDList[j] and str(r[0]).upper() != "NONE" and str(r[0]).rstrip() != "":
                            indexnum = int(GWLabelDict[str(r[5])])
                            GWBigList[j][indexnum][0] = r[6]
                            GWBigList[j][indexnum][1] = r[10]
                            GWBigList[j][indexnum][2] = r[11]
                            GWBigList[j][indexnum][8] = r[7]
                            GWBigList[j][indexnum][9] = r[8]
                            GWBigList[j][indexnum][10] = r[9]
                            GWBigList[j][indexnum][11] = r[12]
                            break;
                        elif ((r[1] == GWLocNoList[j] and r[2] == GWFacLocList[j]) or (
                                r[1] == GWLocNoList[j] and r[3] == GWNorthingList[j]) or (
                                r[1] == GWLocNoList[j] and r[4] == GWEastingList[j]) or (
                                r[2] == GWFacLocList[j] and r[3] == GWNorthingList[j]) or (
                                r[2] == GWFacLocList[j] and r[4] == GWEastingList[j]) or (
                                r[3] == GWNorthingList[j] and r[4] == GWEastingList[j])):
                            indexnum = int(ISLabelDict[str(r[5])])
                            GWBigList[j][indexnum][0] = r[6]
                            GWBigList[j][indexnum][1] = r[10]
                            GWBigList[j][indexnum][2] = r[11]
                            GWBigList[j][indexnum][8] = r[7]
                            GWBigList[j][indexnum][9] = r[8]
                            GWBigList[j][indexnum][10] = r[9]
                            GWBigList[j][indexnum][11] = r[12]
                            break;
                        j += 1
    #Instream Updates
    for each in SessionList:
        MPIDUpdateList = []
        ParameterUpdateList = []
        ModDateDict = {}
        ModDateListTemp = []
        sqlSearch = str(
            "select MpidNo,LocNo,FacLoc,Northing,Easting,Tier,MLevel,FClass,ModDate from MPIDTable where AppNo = '" + str(
                AppNumber) + "' and SessionNo = '" + str(
                each) + "' and MpidType = 'INSTREAM' and ActionType = 'CHANGE' order by ABS(RecordNo) asc")
        cursor.execute(sqlSearch)
        result = cursor.fetchall()
        if type(result) is not types.NoneType:
            if len(result) > 0:
                for r in result:
                    MPIDUpdateList.append(r)
                    if type(r) is not types.NoneType:
                        ModDateDict[str(r[8])] = r
                        ModDateListTemp.append(str(r[8]))
        sqlSearch = str(
            "select MpidNo,LocNo,FacLoc,Northing,Easting,Parameter,Units,Freq,Interval,Method,AcuteCrit,ChronCrit,MonReqd,ModDate from ParameterTable where AppNo = '" + str(
                AppNumber) + "' and SessionNo = '" + str(
                each) + "' and MpidType = 'INSTREAM' and ActionType = 'CHANGE' order by ABS(RecordNo) asc")
        cursor.execute(sqlSearch)
        result = cursor.fetchall()
        if type(result) is not types.NoneType:
            if len(result) > 0:
                for r in result:
                    ParameterUpdateList.append(r)
                    if type(r) is not types.NoneType:
                        ModDateDict[str(r[13])] = r
                        ModDateListTemp.append(str(r[13]))
        if len(ModDateListTemp) > 0 and 'None' not in ModDateListTemp:
            ModDateListTemp.sort()
            for each in ModDateListTemp:
                r = ModDateDict[str(each)]
                if len(r) < 11:
                    j = 0
                    while j < len(ISMPIDList):
                        if r[0] == ISMPIDList[j] and str(r[0]).upper() != "NONE" and str(r[0]).rstrip() != "":
                            ISTierDesList[j] = r[5]
                            ISTypeLabel[j] = r[6]
                            ISDischargeType[j] = r[7]
                            #break;
                        elif ((r[1] == ISLocNoList[j] and r[2] == ISFacLocList[j]) or (
                                r[1] == ISLocNoList[j] and r[3] == ISNorthingList[j]) or (
                                r[1] == ISLocNoList[j] and r[4] == ISEastingList[j]) or (
                                r[2] == ISFacLocList[j] and r[3] == ISNorthingList[j]) or (
                                r[2] == ISFacLocList[j] and r[4] == ISEastingList[j]) or (
                                r[3] == ISNorthingList[j] and r[4] == ISEastingList[j])):
                            ISTierDesList[j] = r[5]
                            ISTypeLabel[j] = r[6]
                            ISDischargeType[j] = r[7]
                            #break;
                        MonitorLevel = ISTypeLabel[j]
                        if MonitorLevel == "None Current":
                            i = 0
                            while i < len(ISBigList[j]):
                                ISBigList[j][i][11] = "No"
                                i += 1
                        elif MonitorLevel == "Baseline":
                            i = 0
                            while i < len(ISBigList[j]):
                                if i < 12:
                                    ISBigList[j][i][11] = "Yes"
                                else:
                                    ISBigList[j][i][11] = "No"
                                i += 1
                        elif MonitorLevel == "Bio and Chem":
                            i = 0
                            while i < len(ISBigList[j]):
                                if i != 12:
                                    ISBigList[j][i][11] = "Yes"
                                    ISBigList[j][i][9] = "Year"
                                    ISBigList[j][i][8] = "2"
                                else:
                                    ISBigList[j][i][11] = "No"
                                    ISBigList[j][i][8] = "2"
                                    ISBigList[j][i][9] = "Year"

                                i += 1
                        elif MonitorLevel == "Chemical":
                            i = 0
                            while i < len(ISBigList[j]):
                                if i != 12:
                                    ISBigList[j][i][11] = "Yes"
                                    ISBigList[j][i][8] = "2"
                                    ISBigList[j][i][9] = "Year"
                                else:
                                    ISBigList[j][i][11] = "No"
                                    ISBigList[j][i][8] = "2"
                                    ISBigList[j][i][9] = "Year"
                                i += 1
                        elif MonitorLevel == "Flow Only":
                            i = 0
                            while i < len(ISBigList[j]):
                                if i > 0:
                                    ISBigList[j][i][11] = "No"
                                else:
                                    ISBigList[j][i][11] = "Yes"
                                i += 1
                        elif MonitorLevel == "Biological Only":
                            i = 0
                            while i < len(ISBigList[j]):
                                ISBigList[j][i][11] = "No"
                                ISBigList[j][i][9] = "Quarter"
                                ISBigList[j][i][8] = "3"
                                i += 1
                        j += 1
                else:
                    j = 0
                    while j < len(ISMPIDList):
                        if r[0] == ISMPIDList[j] and str(r[0]).upper() != "NONE" and str(r[0]).rstrip() != "":
                            indexnum = int(ISLabelDict[str(r[5])])
                            ISBigList[j][indexnum][0] = r[6]
                            ISBigList[j][indexnum][1] = r[10]
                            ISBigList[j][indexnum][2] = r[11]
                            ISBigList[j][indexnum][8] = r[7]
                            ISBigList[j][indexnum][9] = r[8]
                            ISBigList[j][indexnum][10] = r[9]
                            ISBigList[j][indexnum][11] = r[12]
                            break;
                        elif ((r[1] == ISLocNoList[j] and r[2] == ISFacLocList[j]) or (
                                r[1] == ISLocNoList[j] and r[3] == ISNorthingList[j]) or (
                                r[1] == ISLocNoList[j] and r[4] == ISEastingList[j]) or (
                                r[2] == ISFacLocList[j] and r[3] == ISNorthingList[j]) or (
                                r[2] == ISFacLocList[j] and r[4] == ISEastingList[j]) or (
                                r[3] == ISNorthingList[j] and r[4] == ISEastingList[j])):
                            indexnum = int(ISLabelDict[str(r[5])])
                            ISBigList[j][indexnum][0] = r[6]
                            ISBigList[j][indexnum][1] = r[10]
                            ISBigList[j][indexnum][2] = r[11]
                            ISBigList[j][indexnum][8] = r[7]
                            ISBigList[j][indexnum][9] = r[8]
                            ISBigList[j][indexnum][10] = r[9]
                            ISBigList[j][indexnum][11] = r[12]
                            break;
                        j += 1
        else:
            for r in MPIDUpdateList:
                j = 0
                while j < len(ISMPIDList):
                    if r[0] == ISMPIDList[j] and str(r[0]).upper() != "NONE" and str(r[0]).rstrip() != "":
                        ISTierDesList[j] = r[5]
                        ISTypeLabel[j] = r[6]
                        ISDischargeType[j] = r[7]
                        #break;
                    elif ((r[1] == ISLocNoList[j] and r[2] == ISFacLocList[j]) or (
                            r[1] == ISLocNoList[j] and r[3] == ISNorthingList[j]) or (
                            r[1] == ISLocNoList[j] and r[4] == ISEastingList[j]) or (
                            r[2] == ISFacLocList[j] and r[3] == ISNorthingList[j]) or (
                            r[2] == ISFacLocList[j] and r[4] == ISEastingList[j]) or (
                            r[3] == ISNorthingList[j] and r[4] == ISEastingList[j])):
                        ISTierDesList[j] = r[5]
                        ISTypeLabel[j] = r[6]
                        ISDischargeType[j] = r[7]
                        #break;
                    MonitorLevel = ISTypeLabel[j]
                    if MonitorLevel == "None Current":
                        i = 0
                        while i < len(ISBigList[j]):
                            ISBigList[j][i][11] = "No"
                            i += 1
                    elif MonitorLevel == "Baseline":
                        i = 0
                        while i < len(ISBigList[j]):
                            if i < 12:
                                ISBigList[j][i][11] = "Yes"
                            else:
                                ISBigList[j][i][11] = "No"
                            i += 1
                    elif MonitorLevel == "Bio and Chem":
                        i = 0
                        while i < len(ISBigList[j]):
                            if i != 12:
                                ISBigList[j][i][11] = "Yes"
                                ISBigList[j][i][8] = "2"
                                ISBigList[j][i][9] = "Year"
                            else:
                                ISBigList[j][i][11] = "No"
                                ISBigList[j][i][8] = "2"
                                ISBigList[j][i][9] = "Year"
                            i += 1
                    elif MonitorLevel == "Chemical":
                        i = 0
                        while i < len(ISBigList[j]):
                            if i != 12:
                                ISBigList[j][i][11] = "Yes"
                                ISBigList[j][i][8] = "2"
                                ISBigList[j][i][9] = "Year"
                            else:
                                ISBigList[j][i][11] = "No"
                                ISBigList[j][i][8] = "2"
                                ISBigList[j][i][9] = "Year"
                            i += 1
                    elif MonitorLevel == "Flow Only":
                        i = 0
                        while i < len(ISBigList[j]):
                            if i > 0:
                                ISBigList[j][i][11] = "No"
                            else:
                                ISBigList[j][i][11] = "Yes"
                            i += 1
                    elif MonitorLevel == "Biological Only":
                        i = 0
                        while i < len(ISBigList[j]):
                            ISBigList[j][i][11] = "No"
                            ISBigList[j][i][9] = "Quarter"
                            ISBigList[j][i][8] = "3"
                            i += 1
                    j += 1
    k = 0
    while k < len(NPMPIDList):
        for each in StreamIndexList:
            if each == NPTblSrNameList[k]:
                StreamTierDictionary[each] = NPTierDesList[k]
                break;
        k += 1
    k = 0
    while k < len(ISMPIDList):
        for each in StreamIndexList:
            if each == ISTblSrNameList[k]:
                StreamTierDictionary[each] = ISTierDesList[k]
                break;
        k += 1
    k = 0
    while k < len(ISMPIDList):
        l = 0
        while l < len(StreamIndexList):
            if StreamIndexList[l] == ISTblSrNameList[k]:
                StreamsFlowClass[l] = ISDischargeType[k]
                break;
            l += 1
        k += 1
    return NPTierDesList, NPRepChem, NPRepWET, NPAcidList, NPDrainCatList, NPDischargeType, NPBigList, ISTierDesList, ISTypeLabel, ISDischargeType, ISBigList, StreamTierDictionary, StreamsFlowClass, GWBigList


def LoadParameterData(GetApp, parent, AppNumber, SessionList, LabelDict, RevLabelDict, WaterTransDict, NPBigList,
                      NPMPIDList, NPLocNoList,
                      NPFacLocList, NPNorthingList, NPEastingList, ISLabelDict, RevISDict, ISWaterTransDict, ISBigList,
                      ISMPIDList, ISLocNoList,
                      ISFacLocList, ISNorthingList, ISEastingList, GWLabelDict, RevGWLabelDict, GWWaterTransDict,
                      GWBigList, GWMPIDList, GWLocNoList,
                      GWFacLocList, GWNorthingList, GWEastingList):
    conn = odbc.odbc(WaterQuality)
    cursor = conn.cursor()
    UniqueParamAddList = []
    UniqueParamISAddList = []
    UniqueParamGWAddList = []
    NPBigListChanged = False
    ISBigListChanged = False
    GWBigListChanged = False
    for each in SessionList:
        sqlSearch = str(
            "select Parameter from ParameterTable where AppNo = '" + str(AppNumber) + "' and SessionNo = '" + str(
                each) + "' and MpidType = 'NPDES' and ActionType = 'ADD' order by ABS(RecordNo) asc")
        cursor.execute(sqlSearch)
        result = cursor.fetchall()
        if type(result) is not types.NoneType:
            if len(result) > 0:
                for r in result:
                    if [r[0], each] not in UniqueParamAddList:
                        UniqueParamAddList.append([r[0], each])
        sqlSearch = str(
            "select Parameter from ParameterTable where AppNo = '" + str(AppNumber) + "' and SessionNo = '" + str(
                each) + "' and MpidType = 'INSTREAM' and ActionType = 'ADD' order by ABS(RecordNo) asc")
        cursor.execute(sqlSearch)
        result = cursor.fetchall()
        if type(result) is not types.NoneType:
            if len(result) > 0:
                for r in result:
                    if [r[0], each] not in UniqueParamISAddList:
                        UniqueParamISAddList.append([r[0], each])
        sqlSearch = str(
            "select Parameter from ParameterTable where AppNo = '" + str(AppNumber) + "' and SessionNo = '" + str(
                each) + "' and MpidType = 'GROUNDWATER' and ActionType = 'ADD' order by ABS(RecordNo) asc")
        cursor.execute(sqlSearch)
        result = cursor.fetchall()
        if type(result) is not types.NoneType:
            if len(result) > 0:
                for r in result:
                    if [r[0], each] not in UniqueParamGWAddList:
                        UniqueParamGWAddList.append([r[0], each])
    UniqueParamDict = {}
    UniqueParamBlankDict = {}
    if len(UniqueParamAddList) > 0:
        NPBigListChanged = True
        i = 0
        while i < len(UniqueParamAddList):
            lenLabelDict = len(LabelDict)
            LabelDict[UniqueParamAddList[i][0]] = str(lenLabelDict)
            RevLabelDict[str(lenLabelDict)] = str(UniqueParamAddList[i][0])
            WaterTransDict[str(lenLabelDict)] = "Wt" + str(UniqueParamAddList[i][0])
            sqlSearch = str(
                "select Units,MonthLim,WeekLim,MinLim,MaxLim,Freq,Interval,Method,PLoad,Exempt,PLoadUnit,PLoadLimit,PLoadInt from ParameterTable where AppNo = '" + str(
                    AppNumber) + "' and SessionNo = '" + str(UniqueParamAddList[i][
                    1]) + "' and MpidType = 'NPDES' and ActionType = 'ADD' and Parameter = '" + str(
                    UniqueParamAddList[i][0]) + "'")
            cursor.execute(sqlSearch)
            result = cursor.fetchone()
            if type(result) is not types.NoneType:
                if len(result) > 0:
                    UniqueParamDict[UniqueParamAddList[i][0]] = [result[0], result[1], result[2], "NA", "NA", "NA",
                                                                 result[3], "NA", result[4], "NA", result[5], result[6],
                                                                 result[7], result[10], result[11], result[12], "NA",
                                                                 result[9]]
                    UniqueParamBlankDict[UniqueParamAddList[i][0]] = [result[0], "NA", "NA", "NA", "NA", "NA", "NA",
                                                                      "NA", "NA", "NA", result[5], result[6], result[7],
                                                                      result[10], result[11], result[12], "NA",
                                                                      result[9]]
            tempIndexList = []
            sqlSearch = str("select MpidNo,LocNo,FacLoc,Northing,Easting from ParameterTable where AppNo = '" + str(
                AppNumber) + "' and SessionNo = '" + str(
                UniqueParamAddList[i][1]) + "' and ActionType = 'ADD' and MpidType = 'NPDES' and Parameter = '" + str(
                UniqueParamAddList[i][0]) + "'")
            cursor.execute(sqlSearch)
            result = cursor.fetchall()
            if type(result) is not types.NoneType:
                if len(result) > 0:
                    j = 0
                    while j < len(result):
                        k = 0
                        while k < len(NPMPIDList):
                            if result[j][0] == NPMPIDList[k] and str(result[j][0]).upper() != "NONE" and str(
                                    result[j][0]).rstrip() != "":
                                tempIndexList.append(k)
                                break;
                            elif ((result[j][1] == NPLocNoList[k] and result[j][2] == NPFacLocList[k]) or (
                                    result[j][1] == NPLocNoList[k] and result[j][3] == NPNorthingList[k]) or (
                                    result[j][1] == NPLocNoList[k] and result[j][4] == NPEastingList[k]) or (
                                    result[j][2] == NPFacLocList[k] and result[j][3] == NPNorthingList[k]) or (
                                    result[j][2] == NPFacLocList[k] and result[j][4] == NPEastingList[k]) or (
                                    result[j][3] == NPNorthingList[k] and result[j][4] == NPEastingList[k])):
                                tempIndexList.append(k)
                                break;
                            k += 1
                        j += 1
            if len(tempIndexList) > 0:
                j = 0
                while j < len(NPMPIDList):
                    if j in tempIndexList:
                        AddThisList = [UniqueParamDict[UniqueParamAddList[i][0]][0],
                                       UniqueParamDict[UniqueParamAddList[i][0]][1],
                                       UniqueParamDict[UniqueParamAddList[i][0]][2],
                                       UniqueParamDict[UniqueParamAddList[i][0]][3],
                                       UniqueParamDict[UniqueParamAddList[i][0]][4],
                                       UniqueParamDict[UniqueParamAddList[i][0]][5],
                                       UniqueParamDict[UniqueParamAddList[i][0]][6],
                                       UniqueParamDict[UniqueParamAddList[i][0]][7],
                                       UniqueParamDict[UniqueParamAddList[i][0]][8],
                                       UniqueParamDict[UniqueParamAddList[i][0]][9],
                                       UniqueParamDict[UniqueParamAddList[i][0]][10],
                                       UniqueParamDict[UniqueParamAddList[i][0]][11],
                                       UniqueParamDict[UniqueParamAddList[i][0]][12],
                                       UniqueParamDict[UniqueParamAddList[i][0]][13],
                                       UniqueParamDict[UniqueParamAddList[i][0]][14],
                                       UniqueParamDict[UniqueParamAddList[i][0]][15],
                                       UniqueParamDict[UniqueParamAddList[i][0]][16],
                                       UniqueParamDict[UniqueParamAddList[i][0]][17]]
                        NPBigList[j].append(AddThisList)
                    else:
                        AddThisList = [UniqueParamBlankDict[UniqueParamAddList[i][0]][0],
                                       UniqueParamBlankDict[UniqueParamAddList[i][0]][1],
                                       UniqueParamBlankDict[UniqueParamAddList[i][0]][2],
                                       UniqueParamBlankDict[UniqueParamAddList[i][0]][3],
                                       UniqueParamBlankDict[UniqueParamAddList[i][0]][4],
                                       UniqueParamBlankDict[UniqueParamAddList[i][0]][5],
                                       UniqueParamBlankDict[UniqueParamAddList[i][0]][6],
                                       UniqueParamBlankDict[UniqueParamAddList[i][0]][7],
                                       UniqueParamBlankDict[UniqueParamAddList[i][0]][8],
                                       UniqueParamBlankDict[UniqueParamAddList[i][0]][9],
                                       UniqueParamBlankDict[UniqueParamAddList[i][0]][10],
                                       UniqueParamBlankDict[UniqueParamAddList[i][0]][11],
                                       UniqueParamBlankDict[UniqueParamAddList[i][0]][12],
                                       UniqueParamBlankDict[UniqueParamAddList[i][0]][13],
                                       UniqueParamBlankDict[UniqueParamAddList[i][0]][14],
                                       UniqueParamBlankDict[UniqueParamAddList[i][0]][15],
                                       UniqueParamDict[UniqueParamAddList[i][0]][16],
                                       UniqueParamDict[UniqueParamAddList[i][0]][17]]
                        NPBigList[j].append(AddThisList)
                    j += 1
            i += 1
    UniqueParamISDict = {}
    UniqueParamISBlankDict = {}
    if len(UniqueParamISAddList) > 0:
        ISBigListChanged = True
        i = 0
        while i < len(UniqueParamISAddList):
            ISlenLabelDict = len(ISLabelDict)
            ISLabelDict[UniqueParamISAddList[i][0]] = str(ISlenLabelDict)
            RevISDict[str(ISlenLabelDict)] = str(UniqueParamISAddList[i][0])
            ISWaterTransDict[str(ISlenLabelDict)] = "Wt" + str(UniqueParamISAddList[i][0])
            sqlSearch = str(
                "select Units,Freq,Interval,Method,AcuteCrit,ChronCrit,MonReqd from ParameterTable where AppNo = '" + str(
                    AppNumber) + "' and SessionNo = '" + str(UniqueParamISAddList[i][
                    1]) + "' and MpidType = 'INSTREAM' and ActionType = 'ADD' and Parameter = '" + str(
                    UniqueParamISAddList[i][0]) + "'")
            cursor.execute(sqlSearch)
            result = cursor.fetchone()
            if type(result) is not types.NoneType:
                if len(result) > 0:
                    UniqueParamISDict[UniqueParamISAddList[i][0]] = [result[0], result[4], result[5], "NA", "NA", "NA",
                                                                     "NA", "NA", result[1], result[2], result[3],
                                                                     result[6], "NA", "NA", "NA"]
                    UniqueParamISBlankDict[UniqueParamISAddList[i][0]] = [result[0], result[4], result[5], "NA", "NA",
                                                                          "NA", "NA", "NA", result[1], result[2],
                                                                          result[3], "No", "NA", "NA", "NA"]
            tempIndexList = []
            sqlSearch = str("select MpidNo,LocNo,FacLoc,Northing,Easting from ParameterTable where AppNo = '" + str(
                AppNumber) + "' and SessionNo = '" + str(UniqueParamISAddList[i][
                1]) + "' and ActionType = 'ADD' and MpidType = 'INSTREAM' and Parameter = '" + str(
                UniqueParamISAddList[i][0]) + "'")
            cursor.execute(sqlSearch)
            result = cursor.fetchall()
            if type(result) is not types.NoneType:
                if len(result) > 0:
                    j = 0
                    while j < len(result):
                        k = 0
                        while k < len(ISMPIDList):
                            if result[j][0] == ISMPIDList[k] and str(result[j][0]).upper() != "NONE" and str(
                                    result[j][0]).rstrip() != "":
                                tempIndexList.append(k)
                                break;
                            elif ((result[j][1] == ISLocNoList[k] and result[j][2] == ISFacLocList[k]) or (
                                    result[j][1] == ISLocNoList[k] and result[j][3] == ISNorthingList[k]) or (
                                    result[j][1] == ISLocNoList[k] and result[j][4] == ISEastingList[k]) or (
                                    result[j][2] == ISFacLocList[k] and result[j][3] == ISNorthingList[k]) or (
                                    result[j][2] == ISFacLocList[k] and result[j][4] == ISEastingList[k]) or (
                                    result[j][3] == ISNorthingList[k] and result[j][4] == ISEastingList[k])):
                                tempIndexList.append(k)
                                break;
                            k += 1
                        j += 1
            if len(tempIndexList) > 0:
                j = 0
                while j < len(ISMPIDList):
                    if j in tempIndexList:
                        AddThisList = [UniqueParamISDict[UniqueParamISAddList[i][0]][0],
                                       UniqueParamISDict[UniqueParamISAddList[i][0]][1],
                                       UniqueParamISDict[UniqueParamISAddList[i][0]][2],
                                       UniqueParamISDict[UniqueParamISAddList[i][0]][3],
                                       UniqueParamISDict[UniqueParamISAddList[i][0]][4],
                                       UniqueParamISDict[UniqueParamISAddList[i][0]][5],
                                       UniqueParamISDict[UniqueParamISAddList[i][0]][6],
                                       UniqueParamISDict[UniqueParamISAddList[i][0]][7],
                                       UniqueParamISDict[UniqueParamISAddList[i][0]][8],
                                       UniqueParamISDict[UniqueParamISAddList[i][0]][9],
                                       UniqueParamISDict[UniqueParamISAddList[i][0]][10],
                                       UniqueParamISDict[UniqueParamISAddList[i][0]][11]]
                        ISBigList[j].append(AddThisList)
                    else:
                        AddThisList = [UniqueParamISBlankDict[UniqueParamISAddList[i][0]][0],
                                       UniqueParamISBlankDict[UniqueParamISAddList[i][0]][1],
                                       UniqueParamISBlankDict[UniqueParamISAddList[i][0]][2],
                                       UniqueParamISBlankDict[UniqueParamISAddList[i][0]][3],
                                       UniqueParamISBlankDict[UniqueParamISAddList[i][0]][4],
                                       UniqueParamISBlankDict[UniqueParamISAddList[i][0]][5],
                                       UniqueParamISBlankDict[UniqueParamISAddList[i][0]][6],
                                       UniqueParamISBlankDict[UniqueParamISAddList[i][0]][7],
                                       UniqueParamISBlankDict[UniqueParamISAddList[i][0]][8],
                                       UniqueParamISBlankDict[UniqueParamISAddList[i][0]][9],
                                       UniqueParamISBlankDict[UniqueParamISAddList[i][0]][10],
                                       UniqueParamISBlankDict[UniqueParamISAddList[i][0]][11]]
                        ISBigList[j].append(AddThisList)
                    j += 1
            i += 1
    UniqueParamGWDict = {}
    UniqueParamGWBlankDict = {}
    if len(UniqueParamGWAddList) > 0:
        GWBigListChanged = True
        i = 0
        while i < len(UniqueParamGWAddList):
            GWlenLabelDict = len(GWLabelDict)
            GWLabelDict[UniqueParamGWAddList[i][0]] = str(GWlenLabelDict)
            RevGWLabelDict[str(GWlenLabelDict)] = str(UniqueParamGWAddList[i][0])
            GWWaterTransDict[str(GWlenLabelDict)] = "Wt" + str(UniqueParamGWAddList[i][0])
            sqlSearch = str(
                "select Units,Freq,Interval,Method,AcuteCrit,ChronCrit,MonReqd,ModDate from ParameterTable where AppNo = '" + str(
                    AppNumber) + "' and SessionNo = '" + str(UniqueParamGWAddList[i][
                    1]) + "' and MpidType = 'GROUNDWATER' and ActionType = 'ADD' and Parameter = '" + str(
                    UniqueParamGWAddList[i][0]) + "'")
            cursor.execute(sqlSearch)
            result = cursor.fetchone()
            if type(result) is not types.NoneType:
                if len(result) > 0:
                    UniqueParamGWDict[UniqueParamGWAddList[i][0]] = [result[0], result[4], result[5], "NA", "NA", "NA",
                                                                     "NA", "NA", result[1], result[2], result[3],
                                                                     result[6], "NA", "NA", "NA"]
                    UniqueParamGWBlankDict[UniqueParamGWAddList[i][0]] = [result[0], result[4], result[5], "NA", "NA",
                                                                          "NA", "NA", "NA", result[1], result[2],
                                                                          result[3], "No", "NA", "NA", "NA"]
            tempIndexList = []
            sqlSearch = str("select MpidNo,LocNo,FacLoc,Northing,Easting from ParameterTable where AppNo = '" + str(
                AppNumber) + "' and SessionNo = '" + str(UniqueParamGWAddList[i][
                1]) + "' and ActionType = 'ADD' and MpidType = 'GROUNDWATER' and Parameter = '" + str(
                UniqueParamGWAddList[i][0]) + "'")
            cursor.execute(sqlSearch)
            result = cursor.fetchall()
            if type(result) is not types.NoneType:
                if len(result) > 0:
                    j = 0
                    while j < len(result):
                        k = 0
                        while k < len(GWMPIDList):
                            if result[j][0] == GWMPIDList[k] and str(result[j][0]).upper() != "NONE" and str(
                                    result[j][0]).rstrip() != "":
                                tempIndexList.append(k)
                                break;
                            elif ((result[j][1] == GWLocNoList[k] and result[j][2] == GWFacLocList[k]) or (
                                    result[j][1] == GWLocNoList[k] and result[j][3] == GWNorthingList[k]) or (
                                    result[j][1] == GWLocNoList[k] and result[j][4] == GWEastingList[k]) or (
                                    result[j][2] == GWFacLocList[k] and result[j][3] == GWNorthingList[k]) or (
                                    result[j][2] == GWFacLocList[k] and result[j][4] == GWEastingList[k]) or (
                                    result[j][3] == GWNorthingList[k] and result[j][4] == GWEastingList[k])):
                                tempIndexList.append(k)
                                break;
                            k += 1
                        j += 1
            if len(tempIndexList) > 0:
                j = 0
                while j < len(GWMPIDList):
                    if j in tempIndexList:
                        AddThisList = [UniqueParamGWDict[UniqueParamGWAddList[i][0]][0],
                                       UniqueParamGWDict[UniqueParamGWAddList[i][0]][1],
                                       UniqueParamGWDict[UniqueParamGWAddList[i][0]][2],
                                       UniqueParamGWDict[UniqueParamGWAddList[i][0]][3],
                                       UniqueParamGWDict[UniqueParamGWAddList[i][0]][4],
                                       UniqueParamGWDict[UniqueParamGWAddList[i][0]][5],
                                       UniqueParamGWDict[UniqueParamGWAddList[i][0]][6],
                                       UniqueParamGWDict[UniqueParamGWAddList[i][0]][7],
                                       UniqueParamGWDict[UniqueParamGWAddList[i][0]][8],
                                       UniqueParamGWDict[UniqueParamGWAddList[i][0]][9],
                                       UniqueParamGWDict[UniqueParamGWAddList[i][0]][10],
                                       UniqueParamGWDict[UniqueParamGWAddList[i][0]][11]]
                        GWBigList[j].append(AddThisList)
                    else:
                        AddThisList = [UniqueParamGWBlankDict[UniqueParamGWAddList[i][0]][0],
                                       UniqueParamGWBlankDict[UniqueParamGWAddList[i][0]][1],
                                       UniqueParamGWBlankDict[UniqueParamGWAddList[i][0]][2],
                                       UniqueParamGWBlankDict[UniqueParamGWAddList[i][0]][3],
                                       UniqueParamGWBlankDict[UniqueParamGWAddList[i][0]][4],
                                       UniqueParamGWBlankDict[UniqueParamGWAddList[i][0]][5],
                                       UniqueParamGWBlankDict[UniqueParamGWAddList[i][0]][6],
                                       UniqueParamGWBlankDict[UniqueParamGWAddList[i][0]][7],
                                       UniqueParamGWBlankDict[UniqueParamGWAddList[i][0]][8],
                                       UniqueParamGWBlankDict[UniqueParamGWAddList[i][0]][9],
                                       UniqueParamGWBlankDict[UniqueParamGWAddList[i][0]][10],
                                       UniqueParamGWBlankDict[UniqueParamGWAddList[i][0]][11]]
                        GWBigList[j].append(AddThisList)
                    j += 1
            i += 1
    return LabelDict, RevLabelDict, WaterTransDict, NPBigList, NPBigListChanged, ISLabelDict, RevISDict, ISWaterTransDict, ISBigList, ISBigListChanged, GWLabelDict, RevGWLabelDict, GWWaterTransDict, GWBigList, GWBigListChanged


def LoadAdminData(GetApp, parent, AppNumber, SessionList, AdminDictionary, OptionDictionary, OverWrite, OldApp):
    conn = odbc.odbc(WaterQuality)
    cursor = conn.cursor()
    for each in SessionList:
        sqlSearch = str(
            "select ChangeType,VarName,VarType,OldValue,NewValue from AdministrativeTable where AppNo = '" + str(
                AppNumber) + "' and SessionNo = '" + str(each) + "' order by ABS(RecordNo) asc")
        cursor.execute(sqlSearch)
        result = cursor.fetchall()
        if type(result) is not types.NoneType:
            if len(result) > 0:
                for r in result:
                    if r[0] == "CHANGE":
                        if str(r[1]) in AdminDictionary:
                            if AdminDictionary[r[1]] == str(r[3]):
                                AdminDictionary[r[1]] = str(r[4])
                        else:
                            if str(r[1]) in OptionDictionary and OverWrite == True and OldApp == False:
                                OptionDictionary[str(r[1].encode('utf8', 'ignore'))] = str(
                                    r[4].encode('utf8', 'ignore'))
                            elif str(r[1]) in OptionDictionary and OverWrite == True and OldApp == True:
                                if str(r[1]) != "OutfallNarratives.OutfallDesc" and str(
                                        r[1]) != "OutfallNarratives.ProposedOutfall":
                                    OptionDictionary[str(r[1].encode('utf8', 'ignore'))] = str(
                                        r[4].encode('utf8', 'ignore'))
    return AdminDictionary, OptionDictionary


def OrderSessions(GetApp, parent, AppNumber, SearchList):
    conn = odbc.odbc(WaterQuality)
    cursor = conn.cursor()
    sqlSearch = str(
        "select SessionNo,ParentNo from SessionsTable where AppNo = '" + str(AppNumber) + "' and LineageNo = '" + str(
            SearchList[4]) + "' and ABS(OrderNo) <= ABS(" + str(SearchList[5]) + ") and ABS(SessionNo) <= ABS(" + str(
            SearchList[2]) + ") order by ABS(SessionNo) desc")
    cursor.execute(sqlSearch)
    result = cursor.fetchall()
    OrderedSessions = []
    OrderedSessions.append(SearchList[2])
    searchSession = SearchList[6]
    i = int(SearchList[6])
    while i > 0:
        for each in result:
            if each[0] == searchSession:
                OrderedSessions.append(each[0])
                searchSession = each[1]
                i = int(searchSession)
    return OrderedSessions


def AdminUpdate(parent, SessionNo, AppNo, VarName, OldValue, NewValue, ChangeType, VarType):
    conn = odbc.odbc(WaterQuality)
    cursor = conn.cursor()
    sqlSearch = str("select AppNo from AdministrativeTable")
    cursor.execute(sqlSearch)
    result = cursor.fetchall()
    if type(result) is not types.NoneType:
        RecordNo = len(result) + 1
    else:
        RecordNo = 1
    OldValue = OldValue.replace("'", "''")
    NewValue = NewValue.replace("'", "''")
    cursor.execute(
        "insert into AdministrativeTable (RecordNo,AppNo,SessionNo,ChangeType,VarName,VarType,OldValue,NewValue) VALUES ('" + str(
            RecordNo) +
        "','" + str(AppNo) + "','" + str(SessionNo) + "','" + str(ChangeType) + "','" + str(VarName) + "','" + str(
            VarType) + "','" + str(OldValue) + "','" +
        str(NewValue) + "')")


def HistoryUpdate(parent, CommentType, MPID, MPIDType, OldComment, NewComment, Date, PermitNo):
    conn = odbc.odbc(WaterQuality)
    cursor = conn.cursor()
    cursor.execute("insert into CommentsTable (cType,MPIDNo,mType,OldC,NewC,Date,Permit) VALUES ('" + str(
        CommentType) + "','" + str(MPID) + "','" + str(MPIDType) + "','" + str(OldComment) + "','" + str(
        NewComment) + "','" + str(Date) + "','" + str(PermitNo) + "')")


def WaterTransRedraw(parent, MPIDNumber, connList, searchList, LowerDate, UpperDate):
    import datetime
    import types

    cursor = connList[0].cursor()
    LengthBefore = len(searchList)
    if "WtDate" not in searchList:
        searchList.append("WtDate")
    LengthAfter = len(searchList)
    paramString = ",".join(searchList)
    sqlSearch = str("select " + paramString + " from DmlrWaterTrans where MpNo = " + str(MPIDNumber))
    cursor.execute(sqlSearch)
    RecordList = cursor.fetchall()
    FixedList = []
    CopyList = RecordList[:]
    if LengthBefore == LengthAfter:
        for each in CopyList:
            if each[0] < LowerDate or each[0] > UpperDate:
                if each in RecordList:
                    RecordList.remove(each)
    else:
        for each in CopyList:
            if each[LengthAfter - 1] < LowerDate or each[LengthAfter - 1] > UpperDate:
                FixedList.append(each)
                if each in RecordList:
                    RecordList.remove(each)
    CopyList = RecordList[:]
    for each in CopyList:
        firstcounter = 0
        while firstcounter < len(each):
            if type(each[firstcounter]) is types.NoneType or each[firstcounter] == "" or str(
                    each[firstcounter]) == "None" or str(each[firstcounter]) == "Null":
                if each in RecordList:
                    RecordList.remove(each)
            firstcounter += 1
    ResultList = []
    DateList = []
    emptyList = []
    i = 0
    if LengthBefore == LengthAfter:
        while i < LengthBefore - 1:
            ResultList.append(emptyList)
            i += 1
    else:
        while i < LengthBefore:
            ResultList.append(emptyList)
            i += 1
    if LengthBefore == LengthAfter:
        for result in RecordList:
            beancount = 0
            while beancount < len(ResultList):
                ResultList[beancount].append(float(result[beancount + 1]))
                beancount += 1
    else:
        for result in RecordList:
            beancount = 0
            while beancount < (len(ResultList)):
                ResultList[beancount].append(float(result[beancount]))

                beancount += 1
    if LengthBefore == LengthAfter:
        for result in RecordList:
            DateList.append(result[0])
    else:
        for result in RecordList:
            DateList.append(result[LengthAfter - 1])
    return ResultList, DateList


#This function will search WaterTrans for graphing purposes. It'll take in an MPID Number, the connList, and return a list of records.
def WTransFinder(parent, MPIDNumber, connList, HParam, VParam):
    import types

    cursor = connList[0].cursor()
    sqlSearch = str("select " + str(HParam) + "," + VParam + " from DmlrWaterTrans where MpNo = " + str(MPIDNumber))
    cursor.execute(sqlSearch)
    RecordList = cursor.fetchall()
    HList = []
    VList = []
    for each in RecordList:
        if str(each[1]) != "None" and str(each[1]) != "" and str(each[1]) != "Null" and type(
                each[1]) is not types.NoneType:
            VList.append(float(each[1]))
            HList.append(each[0])
    return HList, VList


#This function should add the application permit versions to the revision listbox and update the statusbar with the application number/inform the user
#that the application number isn't in the file.
def FindAppNumberRevisionList(parent, AppNumber, connList, statusBar):
    import datetime
    import types

    try:
        wqConn = odbc.odbc(WaterQuality)
        cursor2 = wqConn.cursor()
    except:
        print 'Failed to set WQCursor'
        wqConn = odbc.odbc(WaterQuality)
        cursor2 = wqConn.cursor()
    try:
        cursor = connList[2].cursor()
    except:
        epConn = odbc.odbc(DMMESDEConnection)
        cursor = epConn.cursor()
    sqlSearch = str("select RevNo,TblSeCode,TblWhCode from Dmlr_AppTracking where AppNo = '" + str(
        AppNumber) + "' order by ABS(RevNo) desc, AtStart desc")
    cursor.execute(sqlSearch)
    parent.ReviewNumber = "None"
    sessionsDict = {}
    displayedSessions = []
    result = cursor.fetchall()
    if type(result) is not types.NoneType:
        parent.MaxReviews = str(result[0][0])
        if len(result) > 0:
            for each in result:
                if str(each[1]) == 'H2O ':
                    parent.ReviewNumber = str(each[0])
                    break;
                if str(each[2]) == 'STW' or str(each[2]) == 'WWW':
                    parent.ReviewNumber = str(each[0])
                    break;
            if parent.ReviewNumber == "None":
                for each in result:
                    if str(each[1]) == 'PERM':
                        parent.ReviewNumber = str(each[0])
                        break;
            if parent.ReviewNumber != "None":
                statusBar = "Application #: " + str(AppNumber) + ", Review " + str(parent.MaxReviews)
                sessionsDict = {}
                sessionsDraftPublishList = []
                sessionsFinalPublishList = []
                sqlSearch = str("select SessionNo from DraftTable where AppNo = '" + str(AppNumber) + "'")
                cursor2.execute(sqlSearch)
                result = cursor2.fetchall()
                if type(result) is not types.NoneType:
                    for each in result:
                        sessionsDraftPublishList.append(str(each[0]))
                sqlSearch = str("select SessionNo from FinalPermitsTable where AppNo = '" + str(AppNumber) + "'")
                cursor2.execute(sqlSearch)
                result = cursor2.fetchall()
                if type(result) is not types.NoneType:
                    for each in result:
                        sessionsFinalPublishList.append(str(each[0]))
                displayedSessions = []
                displayedSessions.append("Current Data")
                sessionsDict["Current Data"] = "Current Data"
                sqlSearch = str(
                    "select RevNo,ExactDate,SessionNo,UserName,LineageNo,OrderNo,ParentNo from SessionsTable where AppNo = '" + str(
                        AppNumber) + "' order by ABS(RevNo) desc, ABS(LineageNo) desc, ABS(SessionNo) desc")
                cursor2.execute(sqlSearch)
                result = cursor2.fetchall()
                if type(result) is not types.NoneType:
                    for each in result:
                        try:
                            tempDate = datetime.datetime.strptime(each[1], "%Y-%m-%d %H:%M:%S.%f")
                        except:
                            tempDate = datetime.datetime.strptime(each[1], "%Y-%m-%d %H:%M:%S")
                        tempYear = tempDate.year
                        tempMonth = tempDate.month
                        tempDay = tempDate.day
                        tempHour = tempDate.hour
                        tempMinute = tempDate.minute
                        conDate = str(tempMonth) + "/" + str(tempDay) + "/" + str(tempYear)
                        conTime = str(tempHour) + ":" + str(tempMinute)
                        sessionstring = str(
                            "User " + str(each[3]).title() + ", Review " + str(each[0]) + ", Session " + str(
                                each[2]) + ", Lineage " + str(each[4]) + ", Order " + str(each[5]) + ", Parent " + str(
                                each[6]) + ", Created on " + str(conDate) + " at " + str(conTime))
                        sessionsDict[sessionstring] = each
                        if str(each[2]) not in sessionsDraftPublishList and str(
                                each[2]) not in sessionsFinalPublishList:
                            sqlSearch = str("select RecordNo from AdministrativeTable where AppNo = '" + str(
                                AppNumber) + "' and SessionNo = '" + str(each[2]) + "'")
                            cursor2.execute(sqlSearch)
                            result = cursor2.fetchone()
                            if type(result) is types.NoneType:
                                sqlSearch = str("select RecordNo from MPIDTable where AppNo = '" + str(
                                    AppNumber) + "' and SessionNo = '" + str(each[2]) + "'")
                                cursor2.execute(sqlSearch)
                                result = cursor2.fetchone()
                                if type(result) is types.NoneType:
                                    sqlSearch = str("select RecordNo from ParameterTable where AppNo = '" + str(
                                        AppNumber) + "' and SessionNo = '" + str(each[2]) + "'")
                                    cursor2.execute(sqlSearch)
                                    result = cursor2.fetchone()
                                    if type(result) is not types.NoneType:
                                        displayedSessions.append(sessionstring)
                                else:
                                    displayedSessions.append(sessionstring)
                            else:
                                displayedSessions.append(sessionstring)
                        else:
                            displayedSessions.append(sessionstring)
                displayedSessions.reverse()
                for each in displayedSessions:
                    tempitem = parent.GetRevList().InsertStringItem(0, each)
                    for draftsession in sessionsDraftPublishList:
                        if str("Session " + str(draftsession)) in each:
                            parent.GetRevList().SetItemBackgroundColour(tempitem, 'LIGHT BLUE')
                    for finalsession in sessionsFinalPublishList:
                        if str("Session " + str(finalsession)) in each:
                            parent.GetRevList().SetItemBackgroundColour(tempitem, 'PALE GREEN')
                parent.GetRevList().Refresh()
                parent.displayedSessions = displayedSessions
                parent.sessionsDict = sessionsDict
                return displayedSessions, statusBar, sessionsDict, displayedSessions
            else:
                displayedSessions = []
                statusBar = "This Application Number cannot be found."
                return displayedSessions, statusBar, sessionsDict, displayedSessions
        else:
            sqlSearch = str("select AppNo from FinalPermitsTable where PermitNo = '" + str(
                AppNumber) + "' order by ABS(RecordNo) desc")
            cursor2.execute(sqlSearch)
            result = cursor2.fetchone()
            if type(result) is not types.NoneType:
                AppNumber = result[0]
                sqlSearch = str("select RevNo,TblSeCode,TblWhCode from Dmlr_AppTracking where AppNo = '" + str(
                    AppNumber) + "' order by ABS(RevNo) desc, AtStart desc")
                cursor.execute(sqlSearch)
                parent.ReviewNumber = "None"
                sessionsDict = {}
                displayedSessions = []
                result = cursor.fetchall()
                if type(result) is not types.NoneType:
                    parent.MaxReviews = str(result[0][0])
                    if len(result) > 0:
                        for each in result:
                            if str(each[1]) == 'H2O ':
                                parent.ReviewNumber = str(each[0])
                                break;
                            if str(each[2]) == 'STW' or str(each[2]) == 'WWW':
                                parent.ReviewNumber = str(each[0])
                                break;
                        if parent.ReviewNumber != "None":
                            statusBar = "Application #: " + str(AppNumber) + ", Review " + str(parent.MaxReviews)
                            sessionsDict = {}
                            displayedSessions = []
                            #parent.GetRevList().InsertItems(["Current Data"],0)
                            displayedSessions.append("Current Data")
                            sessionsDict["Current Data"] = "Current Data"
                            sqlSearch = str(
                                "select RevNo,ExactDate,SessionNo,UserName,LineageNo,OrderNo,ParentNo "
                                "from SessionsTable where AppNo = '" + str(
                                    AppNumber) + "' order by ABS(RevNo) desc, ABS(LineageNo) desc, ABS(SessionNo) desc")
                            cursor2.execute(sqlSearch)
                            result = cursor2.fetchall()
                            if type(result) is not types.NoneType:
                                for each in result:
                                    tempDate = datetime.datetime.strptime(each[1], "%Y-%m-%d %H:%M:%S.%f")
                                    tempYear = tempDate.year
                                    tempMonth = tempDate.month
                                    tempDay = tempDate.day
                                    tempHour = tempDate.hour
                                    tempMinute = tempDate.minute
                                    conDate = str(tempMonth) + "/" + str(tempDay) + "/" + str(tempYear)
                                    conTime = str(tempHour) + ":" + str(tempMinute)
                                    sessionstring = str("User " + str(each[3]).title() + ", Review " + str(
                                        each[0]) + ", Session " + str(each[2]) + ", Lineage " + str(
                                        each[4]) + ", Order " + str(each[5]) + ", Parent " + str(
                                        each[6]) + ", Created on " + str(conDate) + " at " + str(conTime))
                                    sessionsDict[sessionstring] = each
                                    displayedSessions.append(sessionstring)
                            parent.GetRevList().InsertItems(displayedSessions, 0)
                            parent.displayedSessions = displayedSessions
                            parent.sessionsDict = sessionsDict
                            return displayedSessions, statusBar, sessionsDict, displayedSessions
                        else:
                            displayedSessions = []
                            statusBar = "This Application Number exists within the system, but has not yet gone through Water Quality."
                            return displayedSessions, statusBar, sessionsDict, displayedSessions
            else:
                statusBar = "This Application Number does not currently exist in the system."
                return displayedSessions, statusBar, sessionsDict, displayedSessions
    else:
        sqlSearch = str(
            "select AppNo from FinalPermitsTable where PermitNo = '" + str(AppNumber) + "' order by ABS(RecordNo) desc")
        cursor2.execute(sqlSearch)
        result = cursor2.fetchone()
        if type(result) is not types.NoneType:
            AppNumber = result[0]
            sqlSearch = str("select RevNo,TblSeCode,TblWhCode from Dmlr_AppTracking where AppNo = '" + str(
                AppNumber) + "' order by ABS(RevNo) desc, AtStart desc")
            cursor.execute(sqlSearch)
            parent.ReviewNumber = "None"
            sessionsDict = {}
            displayedSessions = []
            result = cursor.fetchall()
            if type(result) is not types.NoneType:
                if len(result) > 0:
                    for each in result:
                        if str(each[1]) == 'H2O ':
                            parent.ReviewNumber = str(each[0])
                            break;
                        if str(each[2]) == 'STW' or str(each[2]) == 'WWW':
                            parent.ReviewNumber = str(each[0])
                            break;
                    if parent.ReviewNumber != "None":
                        statusBar = "Application #: " + str(AppNumber) + ", Review " + str(parent.ReviewNumber)
                        sessionsDict = {}
                        displayedSessions = []
                        #parent.GetRevList().InsertItems(["Current Data"],0)
                        displayedSessions.append("Current Data")
                        sessionsDict["Current Data"] = "Current Data"
                        sqlSearch = str(
                            "select RevNo,ExactDate,SessionNo,UserName,LineageNo,OrderNo,ParentNo from SessionsTable where AppNo = '" + str(
                                AppNumber) + "' order by ABS(RevNo) desc, ABS(LineageNo) desc, ABS(SessionNo) desc")
                        cursor2.execute(sqlSearch)
                        result = cursor2.fetchall()
                        if type(result) is not types.NoneType:
                            for each in result:
                                tempDate = datetime.datetime.strptime(each[1], "%Y-%m-%d %H:%M:%S.%f")
                                tempYear = tempDate.year
                                tempMonth = tempDate.month
                                tempDay = tempDate.day
                                tempHour = tempDate.hour
                                tempMinute = tempDate.minute
                                conDate = str(tempMonth) + "/" + str(tempDay) + "/" + str(tempYear)
                                conTime = str(tempHour) + ":" + str(tempMinute)
                                sessionstring = str(
                                    "User " + str(each[3]).title() + ", Review " + str(each[0]) + ", Session " + str(
                                        each[2]) + ", Lineage " + str(each[4]) + ", Order " + str(
                                        each[5]) + ", Parent " + str(each[6]) + ", Created on " + str(
                                        conDate) + " at " + str(conTime))
                                sessionsDict[sessionstring] = each
                                displayedSessions.append(sessionstring)
                        parent.GetRevList().InsertItems(displayedSessions, 0)
                        parent.displayedSessions = displayedSessions
                        parent.sessionsDict = sessionsDict
                        return displayedSessions, statusBar, sessionsDict, displayedSessions
                    else:
                        displayedSessions = []
                        statusBar = "This Application Number exists within the system, but has not yet gone through Water Quality."
                        return displayedSessions, statusBar, sessionsDict, displayedSessions
        else:
            displayedSessions = []
            statusBar = "This Application Number does not currently exist in the system."
            return displayedSessions, statusBar, sessionsDict, displayedSessions


#This function will take the highlighted review and load its data into the appropriate fields
def StoreSession(username, userdate, application, review, session, lineage, order, parentNo):
    try:
        wqConn = odbc.odbc(WaterQuality)
        cursor = wqConn.cursor()
    except:
        wqConn = odbc.odbc(WaterQuality)
        cursor = wqConn.cursor()
    cursor.execute(
        "insert into SessionsTable (AppNo,RevNo,ExactDate,UserName,SessionNo,LineageNo,OrderNo,ParentNo) VALUES ('" + str(
            application) + "','" + str(review) + "','" + str(userdate) + "','" + str(username) + "','" + str(
            session) + "','" + str(lineage) + "','" + str(order) + "','" + str(parentNo) + "')")


################################################################################################
################DATA THREADS############DATA THREADS#################DATA THREADS###############
def GeologyDataThread(parent, AppNumber, RevisionNumber, mpGeoActionList, mpGeoLocNoList, mpGeoElevation, mpGeoNorthing,
                      mpGeoEasting, mpGeoAnalysis,
                      mpGeoExtractionRate, mpGeoOBDNMetals, mpGeoOBDNVolume, mpGeoCoalABA, mpGeoCoalVolume,
                      mpGeoCoalDepth, mpGeoCoalCode, mpGeoCoalName,
                      mpGeoCoalSeamCode, mpGeoCoalSeamName, mpGeoCoalThickness, mpGeoCoalElevation):
    WriteFileString('Starting Geology Thread')
    try:
        conn = odbc.odbc(DMMESDEConnection)
        cursor = conn.cursor()
    except:
        conn = odbc.odbc(DMMESDEConnection)
        cursor = conn.cursor()
    GeoActionList = []
    GeoLocNoList = []
    GeoElevation = []
    GeoNorthing = []
    GeoEasting = []
    GeoAnalysis = []
    sqlSearch = str(
        "select Action,LocNo,Elevation,Northing,Easting,Analysis from Geology_DataPoints where AppNo = '" + str(
            AppNumber) + "' and RevNo = " + str(RevisionNumber))
    cursor.execute(sqlSearch)
    result = cursor.fetchall()
    for each in result:
        GeoActionList.append(str(each[0]))
        GeoLocNoList.append(str(each[1]))
        GeoElevation.append(str(each[2]))
        GeoNorthing.append(str(each[3]))
        GeoEasting.append(str(each[4]))
        GeoAnalysis.append(str(each[5]))
    GeoCoalCode = []
    GeoCoalName = []
    GeoCoalSeamCode = []
    GeoCoalSeamName = []
    GeoCoalThickness = []
    GeoCoalElevation = []
    GeoCoalDepth = []
    GeoCoalVolume = []
    GeoCoalABA = []
    GeoOBDNVolume = []
    GeoOBDNMetals = []
    GeoExtractionRate = []
    sqlSearch = str(
        "select TblClCode,TblClName,TblCsCode,TblCsName,Thickness,Elevation from Geology_Seams where AppNo = '" + str(
            AppNumber) + "' and RevNo = " + str(RevisionNumber))
    cursor.execute(sqlSearch)
    result = cursor.fetchall()
    for each in result:
        GeoCoalCode.append(str(each[0]))
        GeoCoalName.append(str(each[1]))
        GeoCoalSeamCode.append(str(each[2]))
        GeoCoalSeamName.append(str(each[3]))
        GeoCoalThickness.append(str(each[4]))
        GeoCoalElevation.append(str(each[5]))
        GeoCoalDepth.append("NA")
        GeoCoalVolume.append("NA")
        GeoCoalABA.append("NA")
        GeoOBDNVolume.append("NA")
        GeoOBDNMetals.append("NA")
        GeoExtractionRate.append("NA")
    mpGeoActionList.append(GeoActionList)
    mpGeoLocNoList.append(GeoLocNoList)
    mpGeoElevation.append(GeoElevation)
    mpGeoNorthing.append(GeoNorthing)
    mpGeoEasting.append(GeoEasting)
    mpGeoAnalysis.append(GeoAnalysis)
    mpGeoExtractionRate.append(GeoExtractionRate)
    mpGeoOBDNMetals.append(GeoOBDNMetals)
    mpGeoOBDNVolume.append(GeoOBDNVolume)
    mpGeoCoalABA.append(GeoCoalABA)
    mpGeoCoalVolume.append(GeoCoalVolume)
    mpGeoCoalDepth.append(GeoCoalDepth)
    mpGeoCoalCode.append(GeoCoalCode)
    mpGeoCoalName.append(GeoCoalName)
    mpGeoCoalSeamCode.append(GeoCoalSeamCode)
    mpGeoCoalSeamName.append(GeoCoalSeamName)
    mpGeoCoalThickness.append(GeoCoalThickness)
    mpGeoCoalElevation.append(GeoCoalElevation)
    WriteFileString('Finished Geology Thread')


def LandUseDataThread(parent, AppNumber, RevisionNumber, mpLUPrePermeability, mpLUPrePermitPercent, mpLUPreRateofLoss,
                      mpLUPreLossLag, mpLUPreCode,
                      mpLUPreDesc, mpLUPreAcreage, mpLUPreAction, mpLUPostGainLag, mpLUPostRateofGain,
                      mpLUPostPermitPercent, mpLUPostPermeability,
                      mpLUPostCode, mpLUPostDesc, mpLUPostAcreage, mpLUPostAction):
    WriteFileString('Starting Land Use Thread')
    try:
        conn = odbc.odbc(DMMESDEConnection)
        cursor = conn.cursor()
    except:
        conn = odbc.odbc(DMMESDEConnection)
        cursor = conn.cursor()
    LUPreCode = []
    LUPreDesc = []
    LUPreAcreage = []
    LUPreAction = []
    LUPrePermeability = []
    LUPrePermitPercent = []
    LUPreRateofLoss = []
    LUPreLossLag = []
    sqlSearch = str("select TblLuCode,TblLuDesc,Acreage,Action from LandUse_PreLU where AppNo = '" + str(
        AppNumber) + "' and RevNo = " + str(RevisionNumber))
    cursor.execute(sqlSearch)
    result = cursor.fetchall()
    for each in result:
        LUPreCode.append(each[0])
        LUPreDesc.append(each[1])
        LUPreAcreage.append(each[2])
        LUPreAction.append(each[3])
        LUPrePermeability.append("NA")
        LUPrePermitPercent.append("NA")
        LUPreRateofLoss.append("NA")
        LUPreLossLag.append("NA")
    LUPostCode = []
    LUPostDesc = []
    LUPostAcreage = []
    LUPostAction = []
    LUPostPermeability = []
    LUPostRateofGain = []
    LUPostPermitPercent = []
    LUPostGainLag = []
    sqlSearch = str("select TblLuCode,TblLuDesc,Acreage,Action from LandUse_PostLU where AppNo = '" + str(
        AppNumber) + "' and RevNo = " + str(RevisionNumber))
    cursor.execute(sqlSearch)
    result = cursor.fetchall()
    for each in result:
        LUPostCode.append(each[0])
        LUPostDesc.append(each[1])
        LUPostAcreage.append(each[2])
        LUPostAction.append(each[3])
        LUPostPermeability.append("NA")
        LUPostPermitPercent.append("NA")
        LUPostRateofGain.append("NA")
        LUPostGainLag.append("NA")
    mpLUPrePermeability.append(LUPrePermeability)
    mpLUPrePermitPercent.append(LUPrePermitPercent)
    mpLUPreRateofLoss.append(LUPreRateofLoss)
    mpLUPreLossLag.append(LUPreLossLag)
    mpLUPreCode.append(LUPreCode)
    mpLUPreDesc.append(LUPreDesc)
    mpLUPreAcreage.append(LUPreAcreage)
    mpLUPreAction.append(LUPreAction)
    mpLUPostGainLag.append(LUPostGainLag)
    mpLUPostRateofGain.append(LUPostRateofGain)
    mpLUPostPermitPercent.append(LUPostPermitPercent)
    mpLUPostPermeability.append(LUPostPermeability)
    mpLUPostCode.append(LUPostCode)
    mpLUPostDesc.append(LUPostDesc)
    mpLUPostAcreage.append(LUPostAcreage)
    mpLUPostAction.append(LUPostAction)
    WriteFileString('Finished Land Use Thread')


def ExcessMaterialDataThread(parent, AppNumber, RevisionNumber, mpEMAction, mpEMID, mpEMDispKey, mpEMDispDesc,
                             mpEMDispTypeCode,
                             mpEMDispTypeDesc, mpEMFillSize, mpEMDispID, mpEMIsPerm, mpEMDrainCodes, mpEMDrainDesc,
                             mpEMMatCode,
                             mpEMMatDesc, mpEMRateofFill, mpEMFillLag):
    try:
        conn = odbc.odbc(DMMESDEConnection)
        cursor = conn.cursor()
    except:
        conn = odbc.odbc(DMMESDEConnection)
        cursor = conn.cursor()
    WriteFileString('Starting Disposal Use Thread')
    EMAction = []
    EMID = []
    EMDispKey = []
    EMDispDesc = []
    EMDispTypeCode = []
    EMDispTypeDesc = []
    EMFillSize = []
    EMDispID = []
    EMIsPerm = []
    EMRateofFill = []
    EMFillLag = []
    sqlSearch = str(
        "select keyDisposal,Action,IdNo,DisposalDesc,TblCrCode,TblCrDesc,DisposalPerm,FillSize,DisposalID from ExcessMat_Disposal where AppNo = '" + str(
            AppNumber) + "' and RevNo = " + str(RevisionNumber))
    cursor.execute(sqlSearch)
    result = cursor.fetchall()
    for each in result:
        EMDispKey.append(str(each[0]))
        EMAction.append(str(each[1]))
        EMID.append(str(each[2]))
        EMDispDesc.append(str(each[3]))
        EMDispTypeCode.append(str(each[4]))
        EMDispTypeDesc.append(str(each[5]))
        EMIsPerm.append(str(each[6]))
        EMFillSize.append(str(each[7]))
        EMDispID.append(str(each[8]))
        EMRateofFill.append("NA")
        EMFillLag.append("NA")
    EMDrainCodes = []
    EMDrainDesc = []
    EMMatCode = []
    EMMatDesc = []
    for each in EMDispKey:
        sqlSearch = str(
            "select TblMaCode,TblMaDesc from ExcessMat_MaterialType where keyDisposal = '" + str(each) + "'")
        cursor.execute(sqlSearch)
        result = cursor.fetchall()
        EMMatCodeTemp = []
        EMMatDescTemp = []
        EMDrainCodesTemp = []
        EMDrainDescTemp = []
        if type(result) is not types.NoneType:
            for r in result:
                if type(r) is not types.NoneType:
                    if type(r[0]) is not types.NoneType and type(r[1]) is not types.NoneType:
                        EMMatCodeTemp.append(r[0])
                        EMMatDescTemp.append(r[1])
            EMMatCode.append(",".join(list(set(EMMatCodeTemp))))
            EMMatDesc.append(",".join(list(set(EMMatDescTemp))))
        else:
            EMMatCode.append("NA")
            EMMatDesc.append("NA")
        sqlSearch = str("select TblDrCode,TblDrDesc from ExcessMat_DrainType where keyDisposal = '" + str(each) + "'")
        cursor.execute(sqlSearch)
        result = cursor.fetchall()
        if type(result) is not types.NoneType:
            for r in result:
                if type(r) is not types.NoneType:
                    if type(r[0]) is not types.NoneType and type(r[1]) is not types.NoneType:
                        EMDrainCodesTemp.append(r[0])
                        EMDrainDescTemp.append(r[1])
            EMDrainCodes.append(",".join(list(set(EMDrainCodesTemp))))
            EMDrainDesc.append(",".join(list(set(EMDrainDescTemp))))
        else:
            EMDrainCodes.append("NA")
            EMDrainDesc.append("NA")
    mpEMAction.append(EMAction)
    mpEMID.append(EMID)
    mpEMDispKey.append(EMDispKey)
    mpEMDispDesc.append(EMDispDesc)
    mpEMDispTypeCode.append(EMDispTypeCode)
    mpEMDispTypeDesc.append(EMDispTypeDesc)
    mpEMFillSize.append(EMFillSize)
    mpEMDispID.append(EMDispID)
    mpEMIsPerm.append(EMIsPerm)
    mpEMDrainCodes.append(EMDrainCodes)
    mpEMDrainDesc.append(EMDrainDesc)
    mpEMMatCode.append(EMMatCode)
    mpEMMatDesc.append(EMMatDesc)
    mpEMRateofFill.append(EMRateofFill)
    mpEMFillLag.append(EMFillLag)
    WriteFileString('Finished Disposal Use Thread')


def ClimateDataThread(parent, AppNumber, RevisionNumber, mpClimActionList, mpClimMPIDList, mpClimLocNoList,
                      mpClimFacLocList, mpClimTblQuDescList,
                      mpClimNorthingList, mpClimEastingList, mpClimStatusList, mpClimStatusNameList, mpClimType,
                      mpClimNameList, mpClimWSList,
                      mpClimWSNameList, mpClimChangeList, TMDLGeometries, TMDLWSCodeField, TMDLWSNameField,
                      TMDLWSOBIDField):
    WriteFileString('Starting Rain Gauge Thread')
    try:
        conn = odbc.odbc(DMMESDEConnection)
        conn2 = odbc.odbc(Dmlr_DB)
        conn3 = odbc.odbc(WaterQuality)
        wqConn = odbc.odbc(WaterQuality)
    except:
        conn = odbc.odbc(DMMESDEConnection)
        conn2 = odbc.odbc(Dmlr_DB)
        conn3 = odbc.odbc(WaterQuality)
        wqConn = odbc.odbc(WaterQuality)
    dxcursor = conn3.cursor()  #cursor for dxk_test database
    cursor2 = conn2.cursor()  #cursor for dmlr database
    cursor = conn.cursor()  #cursor for EP database
    wqCursor = wqConn.cursor()

    ClimActionList = []
    ClimMPIDList = []
    ClimLocNoList = []
    ClimFacLocList = []
    ClimTblQuDescList = []
    ClimNorthingList = []
    ClimEastingList = []
    ClimStatusList = []
    ClimStatusNameList = []
    ClimType = []
    ClimNameList = []
    ClimWSList = []
    ClimWSNameList = []
    ClimChangeList = []
    rrr = []
    sqlSearch = str("select Action,MPIDNo,LocNo,FacLoc,TblQuDesc,Northing,Easting,Status,TblMdDesc "
                    "from Hydro_CLMP where AppNo = '" + str(AppNumber) + "' and RevNo = " + str(RevisionNumber))
    cursor.execute(sqlSearch)
    result = cursor.fetchall()
    for each in result:
        addflag = 0
        if type(each[0]) is not types.NoneType:
            # If MPID exists, and Action is not "A":
            if str(each[1]) != "" and str(each[1]).upper() != "NONE" and str(each[0]).upper() != "A":
                sqlSearch = str("select FsRgDeleted from DmlrFactSheets where MpRgNo = '" + str(each[0]) + "'")
                cursor2.execute(sqlSearch)
                res = cursor2.fetchall()
                if type(res) is not types.NoneType:
                    for eachrecord in res:
                        if type(eachrecord[0]) is not types.NoneType:
                            if str(eachrecord[0]).upper() != "NONE":
                                pass
                        else:
                            addflag = 1
                    if addflag == 1:
                        rrr.append(each)
                else:
                    rrr.append(each)
            else:
                rrr.append(each)
        else:
            rrr.append(each)
    for each in rrr:
        if str(each[0]) == "None":
            ClimActionList.append("")
        else:
            ClimActionList.append(str(each[0]))
        ClimMPIDList.append(str(each[1]))
        ClimLocNoList.append(str(each[2]))
        ClimFacLocList.append(str(each[3]))
        ClimTblQuDescList.append(str(each[4]))
        ClimNorthingList.append(str(each[5]))
        ClimEastingList.append(str(each[6]))
        ClimStatusList.append(str(each[7]))
        ClimType.append(str(each[8]).title())
        ClimNameList.append(str(each[2]) + "-" + str(each[3]))
        ClimWSList.append("")
        ClimWSNameList.append("No TMDL")
        ClimStatusNameList.append("NOT CONSTRUCTED")
        ClimChangeList.append("")
    i = 0
    while i < len(ClimMPIDList):
        if str(ClimMPIDList[i]) == "None":
            sqlSearch = str("select MpNo,TblMsCode "
                            "from DmlrMpids "
                            "where (MpCompId = '" + str(ClimLocNoList[i]) + "' or MpFacilLoc = '" + str(
                ClimFacLocList[i]) + "') and (MPEasting = '" + str(ClimEastingList[i]) + "' or MPNorthing = '" + str(
                ClimNorthingList[i]) + "')")
            cursor2.execute(sqlSearch)
            result = cursor2.fetchall()
            if type(result) is not types.NoneType:
                if len(result) == 1:
                    ClimMPIDList[i] = str(result[0][0])
                    ClimStatusList[i] = str(result[0][1])
        i += 1
    for i in range(0, len(ClimMPIDList)):
        if str(ClimMPIDList[i]) != "None" and str(ClimMPIDList[i]) != "":
            tempEast = str(ClimEastingList[i]).split(".")
            tempNorth = str(ClimNorthingList[i]).split(".")
            if len(tempEast[0]) != 8 or len(tempNorth[0]) != 7:
                sqlSearch = str(
                    "select MpEasting,MpNorthing from DmlrMpids where (MpNo = '" + str(ClimMPIDList[i]) + "')")
                cursor2.execute(sqlSearch)
                result = cursor2.fetchone()
                ClimEastingList[i] = str(result[0])
                ClimNorthingList[i] = str(result[1])
    climcounter = 0
    while climcounter < len(ClimStatusList):
        if ClimStatusList[climcounter] == "A":
            ClimStatusNameList[climcounter] = "Active"
        elif ClimStatusList[climcounter] == "ND":
            ClimStatusNameList[climcounter] = "No Discharge"
        elif ClimStatusList[climcounter] == "NC":
            ClimStatusNameList[climcounter] = "Not Constructed"
        climcounter += 1
    i = 0
    while i < len(ClimMPIDList):
        if str(ClimActionList[i]) == "A":
            ClimChangeList[i] = "Climatological monitoring point " + ClimLocNoList[
                i] + " has been added to the permit through application " + str(AppNumber) + "."
        elif str(ClimActionList[i]) == "D":
            ClimChangeList[i] = "This climatological monitoring point has been deleted from this permit."
        elif str(ClimActionList[i]) == "C" and str(ClimMPIDList[i]) != "None" and str(ClimMPIDList[i]) != "":
            ClimChangeList[i] = ""
            sqlSearch = str(
                "select TblMsCode,MpCompId,MpFacilLoc,TblQuCode,MpEasting,MpNorthing from DmlrMpids where MpNo = '" + str(
                    ClimMPIDList[i]) + "'")
            cursor2.execute(sqlSearch)
            result = cursor2.fetchone()
            sqlSearch = str(
                "select Status,LocNo,FacLoc,TblQuCode,Easting,Northing from Hydro_CLMP where AppNo = '" + str(
                    AppNumber) + "' and RevNo = 1 and MPIDNo = '" + str(ClimMPIDList[i]) + "'")
            cursor.execute(sqlSearch)
            result2 = cursor.fetchone()
            tempMsCode2 = str(result2[0])
            tempLocNo2 = str(result2[1])
            tempFacLoc2 = str(result2[2])
            tempQuCode2 = str(result2[3])
            tempEasting2 = str(result2[4])
            tempNorthing2 = str(result2[5])
            tempMsCode = str(result[0])
            tempLocNo = str(result[1])
            tempFacLoc = str(result[2])
            tempQuCode = str(result[3])
            tempEasting = str(result[4])
            tempNorthing = str(result[5])
            if tempLocNo != str(ClimLocNoList[i]):
                if tempLocNo == "None":
                    ClimChangeList[i] += str(
                        "The name of this climatological monitoring point has been added as " + str(
                            ClimLocNoList[i]) + ". ")
                else:
                    ClimChangeList[i] += str(
                        "The name of this climatological monitoring point has been changed from " + tempLocNo + " to " + str(
                            ClimLocNoList[i]) + ". ")
            else:
                if tempLocNo2 != str(ClimLocNoList[i]):
                    if tempLocNo2 == "None":
                        ClimChangeList[i] += str(
                            "The name of this climatological monitoring point has been added as " + str(
                                ClimLocNoList[i]) + ". ")
                    else:
                        ClimChangeList[i] += str(
                            "The name of this climatological monitoring point has been changed from " + tempLocNo2 + " to " + str(
                                ClimLocNoList[i]) + ". ")
            if tempEasting != str(ClimEastingList[i]):
                if tempEasting == "None":
                    ClimChangeList[i] += str(
                        "The easting coordinate of the climatological monitoring point (VASP) has been added as " + str(
                            ClimEastingList[i]) + ". ")
                else:
                    ClimChangeList[i] += str(
                        "The easting coordinate of the climatological monitoring point (VASP) has been changed from " + tempEasting + " to " + str(
                            ClimEastingList[i]) + ". ")
            else:
                if tempEasting2 != str(ClimEastingList[i]):
                    if tempEasting2 == "None":
                        ClimChangeList[i] += str(
                            "The easting coordinate of the climatological monitoring point (VASP) has been added as " + str(
                                ClimEastingList[i]) + ". ")
                    else:
                        ClimChangeList[i] += str(
                            "The easting coordinate of the climatological monitoring point (VASP) has been changed from " + tempEasting2 + " to " + str(
                                ClimEastingList[i]) + ". ")
            if tempNorthing != str(ClimNorthingList[i]):
                if tempNorthing == "None":
                    ClimChangeList[i] += str(
                        "The northing coordinate of the climatological monitoring point (VASP) has been added as " + str(
                            ClimNorthingList[i]) + ". ")
                else:
                    ClimChangeList[i] += str(
                        "The northing coordinate of the climatological monitoring point (VASP) has been changed from " + tempNorthing + " to " + str(
                            ClimNorthingList[i]) + ". ")
            else:
                if tempNorthing2 != str(ClimNorthingList[i]):
                    if tempNorthing2 == "None":
                        ClimChangeList[i] += str(
                            "The northing coordinate of the climatological monitoring point (VASP) has been added as " + str(
                                ClimNorthingList[i]) + ". ")
                    else:
                        ClimChangeList[i] += str(
                            "The northing coordinate of the climatological monitoring point (VASP) has been changed from " + tempNorthing2 + " to " + str(
                                ClimNorthingList[i]) + ". ")
        i += 1
    #####################################TMDL SELECTION MODULE#######################################
    counter = 0
    while counter < len(ClimMPIDList):
        point = ogr.Geometry(ogr.wkbPoint)
        point.AddPoint(float(ClimEastingList[counter]), float(ClimNorthingList[counter]))
        for wtsd in TMDLGeometries:
            w = ogr.CreateGeometryFromWkt(wtsd)
            if w.Contains(point):
                ClimWSList[counter] = str(TMDLWSCodeField[TMDLGeometries.index(wtsd)])
                ClimWSNameList[counter] = str(TMDLWSNameField[TMDLGeometries.index(wtsd)])
        counter += 1
    #####################################TMDL SELECTION MODULE#######################################

    mpClimActionList.append(ClimActionList)
    mpClimMPIDList.append(ClimMPIDList)
    mpClimLocNoList.append(ClimLocNoList)
    mpClimFacLocList.append(ClimFacLocList)
    mpClimTblQuDescList.append(ClimTblQuDescList)
    mpClimNorthingList.append(ClimNorthingList)
    mpClimEastingList.append(ClimEastingList)
    mpClimStatusList.append(ClimStatusList)
    mpClimStatusNameList.append(ClimStatusNameList)
    mpClimType.append(ClimType)
    mpClimNameList.append(ClimNameList)
    mpClimWSList.append(ClimWSList)
    mpClimWSNameList.append(ClimWSNameList)
    mpClimChangeList.append(ClimChangeList)
    WriteFileString('Finished Rain Gauge Thread')


def NPDESDataThread(parent, AppNumber, RevisionNumber, NPMPIDList, NPActionList, NPChangeList, NPLocNoList,
                    NPWaterShedAcresList, NPDisturbedAcresList,
                    NPTblSrCodeList, NPTblSrNameList, NPElevationList, NPEastingList, NPNorthingList, NPWSList,
                    NPWSNameList, NPNameList, NPTierDesList,
                    NPDistList, NPImpairList, NPUseDescList, NPCauseName, NPRepWET, WaterTransDict, WaterFieldList,
                    NPAgeList, NPAcidList, NPBigList,
                    NPDrainCatList, NPWSFlowList, LDTblDict, StressTranslator, NPRepChem, NPStatusList, NPFacLocList,
                    mpNarrWQCheckbox, mpNumWQCheckbox,
                    mpStandardCheckbox, mpSMCRASpecialCheckbox, mpReceivingFlowCheckbox, mpTechLimitsCheckbox,
                    mpSMCRAStandardCheckbox, mpTMDLCheckbox,
                    mpReminingCheckbox, mpInterstateCheckbox, mpWETViolation, mpWQLimit, mpUniqueTMDLS,
                    mpNPDischargeType, mpNPMPIDOutfallCheckList, mpOutfallDischargeLocations, mpNPWSList,
                    mpNPWSNameList, mpNPWSFlowList, mpNPTierDesList,
                    mpNPDistList, mpNPCauseName, mpNPImpairList, mpNPUseDescList, mpNPChangeList, mpNPRepWET,
                    mpNPBigList, mpFlowRatioList, mpStressorList,
                    mpNPStressNames, mpstressString, mptmdlString, mpAltEffLimitsNarrative,
                    mpPCBMonitoringPlanNecessary, mpNarrativeStandards,
                    mpNarrativeStandardsText, mpNumericStandards, mpNumericStandardsText, mpStandardConditions,
                    mpStandardConditionsText, mpSpecialConditions,
                    mpSpecialConditionsText, mpMixingZoneConditions, mpMixingZoneConditionsText, mpTechnologyLimits,
                    mpTechnologyLimitsText, mpSMCRAStandard,
                    mpSMCRAStandardText, mpTMDLWatershed, mpTMDLWatershedText, mpReminingConditions,
                    mpReminingConditionsText, mpInterstateEffect,
                    mpInterstateEffectText, mpRainfallExclusion, mpRainfallExclusionText, mpTSSBenthicImpairment,
                    mpTSSBenthicImpairmentText,
                    mpComplianceRequirement, mpComplianceRequirementText, mpTSSOffset, mpTSSOffsetText,
                    mpSSPMRequirement, mpSSPMRequirementText,
                    mpNPDESOutfallDescriptionText, mpRepresentativeSamplingText, mpEffluentScreeningText,
                    TMDLGeometries, TMDLWSCodeField, TMDLWSNameField, TMDLWSOBIDField, mpNPParamPlotList,
                    mpNPParamLoadPlotList,
                    NPParamPlotList, NPParamLoadPlotList):
    WriteFileString('Starting NPDES Assignment Thread')
    try:
        conn = odbc.odbc(DMMESDEConnection)
        conn2 = odbc.odbc(Dmlr_DB)
        conn3 = odbc.odbc(WaterQuality)
    except:
        conn = odbc.odbc(DMMESDEConnection)
        conn2 = odbc.odbc(Dmlr_DB)
        conn3 = odbc.odbc(WaterQuality)
    dxcursor = conn3.cursor()  #cursor for dxk_test database
    cursor2 = conn2.cursor()  #cursor for dmlr database
    cursor = conn.cursor()  #cursor for EP database
    i = 0
    while i < len(NPMPIDList):
        if str(NPActionList[i]) == "A":
            NPChangeList[i] = "Outfall " + NPLocNoList[i] + " has been added to the permit through application " + str(
                AppNumber) + "."
        elif str(NPActionList[i]) == "D":
            NPChangeList[i] = "This outfall has been deleted from this permit."
        elif str(NPActionList[i]) == "C" and str(NPMPIDList[i]) != "None" and str(NPMPIDList[i]) != "":
            NPChangeList[i] = ""

            sqlSearch = str("select TblMsCode,MpCompId,MpWtsdAcre,MpDistAcre,MpFacilLoc,TblSrCode,"
                            "TblQuCode,MpElevation,MpFrqQtr,MpEasting,MpNorthing "
                            "from DmlrMpids where MpNo = '" + str(NPMPIDList[i]) + "'")
            cursor2.execute(sqlSearch)
            result = cursor2.fetchone()

            sqlSearch = str("select Status,LocNo,WaterShedAcres,DisturbedAcres,FacLoc,TblSrCode,"
                            "TblQuCode,Elevation,Frequency,Easting,Northing "
                            "from Hydro_PollutionDis "
                            "where AppNo = '" + str(AppNumber) + "' and RevNo = '" + str(
                RevisionNumber) + "' and MPIDNo = '" + str(NPMPIDList[i]) + "'")
            cursor.execute(sqlSearch)
            result2 = cursor.fetchone()
            tempMsCode2 = str(result2[0])
            tempLocNo2 = str(result2[1])
            tempWtsdAcre2 = str(result2[2])
            tempDistAcre2 = str(result2[3])
            tempFacLoc2 = str(result2[4])
            tempSrCode2 = str(result2[5])
            tempQuCode2 = str(result2[6])
            tempElevation2 = str(result2[7])
            tempFreq2 = str(result2[8])
            tempEasting2 = str(result2[9])
            tempNorthing2 = str(result2[10])
            tempMsCode = str(result[0])
            tempLocNo = str(result[1])
            tempWtsdAcre = str(result[2])
            tempDistAcre = str(result[3])
            tempFacLoc = str(result[4])
            tempSrCode = str(result[5])
            tempQuCode = str(result[6])
            tempElevation = str(result[7])
            tempFreq = str(result[8])
            tempEasting = str(result[9])
            tempNorthing = str(result[10])
            if tempWtsdAcre != str(NPWaterShedAcresList[i]):
                if tempWtsdAcre == "None":
                    NPChangeList[i] += str("A watershed area flowing to this outfall has been added as " + str(
                        NPWaterShedAcresList[i]) + " acres. ")
                else:
                    NPChangeList[i] += str(
                        "The watershed area flowing to this outfall has been changed from " + tempWtsdAcre + " acres to " + str(
                            NPWaterShedAcresList[i]) + " acres. ")
            else:
                if tempWtsdAcre2 != str(NPWaterShedAcresList[i]):
                    if tempWtsdAcre2 == "None":
                        NPChangeList[i] += str("A watershed area flowing to this outfall has been added as " + str(
                            NPWaterShedAcresList[i]) + " acres. ")
                    else:
                        NPChangeList[i] += str(
                            "The watershed area flowing to this outfall has been changed from " + tempWtsdAcre2 + " acres to " + str(
                                NPWaterShedAcresList[i]) + " acres. ")
            if tempDistAcre != str(NPDisturbedAcresList[i]):
                if tempDistAcre == "None":
                    NPChangeList[i] += str("A watershed area flowing to this outfall has been added as " + str(
                        NPDisturbedAcresList[i]) + " acres. ")
                else:
                    NPChangeList[i] += str(
                        "The disturbed acreage within this outfall's watershed has been changed from " + tempDistAcre + " acres to " + str(
                            NPDisturbedAcresList[i]) + " acres. ")
            else:
                if tempDistAcre2 != str(NPDisturbedAcresList[i]):
                    if tempDistAcre2 == "None":
                        NPChangeList[i] += str("A watershed area flowing to this outfall has been added as " + str(
                            NPDisturbedAcresList[i]) + " acres. ")
                    else:
                        NPChangeList[i] += str(
                            "The disturbed acreage within this outfall's watershed has been changed from " + tempDistAcre2 + " acres to " + str(
                                NPDisturbedAcresList[i]) + " acres. ")
            if tempLocNo != str(NPLocNoList[i]):
                if tempLocNo == "None":
                    NPChangeList[i] += str("The name of this outfall has been added as " + str(NPLocNoList[i]) + ". ")
                else:
                    NPChangeList[i] += str("The name of this outfall has been changed from " + tempLocNo + " to " + str(
                        NPLocNoList[i]) + ". ")
            else:
                if tempLocNo2 != str(NPLocNoList[i]):
                    if tempLocNo2 == "None":
                        NPChangeList[i] += str(
                            "The name of this outfall has been added as " + str(NPLocNoList[i]) + ". ")
                    else:
                        NPChangeList[i] += str(
                            "The name of this outfall has been changed from " + tempLocNo2 + " to " + str(
                                NPLocNoList[i]) + ". ")
            if tempSrCode != str(NPTblSrCodeList[i]):
                sqlSearch1 = str("select TblSrName from StreamTbl where TblSrCode = " + str(tempSrCode))
                cursor.execute(sqlSearch1)
                res = cursor.fetchone()
                tempSrName = str(res[0]).title()
                if tempSrName == "None":
                    NPChangeList[i] += str("The stream which the outfall discharges to has been added as " + str(
                        NPTblSrNameList[i]) + ". ")
                else:
                    NPChangeList[i] += str(
                        "The stream which the outfall discharges to has been changed from " + tempSrName + " to " + str(
                            NPTblSrNameList[i]) + ". ")
            else:
                if tempSrCode2 != str(NPTblSrCodeList[i]):
                    sqlSearch1 = str("select TblSrName from StreamTbl where TblSrCode = " + str(tempSrCode2))
                    cursor.execute(sqlSearch1)
                    res = cursor.fetchone()
                    tempSrName = str(res[0]).title()
                    if tempSrName == "None":
                        NPChangeList[i] += str("The stream which the outfall discharges to has been added as " + str(
                            NPTblSrNameList[i]) + ". ")
                    else:
                        NPChangeList[i] += str(
                            "The stream which the outfall discharges to has been changed from " + tempSrName + " to " + str(
                                NPTblSrNameList[i]) + ". ")
            if tempElevation != str(NPElevationList[i]):
                if tempElevation == "None":
                    NPChangeList[i] += str(
                        "The elevation of the outfall has been added as " + str(NPElevationList[i]) + ". ")
                else:
                    NPChangeList[i] += str(
                        "The elevation of the outfall has changed from " + tempElevation + " to " + str(
                            NPElevationList[i]) + ". ")
            else:
                if tempElevation2 != str(NPElevationList[i]):
                    if tempElevation2 == "None":
                        NPChangeList[i] += str(
                            "The elevation of the outfall has been added as " + str(NPElevationList[i]) + ". ")
                    else:
                        NPChangeList[i] += str(
                            "The elevation of the outfall has changed from " + tempElevation2 + " to " + str(
                                NPElevationList[i]) + ". ")
            if tempEasting != str(NPEastingList[i]):
                if tempEasting == "None":
                    NPChangeList[i] += str("The easting coordinate of the outfall (VASP) has been added as " + str(
                        NPEastingList[i]) + ". ")
                else:
                    NPChangeList[i] += str(
                        "The easting coordinate of the outfall (VASP) has been changed from " + tempEasting + " to " + str(
                            NPEastingList[i]) + ". ")
            else:
                if tempEasting2 != str(NPEastingList[i]):
                    if tempEasting2 == "None":
                        NPChangeList[i] += str("The easting coordinate of the outfall (VASP) has been added as " + str(
                            NPEastingList[i]) + ". ")
                    else:
                        NPChangeList[i] += str(
                            "The easting coordinate of the outfall (VASP) has been changed from " + tempEasting2 + " to " + str(
                                NPEastingList[i]) + ". ")
            if tempNorthing != str(NPNorthingList[i]):
                if tempNorthing == "None":
                    NPChangeList[i] += str("The northing coordinate of the outfall (VASP) has been added as " + str(
                        NPNorthingList[i]) + ". ")
                else:
                    NPChangeList[i] += str(
                        "The northing coordinate of the outfall (VASP) has been changed from " + tempNorthing + " to " + str(
                            NPNorthingList[i]) + ". ")
            else:
                if tempNorthing2 != str(NPNorthingList[i]):
                    if tempNorthing2 == "None":
                        NPChangeList[i] += str("The northing coordinate of the outfall (VASP) has been added as " + str(
                            NPNorthingList[i]) + ". ")
                    else:
                        NPChangeList[i] += str(
                            "The northing coordinate of the outfall (VASP) has been changed from " + tempNorthing2 + " to " + str(
                                NPNorthingList[i]) + ". ")
        i += 1
    #####################################TMDL SELECTION MODULE#######################################
    counter = 0
    while counter < len(NPMPIDList):
        point = ogr.Geometry(ogr.wkbPoint)
        point.AddPoint(float(NPEastingList[counter]), float(NPNorthingList[counter]))
        for wtsd in TMDLGeometries:
            w = ogr.CreateGeometryFromWkt(wtsd)
            if w.Contains(point):
                NPWSList[counter] = str(TMDLWSCodeField[TMDLGeometries.index(wtsd)])
                NPWSNameList[counter] = str(TMDLWSNameField[TMDLGeometries.index(wtsd)])
        counter += 1
    #####################################TMDL SELECTION MODULE#######################################
    #####################################TIER SELECTION MODULE#######################################
    i = 0
    while i < len(NPNameList):
        try:
            sqlSearch = str(
                "select WATER_STATUS,USE_DESCRIPTION,CAUSE_NAME from Sr303d where SrCode =" + str(NPTblSrCodeList[i]))
            dxcursor.execute(sqlSearch)
            result = dxcursor.fetchone()
        except:
            result = "None"
        if str(result) != "None":
            NPTierDesList[i] = "Tier I"
            NPDistList[i] = "303d"
            NPImpairList[i] = str(result[0])
            NPUseDescList[i] = str(result[1])
            NPCauseName[i] = str(result[2])
        else:
            try:
                sqlSearch = str("select WATER_STATUS,USE_DESCRIPTION,CAUSE_NAME from Sr305b where SrCode=" + str(
                    NPTblSrCodeList[i]))
                result = dxcursor.fetchone()
            except:
                result = "None"
            if str(result) != "None":
                NPTierDesList[i] = "Tier I"
                NPDistList[i] = "305b"
                NPImpairList[i] = str(result[0])
                NPUseDescList[i] = str(result[1])
                NPCauseName[i] = str(result[2])
            else:
                if NPWSNameList[i] != "No TMDL":
                    NPTierDesList[i] = "Tier I"
                    NPDistList[i] = "TMDL"
                    NPCauseName[i] = "In " + str(NPWSNameList[i]) + " TMDL"
        i += 1
        #####################################TIER SELECTION MODULE#######################################
        ####################################Representative Chemical Module###############################
    ##            i = 0
    ##            while i < len(NPMPIDList):
    ##                ThirtyTwoCount = 0
    ##                if str(NPMPIDList[i]) != "None" and str(NPStatusList[i]) == "A":
    ##                    for each in WaterTransDict:
    ##                        if WaterTransDict[each] in WaterFieldList and WaterTransDict[each] not in TechStandardsList and WaterTransDict[each] not in WETList and WaterTransDict[each] not in SolidsList:
    ##                            sqlSearch = str("select " + WaterTransDict[each] + " from DmlrWaterTrans where MpNo = " + str(NPMPIDList[i]))
    ##                            cursor2.execute(sqlSearch)
    ##                            result = cursor2.fetchall()
    ##                            ParameterCounter = 0
    ##                            TotalCounter = 0
    ##                            for record in result:
    ##                                TotalCounter += 1
    ##                                if str(record[0]) != "None" and str(record[0]) != "" and str(record[0]) != "Null":
    ##                                    ParameterCounter += 1
    ##                            if float(ParameterCounter)/float(TotalCounter) > 0:
    ##                                ThirtyTwoCount += 1
    ##                if ThirtyTwoCount > 3:
    ##                    NPRepChem[i] = "Yes"
    ##                i += 1
    ####################################Representative Chemical Module###############################
    ####################################Representative WET Module####################################
    i = 0
    while i < len(NPMPIDList):
        WETCount = 0
        NPRepWET[i] = "No"
        i += 1
    ####################################Representative WET Module####################################
    ####################################Initial Assignments Module###################################
    FlowRatioList = []
    StressorList = []
    NPShortDict = {}
    searchString = ""
    NPStressList = []
    paramIndex = []
    for each in WaterTransDict:
        if WaterTransDict[each] in WaterFieldList:
            paramIndex.append(WaterTransDict[each])
            NPShortDict[each] = each
            searchString += WaterTransDict[each]
            searchString += ","
    WriteFileString('Gathering NPDES Parameter Data')
    i = 0
    while i < len(NPMPIDList):
        if NPAgeList[i] == "Old":
            if NPAcidList[i] == "Acid":
                NPBigList[i][6][1] = "3.5"
                NPBigList[i][6][8] = "7.0"
                NPBigList[i][7][1] = "2.0"
                NPBigList[i][7][8] = "4.0"
            elif NPAcidList[i] == "Alkaline":
                NPBigList[i][6][1] = "3.5"
                NPBigList[i][7][8] = "7.0"
        elif NPAgeList[i] == "New":
            if NPAcidList[i] == "Acid" and str(NPDrainCatList[i]) != '5':
                NPBigList[i][6][1] = "3.0"
                NPBigList[i][6][8] = "6.0"
                NPBigList[i][7][1] = "2.0"
                NPBigList[i][7][8] = "4.0"
            elif NPAcidList[i] == "Alkaline" and str(NPDrainCatList[i]) != '5':
                NPBigList[i][6][1] = "3.0"
                NPBigList[i][6][8] = "6.0"
        if str(NPDrainCatList[i]) == "5":
            NPBigList[i][9][8] == "0.5"
        else:
            NPBigList[i][4][1] == "35"
            NPBigList[i][4][8] == "70"
        draincount = 0
        while draincount < len(NPBigList[i]):
            if str(draincount) != "0" and str(draincount) != "1" and str(draincount) != "2" and str(
                    draincount) != "3" and str(draincount) != "10" and str(draincount) != "5" and str(
                    draincount) != "11" and str(draincount) != "8" and str(draincount) != "9" and int(draincount) < 11:
                if NPDrainCatList[i] == "1":
                    NPBigList[i][draincount][17] = "0.2 In"
                elif NPDrainCatList[i] == "2":
                    NPBigList[i][draincount][17] = "10Y/24H"
                elif NPDrainCatList[i] == "3":
                    NPBigList[i][draincount][17] = "NA"
                elif NPDrainCatList[i] == "4":
                    NPBigList[i][draincount][17] = "1Y/24H"
                else:
                    NPBigList[i][draincount][17] = "NA"
            draincount += 1
        if NPWSList[i] != "None" and NPWSList[i] != "":
            sqlSearch = "select TblLdCode,TWsAvgFlow,TWsParamForEst,TWsWLA,TWsWaterTransDefault from DmlrTMDLWaterShed_Stressor where TWsCode = " + str(
                NPWSList[i])
            cursor2.execute(sqlSearch)
            result = cursor2.fetchall()
            numStressors = len(result)
            smallstressstring = ""
            j = 0
            while j < numStressors:
                if numStressors - j != 1:
                    smallstressstring += str(result[j][0])
                    smallstressstring += ", "
                else:
                    smallstressstring += str(result[j][0])
                NPStressList.append(result[j][0].upper())
                NPWSFlowList[i] = (str(result[j][1]))
                for each in LDTblDict:
                    if result[j][0].upper() == LDTblDict[each]:
                        if int(each) != 5:
                            NPBigList[i][int(each)][8] = str(result[j][4])
                            NPBigList[i][int(each)][1] = str(result[j][2])
                            NPBigList[i][int(each)][17] = "NA"
                        elif int(each) == 5:
                            NPBigList[i][int(each)][8] = "NL"
                            NPBigList[i][int(each)][1] = "NL"
                            NPBigList[i][int(each)][17] = "NA"
                j += 1
            StressorList.append(smallstressstring)
        else:
            StressorList.append("None")
        if NPMPIDList[i] != "None":
            sqlSearch = str("select WtFlow,WtDate from DmlrWaterTrans where MpNo = " + str(NPMPIDList[i]))
            cursor2.execute(sqlSearch)
            result = cursor2.fetchall()
            flow = []
            DateList = []
            flowcounter = 0
            for record in result:
                if type(record[0]) is not types.NoneType and str(record[0]) != "" and str(record[0]) != "None" and str(
                        record[0]) != "Null":
                    flow.append(float(record[0]))
                    DateList.append(record[1])
                    if float(record[0]) != 0:
                        flowcounter += 1
            if len(flow) > 0:
                flowavg = sum(flow) / len(flow)
                FlowRatioList.append(float((float(flowcounter) / float(len(flow)))))
            else:
                flowavg = 0
                FlowRatioList.append(float(0))
            sqlSearch = str("select " + searchString + "WtDate from DmlrWaterTrans where MpNo = " + str(NPMPIDList[i]))
            cursor2.execute(sqlSearch)
            result = cursor2.fetchall()
            for entry in NPShortDict:
                resultCount = 0
                ResultList = []
                DateList = []
                LoadResultList = []
                plotList = []
                plotLoadList = []
                while resultCount < len(result):
                    if type(result[resultCount][
                        int(paramIndex.index(WaterTransDict[entry]))]) is not types.NoneType and str(
                            result[resultCount][int(paramIndex.index(WaterTransDict[entry]))]) != "" and str(
                            result[resultCount][
                                int(paramIndex.index(WaterTransDict[entry]))]).upper() != "NONE" and str(
                            result[resultCount][int(paramIndex.index(WaterTransDict[entry]))]).upper() != "NULL":
                        ResultList.append(float(result[resultCount][int(paramIndex.index(WaterTransDict[entry]))]))
                        plotList.append([float(result[resultCount][int(paramIndex.index(WaterTransDict[entry]))]),
                                         str(result[resultCount][len(NPShortDict)])])
                        if type(result[resultCount][int(paramIndex.index('WtFlow'))]) is not types.NoneType and str(
                                result[resultCount][int(paramIndex.index('WtFlow'))]) != "" and str(
                                result[resultCount][int(paramIndex.index('WtFlow'))]).upper() != "NONE" and str(
                                result[resultCount][int(paramIndex.index('WtFlow'))]).upper() != "NULL":
                            LoadResultList.append(
                                (float(result[resultCount][int(paramIndex.index(WaterTransDict[entry]))])) * (
                                float(result[resultCount][int(paramIndex.index('WtFlow'))])))
                            plotLoadList.append([
                                (float(result[resultCount][int(paramIndex.index(WaterTransDict[entry]))])) * (
                                float(result[resultCount][int(paramIndex.index('WtFlow'))])),
                                str(result[resultCount][len(NPShortDict)])])
                    resultCount += 1
                if len(ResultList) > 0:
                    NPParamPlotList[i][int(entry)] = plotList
                    meanResult = sum(ResultList) / len(ResultList)
                    NPBigList[i][int(entry)][5] = str(len(ResultList))
                    NPBigList[i][int(entry)][4] = str(np.std(ResultList))
                    NPBigList[i][int(entry)][3] = str(meanResult)
                    NPBigList[i][int(entry)][7] = str(min(ResultList))
                    NPBigList[i][int(entry)][9] = str(max(ResultList))
                    if len(LoadResultList) > 0:
                        if NPBigList[i][int(entry)][0] == "mg/L" or NPBigList[i][int(entry)][0] == "mL/L":
                            for l in range(0, len(plotLoadList)):
                                plotLoadList[l][0] = plotLoadList[l][0] * .005451
                        elif NPBigList[i][int(entry)][0] == "ug/L":
                            for l in range(0, len(plotLoadList)):
                                plotLoadList[l][0] = plotLoadList[l][0] * .000005451
                        NPParamLoadPlotList[i][int(entry)] = plotLoadList
                        meanLoadResult = sum(LoadResultList) / len(LoadResultList)
                        if NPBigList[i][int(entry)][0] == "mg/L":
                            NPBigList[i][int(entry)][16] = str(meanLoadResult * .16591)
                        elif NPBigList[i][int(entry)][0] == "ug/L":
                            NPBigList[i][int(entry)][16] = str(meanLoadResult * .001659)
        else:
            FlowRatioList.append(float(0))
        i += 1
    catcount = 0
    while catcount < len(NPDrainCatList):
        if str(NPDrainCatList[catcount]) == "5":
            NPBigList[catcount][9][8] = "0.5"
        else:
            NPBigList[catcount][4][1] = "35"
            NPBigList[catcount][4][8] = "70"
        catcount += 1
    fillcount = 0
    while fillcount < len(NPBigList):
        innercount = 0
        if NPBigList[fillcount][5][3] != "NA":
            if float(NPBigList[fillcount][5][3]) > float(420) and str(NPDrainCatList[fillcount]) != "5":
                if NPBigList[fillcount][5][1] == "NA":
                    NPBigList[fillcount][5][1] = "NL"
                if NPBigList[fillcount][5][8] == "NA":
                    NPBigList[fillcount][5][8] = "NL"
        fillcount += 1

    ####################################Initial Assignments Module###################################
    ####################################Initial Checkboxes Module####################################
    NPStressList = list(set(NPStressList))
    NPStressNames = []
    stresscount = 0
    while stresscount < len(NPStressList):
        if NPStressList[stresscount] in StressTranslator:
            NPStressNames.append(StressTranslator[NPStressList[stresscount]])
        stresscount += 1
    UniqueTMDLS = list(set(NPWSNameList))
    if "No TMDL" in UniqueTMDLS:
        UniqueTMDLS.remove("No TMDL")
    if len(UniqueTMDLS) > 0:
        if len(UniqueTMDLS) > 1:
            lastTMDL = UniqueTMDLS.pop()
            tmdlString = ",".join(UniqueTMDLS)
            tmdlString = tmdlString + " and " + lastTMDL
        else:
            tmdlString = UniqueTMDLS[0]
    else:
        tmdlString = ""
    stressString = "None"
    if len(NPStressNames) > 0:
        if len(NPStressNames) > 1:
            lastStressor = NPStressNames.pop()
            stressString = ",".join(NPStressNames)
            stressString = stressString + " and " + lastStressor
        else:
            stressString = NPStressNames[0]
    NarrativeStandards = 1
    NarrativeStandardsText = ""
    NumericStandards = 1
    NumericStandardsText = ""
    StandardConditions = 1
    StandardConditionsText = ""
    SpecialConditions = 1
    SpecialConditionsText = ""
    MixingZoneConditions = 0
    MixingZoneConditionsText = ""
    TechnologyLimits = 1
    TechnologyLimitsText = ""
    SMCRAStandard = 1
    SMCRAStandardText = ""
    TMDLWatershed = 0
    TMDLWatershedText = ""
    ReminingConditions = 0
    ReminingConditionsText = "Not Requested."
    InterstateEffect = 0
    InterstateEffectText = ""
    RainfallExclusion = False
    RainfallExclusionText = ""
    TSSBenthicImpairment = False
    TSSBenthicImpairmentText = ""
    ComplianceRequirement = False
    ComplianceRequirementText = "No Schedule of Compliance is required."
    TSSOffset = False
    TSSOffsetText = ""
    SSPMRequirement = False
    SSPMRequirementText = ""
    # PermitVariances = False
    # PermitVariancesText = ""
    PCBMonitoringPlanNecessary = False
    AltEffLimitsNarrative = "None requested."
    OutfallDischargeLocations = ""
    for each in NPRepWET:
        if str(each) != "No":
            NarrativeStandards = 1
            break;
    for each in NPRepChem:
        if str(each) != "No":
            TechnologyLimits = 1
            break;
    for each in NPDrainCatList:
        if str(each) == "5":
            TechnologyLimits = 1
            break;
    for each in NPBigList:
        if str(each[2][7]) != "NA":
            NumericStandards = 1
            break;
    for each in NPWSNameList:
        if each != "No TMDL":
            TMDLWatershed = 1
    if NarrativeStandards == 0:
        NarrWQCheckbox = False
        NarrativeStandardsText = "9VAC25-260-20\nDischarges from this operation must not cause the violation of any applicable narrative instream water quality standards."
    else:
        NarrWQCheckbox = True
        NarrativeStandardsText = "9VAC25-260-20\nDischarges from this operation must not cause the violation of any applicable narrative instream water quality standards."
    if NumericStandards == 0:
        NumWQCheckbox = False
        NumericStandardsText = "9VAC25-260-140"
    else:
        NumWQCheckbox = True
        NumericStandardsText = "9VAC25-260-140\nDischarges from this operation must not cause the violation of any applicable numeric instream water quality\
standards."
    if StandardConditions == 0:
        StandardCheckbox = False
        StandardConditionsText = "40 CFR 122.41 and 9VAC25-31-190"
    else:
        StandardCheckbox = True
        StandardConditionsText = "40 CFR 122.41 and 9VAC25-31-190\nThe outfalls, discharges, and related activities associated with the proposed operation must\
individually and in aggregate remain in compliance with the requirements stated in sections 318, 402, and 405 of the Clean Water Act.\
Additionally, the permittee must comply with all conditions attached to the permit, including but not limited to the effluent standards established\
under 307(a) of the Clean Water Act. The permittee is bound to all duties, procedures, and requirements laid out in both Federal Regulation\
40 CFR 122.41 and State Regulation 9VAC25-260."
    if SpecialConditions == 0:
        SMCRASpecialCheckbox = False
        SpecialConditionsText = "4VAC25-130-773-17"
    else:
        SMCRASpecialCheckbox = True
        SpecialConditionsText = "4VAC25-130-773-17"
    if MixingZoneConditions == 0:
        ReceivingFlowCheckbox = False
        MixingZoneConditionsText = "9VAC260-20"
    else:
        ReceivingFlowCheckbox = True
        MixingZoneConditionsText = "9VAC260-20"
    if TechnologyLimits == 0:
        TechLimitsCheckbox = False
        TechnologyLimitsText = "40 CFR 434"
    else:
        TechLimitsCheckbox = True
        TechnologyLimitsText = "40 CFR 434"
    if SMCRAStandard == 0:
        SMCRAStandardCheckbox = False
        SMCRAStandardText = "4VAC25-130-816.42 and/or 4VAC25-130-817.42"
    else:
        SMCRAStandardCheckbox = True
        SMCRAStandardText = "4VAC25-130-816.42 and/or 4VAC25-130-817.42"
    if TMDLWatershed == 0 or stressString == "None":
        TMDLCheckbox = False
        TMDLWatershedText = "40 CFR 130 and CWA 303(d)\nThe application does not include any outfalls or discharges within established TMDL Watershed Areas. Therefore,\
no special TMDL permit conditions will be imposed."
    else:
        TMDLCheckbox = True
        TMDLWatershedText = "40 CFR 130 and CWA 303(d)\nThe application includes outfalls and/or discharges falling within established boundaries of the TMDL\
Watershed(s) " + tmdlString + " due to established stressor(s) " + stressString + ". Therefore, special permit conditions as defined in the regulations\
cited above are applicable to the permit."
    if ReminingConditions == 0:
        ReminingCheckbox = False
        ReminingConditionsText = "4VAC25-130-825"
    else:
        ReminingCheckbox = True
        ReminingConditionsText = "4VAC25-130-825"
    if InterstateEffect == 0:
        InterstateCheckbox = False
        InterstateEffectText = "This permit is not permitted to cross state boundaries or otherwise require Virginia interstate regulations."
    else:
        InterstateCheckbox = True
        InterstateEffectText = "This permit has the possibility to affect areas outside of the jurisdiction of the Commonwealth of Virginia. \
The permit must conform to the standards of all affected jurisdictions."
    ####################################Initial Checkboxes Module####################################
    ####################################Initial Outfall Narratives###################################
    NPDESOutfallDescriptionText = ""
    RepresentativeSamplingText = ""
    EffluentScreeningText = ""
    ####################################Initial Outfall Narratives###################################
    ####################################Discharge Classification Module##############################
    count = 0
    NPDischargeType = []
    while count < len(NPMPIDList):
        if NPMPIDList[count] == "None":  #Here is where we will put the discharge potential module
            NPDischargeType.append("Rarely/Never")
        else:
            if NPStatusList[count] == "NB" or NPStatusList[count] == "NC":
                NPDischargeType.append("Rarely/Never")
            else:
                if FlowRatioList[count] > .1 and FlowRatioList[count] < .5:
                    NPDischargeType.append("Intermittent")
                elif FlowRatioList[count] < .1:
                    NPDischargeType.append("Rarely/Never")
                else:
                    NPDischargeType.append("Continuous")
        count += 1
        ##################################
    WQLimit = "No"
    RainfallExclusion = False
    RainfallExclusionText = ""
    xcount = 0
    while xcount < len(NPMPIDList):
        if str(NPBigList[xcount][5][3]) != "NA":
            if float(NPBigList[xcount][5][3]) > float(420):
                WETViolation = "Yes"
                break
        xcount += 1
    if len(UniqueTMDLS) > 0:
        WQLimit = "Yes"
    xcount = 0
    while xcount < len(NPMPIDList):
        if NPBigList[xcount][6][15] != "NA" and NPBigList[xcount][7][15] != "NA":
            RainfallExclusion = True
            RainfallExclusionText = "A Rainfall exclusion for qualifying rainfall events greater than or equal\
to " + str(NPBigList[xcount][6][15]) + ", alternate effluent limits are applicable to the permit."
            if NPBigList[xcount][4][15] == "NA":
                TSSBenthicImpairment = True
                TSSBenthicImpairmentText = "Because the permit identifies TSS as a stressor of concern, permit specified limits still apply\
even during qualifying rainfall events."
        xcount += 1
    WETViolation = "No"
    mpNarrWQCheckbox.append(NarrWQCheckbox)
    mpNumWQCheckbox.append(NumWQCheckbox)
    mpStandardCheckbox.append(StandardCheckbox)
    mpSMCRASpecialCheckbox.append(SMCRASpecialCheckbox)
    mpReceivingFlowCheckbox.append(ReceivingFlowCheckbox)
    mpTechLimitsCheckbox.append(TechLimitsCheckbox)
    mpSMCRAStandardCheckbox.append(SMCRAStandardCheckbox)
    mpTMDLCheckbox.append(TMDLCheckbox)
    mpReminingCheckbox.append(ReminingCheckbox)
    mpInterstateCheckbox.append(InterstateCheckbox)
    mpWETViolation.append(WETViolation)
    mpWQLimit.append(WQLimit)
    mpUniqueTMDLS.append(UniqueTMDLS)
    mpNPDischargeType.append(NPDischargeType)
    mpNPMPIDOutfallCheckList.append(NPFacLocList)
    mpOutfallDischargeLocations.append(OutfallDischargeLocations)
    mpNPWSList.append(NPWSList)
    mpNPWSNameList.append(NPWSNameList)
    mpNPWSFlowList.append(NPWSFlowList)
    mpNPTierDesList.append(NPTierDesList)
    mpNPDistList.append(NPDistList)
    mpNPCauseName.append(NPCauseName)
    mpNPImpairList.append(NPImpairList)
    mpNPUseDescList.append(NPUseDescList)
    mpNPChangeList.append(NPChangeList)
    mpNPRepWET.append(NPRepWET)
    mpNPBigList.append(NPBigList)
    mpFlowRatioList.append(FlowRatioList)
    mpStressorList.append(StressorList)
    mpNPStressNames.append(NPStressNames)
    mpstressString.append(stressString)
    mptmdlString.append(tmdlString)
    mpAltEffLimitsNarrative.append(AltEffLimitsNarrative)
    mpPCBMonitoringPlanNecessary.append(PCBMonitoringPlanNecessary)
    mpNarrativeStandards.append(NarrativeStandards)
    mpNarrativeStandardsText.append(NarrativeStandardsText)
    mpNumericStandards.append(NumericStandards)
    mpNumericStandardsText.append(NumericStandardsText)
    mpStandardConditions.append(StandardConditions)
    mpStandardConditionsText.append(StandardConditionsText)
    mpSpecialConditions.append(SpecialConditions)
    mpSpecialConditionsText.append(SpecialConditionsText)
    mpMixingZoneConditions.append(MixingZoneConditions)
    mpMixingZoneConditionsText.append(MixingZoneConditionsText)
    mpTechnologyLimits.append(TechnologyLimits)
    mpTechnologyLimitsText.append(TechnologyLimitsText)
    mpSMCRAStandard.append(SMCRAStandard)
    mpSMCRAStandardText.append(SMCRAStandardText)
    mpTMDLWatershed.append(TMDLWatershed)
    mpTMDLWatershedText.append(TMDLWatershedText)
    mpReminingConditions.append(ReminingConditions)
    mpReminingConditionsText.append(ReminingConditionsText)
    mpInterstateEffect.append(InterstateEffect)
    mpInterstateEffectText.append(InterstateEffectText)
    mpRainfallExclusion.append(RainfallExclusion)
    mpRainfallExclusionText.append(RainfallExclusionText)
    mpTSSBenthicImpairment.append(TSSBenthicImpairment)
    mpTSSBenthicImpairmentText.append(TSSBenthicImpairmentText)
    mpComplianceRequirement.append(ComplianceRequirement)
    mpComplianceRequirementText.append(ComplianceRequirementText)
    mpTSSOffset.append(TSSOffset)
    mpTSSOffsetText.append(TSSOffsetText)
    mpSSPMRequirement.append(SSPMRequirement)
    mpSSPMRequirementText.append(SSPMRequirementText)
    # mpPermitVariances.append(PermitVariances)
    # mpPermitVariancesText.append(PermitVariancesText)
    mpNPDESOutfallDescriptionText.append(NPDESOutfallDescriptionText)
    mpRepresentativeSamplingText.append(RepresentativeSamplingText)
    mpEffluentScreeningText.append(EffluentScreeningText)
    mpNPParamPlotList.append(NPParamPlotList)
    mpNPParamLoadPlotList.append(NPParamLoadPlotList)
    WriteFileString('Finished NPDES Data Thread')


def InstreamDataThread(parent, AppNumber, RevisionNumber, ISMPIDList, ISActionList, ISChangeList, ISLocNoList,
                       ISTblSrNameList, ISTblSrCodeList,
                       ISEastingList, ISNorthingList, ISWSList, ISWSNameList, ISNameList, ISTierDesList, ISDistList,
                       ISImpairList, ISUseDescList,
                       ISCauseName, ISWaterTransDict, WaterFieldList, ISStressList, ISBigList, ISAcidList, ISType,
                       mpBiologicalMonitoring,
                       mpBiologicalMonitoringText, mpFlowTypePCChoose, mpISWSList, mpISStressList, mpISStressorList,
                       mpISWSNameList, mpISTierDesList,
                       mpISDistList, mpISCauseName, mpISImpairList, mpISUseDescList, mpISAcidList, mpISChangeList,
                       mpISBigList, mpISDischargeType,
                       mpISFlowRatioList, TMDLGeometries, TMDLWSCodeField, TMDLWSNameField, TMDLWSOBIDField,
                       mpISParamPlotList, mpISParamLoadPlotList,
                       ISParamPlotList, ISParamLoadPlotList):
    WriteFileString('Starting Instream Data Thread')
    try:
        conn = odbc.odbc(DMMESDEConnection)
        conn2 = odbc.odbc(Dmlr_DB)
        conn3 = odbc.odbc(WaterQuality)
        wqConn = odbc.odbc(WaterQuality)
    except:
        conn = odbc.odbc(DMMESDEConnection)
        conn2 = odbc.odbc(Dmlr_DB)
        conn3 = odbc.odbc(WaterQuality)
        wqConn = odbc.odbc(WaterQuality)
    dxcursor = conn3.cursor()  #cursor for dxk_test database
    cursor2 = conn2.cursor()  #cursor for dmlr database
    cursor = conn.cursor()  #cursor for EP database
    wqCursor = wqConn.cursor()
    i = 0
    while i < len(ISMPIDList):
        if str(ISActionList[i]) == "A":
            ISChangeList[i] = "This instream monitoring location " + ISLocNoList[
                i] + " has been added to the permit through application " + str(AppNumber) + "."
        elif str(ISActionList[i]) == "D":
            ISChangeList[i] = "This instream monitoring location has been deleted from this permit."
        elif str(ISActionList[i]) == "C" and str(ISMPIDList[i]) != "None" and str(ISMPIDList[i]) != "":
            ISChangeList[i] = ""
            sqlSearch = str(
                "select TblMsCode,MpCompId,MpFacilLoc,TblSrCode,TblQuCode,MpFrqQtr,MpEasting,MpNorthing from DmlrMpids where MpNo = '" + str(
                    ISMPIDList[i]) + "'")
            cursor2.execute(sqlSearch)
            result = cursor2.fetchone()
            sqlSearch = str(
                "select Status,LocNo,FacLoc,TblSrCode,TblQuCode,Frequency,Easting,Northing from Hydro_SWMP where AppNo = '" + str(
                    AppNumber) + "' and RevNo = '" + str(RevisionNumber) + "' and MPIDNo = '" + str(
                    ISMPIDList[i]) + "'")
            cursor.execute(sqlSearch)
            result2 = cursor.fetchone()
            tempMsCode2 = str(result2[0])
            tempLocNo2 = str(result2[1])
            tempFacLoc2 = str(result2[2])
            tempSrCode2 = str(result2[3])
            tempQuCode2 = str(result2[4])
            tempFreq2 = str(result2[5])
            tempEasting2 = str(result2[6])
            tempNorthing2 = str(result2[7])
            tempMsCode = str(result[0])
            tempLocNo = str(result[1])
            tempFacLoc = str(result[2])
            tempSrCode = str(result[3])
            tempQuCode = str(result[4])
            tempFreq = str(result[5])
            tempEasting = str(result[6])
            tempNorthing = str(result[7])
            if tempLocNo != str(ISLocNoList[i]):
                if tempLocNo == "None":
                    ISChangeList[i] += str(
                        "The name of this instream point has been added as " + str(ISLocNoList[i]) + ". ")
                else:
                    ISChangeList[i] += str(
                        "The name of this instream point has been changed from " + tempLocNo + " to " + str(
                            ISLocNoList[i]) + ". ")
            else:
                if tempLocNo2 != str(ISLocNoList[i]):
                    if tempLocNo2 == "None":
                        ISChangeList[i] += str(
                            "The name of this instream point has been added as " + str(ISLocNoList[i]) + ". ")
                    else:
                        ISChangeList[i] += str(
                            "The name of this instream point has been changed from " + tempLocNo2 + " to " + str(
                                ISLocNoList[i]) + ". ")
            if tempSrCode != str(ISTblSrCodeList[i]):
                sqlSearch1 = str("select TblSrName from StreamTbl where TblSrCode = " + str(tempSrCode))
                cursor.execute(sqlSearch1)
                res = cursor.fetchone()
                tempSrName = str(res[0]).title()
                if tempSrName == "None":
                    ISChangeList[i] += str("The stream which the instream point discharges to has been added as " + str(
                        ISTblSrNameList[i]) + ". ")
                else:
                    ISChangeList[i] += str(
                        "The stream which the instream point discharges to has been changed from " + tempSrName + " to " + str(
                            ISTblSrNameList[i]) + ". ")
            else:
                if tempSrCode2 != str(ISTblSrCodeList[i]):
                    sqlSearch1 = str("select TblSrName from StreamTbl where TblSrCode = " + str(tempSrCode2))
                    cursor.execute(sqlSearch1)
                    res = cursor.fetchone()
                    tempSrName = str(res[0]).title()
                    if tempSrName == "None":
                        ISChangeList[i] += str(
                            "The stream which the instream point discharges to has been added as " + str(
                                ISTblSrNameList[i]) + ". ")
                    else:
                        ISChangeList[i] += str(
                            "The stream which the instream point discharges to has been changed from " + tempSrName + " to " + str(
                                ISTblSrNameList[i]) + ". ")
            if tempEasting != str(ISEastingList[i]):
                if tempEasting == "None":
                    ISChangeList[i] += str(
                        "The easting coordinate of the instream point (VASP) has been added as " + str(
                            ISEastingList[i]) + ". ")
                else:
                    ISChangeList[i] += str(
                        "The easting coordinate of the instream point (VASP) has been changed from " + tempEasting + " to " + str(
                            ISEastingList[i]) + ". ")
            else:
                if tempEasting2 != str(ISEastingList[i]):
                    if tempEasting2 == "None":
                        ISChangeList[i] += str(
                            "The easting coordinate of the instream point (VASP) has been added as " + str(
                                ISEastingList[i]) + ". ")
                    else:
                        ISChangeList[i] += str(
                            "The easting coordinate of the instream point (VASP) has been changed from " + tempEasting2 + " to " + str(
                                ISEastingList[i]) + ". ")
            if tempNorthing != str(ISNorthingList[i]):
                if tempNorthing == "None":
                    ISChangeList[i] += str(
                        "The northing coordinate of the instream point (VASP) has been added as " + str(
                            ISNorthingList[i]) + ". ")
                else:
                    ISChangeList[i] += str(
                        "The northing coordinate of the instream point (VASP) has been changed from " + tempNorthing + " to " + str(
                            ISNorthingList[i]) + ". ")
            else:
                if tempNorthing2 != str(ISNorthingList[i]):
                    if tempNorthing2 == "None":
                        ISChangeList[i] += str(
                            "The northing coordinate of the instream point (VASP) has been added as " + str(
                                ISNorthingList[i]) + ". ")
                    else:
                        ISChangeList[i] += str(
                            "The northing coordinate of the instream point (VASP) has been changed from " + tempNorthing2 + " to " + str(
                                ISNorthingList[i]) + ". ")
        i += 1
    #####################################TMDL SELECTION MODULE#######################################
    counter = 0
    while counter < len(ISMPIDList):
        if ISEastingList[counter] == "None" or ISNorthingList[counter] == "None":
            ISWSList[counter] = "None"
            ISWSNameList[counter] = "No TMDL"
        else:
            point = ogr.Geometry(ogr.wkbPoint)
            point.AddPoint(float(ISEastingList[counter]), float(ISNorthingList[counter]))
            for wtsd in TMDLGeometries:
                w = ogr.CreateGeometryFromWkt(wtsd)
                if w.Contains(point):
                    ISWSList[counter] = str(TMDLWSCodeField[TMDLGeometries.index(wtsd)])
                    ISWSNameList[counter] = str(TMDLWSNameField[TMDLGeometries.index(wtsd)])
        counter += 1
    #####################################TMDL SELECTION MODULE#######################################
    #####################################TIER SELECTION MODULE#######################################
    i = 0
    while i < len(ISNameList):
        try:
            sqlSearch = str(
                "select WATER_STATUS,USE_DESCRIPTION,CAUSE_NAME from Sr303d where SrCode =" + str(ISTblSrCodeList[i]))
            dxcursor.execute(sqlSearch)
            result = dxcursor.fetchone()
            if str(result) != "None":
                ISTierDesList[i] = "Tier I"
                ISDistList[i] = "303d"
                ISImpairList[i] = str(result[0])
                ISUseDescList[i] = str(result[1])
                ISCauseName[i] = str(result[2])
            else:
                sqlSearch = str("select WATER_STATUS,USE_DESCRIPTION,CAUSE_NAME from Sr305b where SrCode=" + str(
                    ISTblSrCodeList[i]))
                result = dxcursor.fetchone()
                if str(result) != "None":
                    ISTierDesList[i] = "Tier I"
                    ISDistList[i] = "305b"
                    ISImpairList[i] = str(result[0])
                    ISUseDescList[i] = str(result[1])
                    ISCauseName[i] = str(result[2])
                else:
                    if ISWSNameList[i] != "No TMDL":
                        ISTierDesList[i] = "Tier I"
                        ISDistList[i] = "TMDL"
                        ISCauseName[i] = "In " + str(ISWSNameList[i]) + " TMDL"
        except:
            pass
        i += 1
    #####################################TIER SELECTION MODULE#######################################
    #####################################Initial Assignments Module###################################
    ISFlowRatioList = []
    ISStressorList = []
    ISShortDict = {}
    searchString = ""
    paramIndex = []
    for each in ISWaterTransDict:
        if ISWaterTransDict[each] in WaterFieldList:
            paramIndex.append(ISWaterTransDict[each])
            ISShortDict[each] = each
            searchString += ISWaterTransDict[each]
            searchString += ","
    WriteFileString('Compiling Instream Parameter Data')
    i = 0
    while i < len(ISMPIDList):
        if ISWSList[i] != "None" and ISWSList[i] != "":
            sqlSearch = "select TblLdCode,TWsAvgFlow,TWsParamForEst,TWsWLA,TWsWaterTransDefault from DmlrTMDLWaterShed_Stressor where TWsCode = " + str(
                ISWSList[i])
            cursor2.execute(sqlSearch)
            result = cursor2.fetchall()
            numStressors = len(result)
            smallstressstring = ""
            j = 0
            while j < numStressors:
                if numStressors - j != 1:
                    smallstressstring += str(result[j][0])
                    smallstressstring += ", "
                else:
                    smallstressstring += str(result[j][0])
                ISStressList.append(result[j][0].upper())
                j += 1
            ISStressorList.append(smallstressstring)
        else:
            ISStressorList.append("None")
        if ISMPIDList[i] != "None":
            sqlSearch = str("select WtFlow,WtDate from DmlrWaterTrans where MpNo = '" + str(ISMPIDList[i]) + "'")
            cursor2.execute(sqlSearch)
            result = cursor2.fetchall()
            flow = []
            DateList = []
            flowcounter = 0
            for record in result:
                if type(record[0]) is not types.NoneType and str(record[0]) != "" and str(record[0]) != "None" and str(
                        record[0]) != "Null":
                    flow.append(float(record[0]))
                    DateList.append(record[1])
                    if float(record[0]) != 0:
                        flowcounter += 1
            if len(flow) > 0:
                flowavg = sum(flow) / len(flow)
                ISFlowRatioList.append(float((float(flowcounter) / float(len(flow)))))
            else:
                flowavg = 0
                ISFlowRatioList.append(float(0))
            sqlSearch = str(
                "select " + searchString + "WtDate from DmlrWaterTrans where MpNo = '" + str(ISMPIDList[i]) + "'")
            cursor2.execute(sqlSearch)
            result = cursor2.fetchall()
            for entry in ISShortDict:
                resultCount = 0
                ResultList = []
                DateList = []
                LoadResultList = []
                plotList = []
                plotLoadList = []
                while resultCount < len(result):
                    if type(result[resultCount][
                        int(paramIndex.index(ISWaterTransDict[entry]))]) is not types.NoneType and str(
                            result[resultCount][int(paramIndex.index(ISWaterTransDict[entry]))]) != "" and str(
                            result[resultCount][
                                int(paramIndex.index(ISWaterTransDict[entry]))]).upper() != "NONE" and str(
                            result[resultCount][int(paramIndex.index(ISWaterTransDict[entry]))]).upper() != "NULL":
                        ResultList.append(float(result[resultCount][int(paramIndex.index(ISWaterTransDict[entry]))]))
                        plotList.append([float(result[resultCount][int(paramIndex.index(ISWaterTransDict[entry]))]),
                                         str(result[resultCount][len(ISShortDict)])])
                        if type(result[resultCount][int(paramIndex.index('WtFlow'))]) is not types.NoneType and str(
                                result[resultCount][int(paramIndex.index('WtFlow'))]) != "" and str(
                                result[resultCount][int(paramIndex.index('WtFlow'))]).upper() != "NONE" and str(
                                result[resultCount][int(paramIndex.index('WtFlow'))]).upper() != "NULL":
                            LoadResultList.append(
                                (float(result[resultCount][int(paramIndex.index(ISWaterTransDict[entry]))])) * (
                                float(result[resultCount][int(paramIndex.index('WtFlow'))])))
                            plotLoadList.append([
                                (float(result[resultCount][int(paramIndex.index(ISWaterTransDict[entry]))])) * (
                                float(result[resultCount][int(paramIndex.index('WtFlow'))])),
                                str(result[resultCount][len(ISShortDict)])])
                    resultCount += 1
                if len(ResultList) > 0:
                    ISParamPlotList[i][int(entry)] = plotList
                    meanResult = sum(ResultList) / len(ResultList)
                    ISBigList[i][int(entry)][5] = str(len(ResultList))
                    ISBigList[i][int(entry)][4] = str(np.std(ResultList))
                    ISBigList[i][int(entry)][3] = str(meanResult)
                    ISBigList[i][int(entry)][6] = str(min(ResultList))
                    ISBigList[i][int(entry)][7] = str(max(ResultList))
                    if len(LoadResultList) > 0:
                        if ISBigList[i][int(entry)][0] == "mg/L":
                            for l in range(0, len(plotLoadList)):
                                plotLoadList[l][0] = plotLoadList[l][0] * .005451
                        elif ISBigList[i][int(entry)][0] == "ug/L":
                            for l in range(0, len(plotLoadList)):
                                plotLoadList[l][0] = plotLoadList[l][0] * .000005451
                        ISParamLoadPlotList[i][int(entry)] = plotLoadList
                        meanLoadResult = sum(LoadResultList) / len(LoadResultList)
                        if ISBigList[i][int(entry)][0] == "mg/L":
                            ISBigList[i][int(entry)][14] = str(meanLoadResult * .16591)
                        elif ISBigList[i][int(entry)][0] == "ug/L":
                            ISBigList[i][int(entry)][14] = str(meanLoadResult * .001659)
                    if int(entry) == 1:
                        if float(meanResult) > float(9.0):
                            ISAcidList[i] = "Alkaline"
                        elif float(meanResult) >= float(6.0) and float(meanResult) <= 9.0:
                            ISAcidList[i] = "Neutral"
                        elif float(meanResult) < float(6.0):
                            ISAcidList[i] = "Acidic"
        else:
            ISFlowRatioList.append(float(0))
        i += 1
    i = 0
    FlowTypePCChoose = 0
    ##    while i < len(ISMPIDList):
    ##        paramCounter = 0
    ##        if ISBigList[i][0][5] != "NA":
    ##            if int(ISBigList[i][0][5]) > 10:
    ##                j = 1
    ##                while j < 11:
    ##                    if str(ISBigList[i][j][5]) == "NA" or int(ISBigList[i][j][5]) < 10:
    ##                        paramCounter += 1
    ##                    j += 1
    ##                if paramCounter > 4:
    ##                    FlowTypePCChoose = 1
    ##                    k=1
    ##                    while k < 11:
    ##                        if k != 2 and k != 0:
    ##                            ISBigList[i][k][11]="No"
    ##                        k+=1
    ##        i+=1
    fillcount = 0
    while fillcount < len(ISBigList):
        innercount = 0
        if ISBigList[fillcount][4][3] != "NA":
            if float(ISBigList[fillcount][4][3]) > float(420):
                ISBigList[fillcount][4][11] = "Yes"
        while innercount < len(ISBigList[fillcount]):
            if ISBigList[fillcount][innercount][5] != "NA":
                if int(ISBigList[fillcount][innercount][5]) > 10:
                    ISBigList[fillcount][innercount][11] = "Yes"
            innercount += 1
        fillcount += 1
        ####################################Initial Assignments Module###################################
    ####################################Flow Classification Module Instream##############################
    count = 0
    ISDischargeType = []
    while count < len(ISMPIDList):
        if ISMPIDList[count] == "None":  #Here is where we will put the discharge potential module
            ISDischargeType.append("Perennial")
        else:
            if ISFlowRatioList[count] >= .2 and ISFlowRatioList[count] < .8:  #Check these signs
                ISDischargeType.append("Intermittent")
            elif ISFlowRatioList[count] < .2:
                ISDischargeType.append("Ephemeral")
            else:
                ISDischargeType.append("Perennial")
        count += 1
    iscount = 0
    BioPointsList = []
    BioPointsStreamList = []
    BiologicalMonitoring = False
    BiologicalMonitoringText = ""
    while iscount < len(ISMPIDList):
        if str(ISType[iscount]).upper() == "BSIS":
            BioPointsList.append(str(ISLocNoList[iscount]))
            BioPointsStreamList.append(str(ISTblSrNameList[iscount]))
        iscount += 1
    if len(BioPointsList) > 0:
        BiologicalMonitoring = True
        BioPointsStreamList = list(set(BioPointsStreamList))
        if len(BioPointsStreamList) > 0:
            BiologicalMonitoringText = ""
    mpBiologicalMonitoring.append(BiologicalMonitoring)
    mpBiologicalMonitoringText.append(BiologicalMonitoringText)
    mpFlowTypePCChoose.append(FlowTypePCChoose)
    mpISWSList.append(ISWSList)
    mpISStressList.append(ISStressList)
    mpISStressorList.append(ISStressorList)
    mpISWSNameList.append(ISWSNameList)
    mpISTierDesList.append(ISTierDesList)
    mpISDistList.append(ISDistList)
    mpISCauseName.append(ISCauseName)
    mpISImpairList.append(ISImpairList)
    mpISUseDescList.append(ISUseDescList)
    mpISAcidList.append(ISAcidList)
    mpISChangeList.append(ISChangeList)
    mpISBigList.append(ISBigList)
    mpISDischargeType.append(ISDischargeType)
    mpISFlowRatioList.append(ISFlowRatioList)
    mpISParamPlotList.append(ISParamPlotList)
    mpISParamLoadPlotList.append(ISParamLoadPlotList)
    WriteFileString('Finished Instream Data Thread')


def GroundwaterDataThread(parent, AppNumber, RevisionNumber, GWMPIDList, GWActionList, GWChangeList, GWLocNoList,
                          GWEastingList, GWNorthingList,
                          GWElevationList, GWWSList, GWWSNameList, GWWaterTransDict, WaterFieldList, GWBigList,
                          GWFreqList, GWAcidList, mpGWAcidList,
                          mpGWWSList, mpGWWSNameList, mpGWChangeList, mpGWBigList, TMDLGeometries, TMDLWSCodeField,
                          TMDLWSNameField, TMDLWSOBIDField,
                          mpGWParamPlotList, mpGWParamLoadPlotList, GWParamPlotList, GWParamLoadPlotList):
    WriteFileString('Starting Groundwater Data Thread')
    try:
        conn = odbc.odbc(DMMESDEConnection)
        conn2 = odbc.odbc(Dmlr_DB)
        conn3 = odbc.odbc(WaterQuality)
        wqConn = odbc.odbc(WaterQuality)
    except:
        conn = odbc.odbc(DMMESDEConnection)
        conn2 = odbc.odbc(Dmlr_DB)
        conn3 = odbc.odbc(WaterQuality)
        wqConn = odbc.odbc(WaterQuality)
    dxcursor = conn3.cursor()  #cursor for dxk_test database
    cursor2 = conn2.cursor()  #cursor for dmlr database
    cursor = conn.cursor()  #cursor for EP database
    wqCursor = wqConn.cursor()
    i = 0
    while i < len(GWMPIDList):
        if str(GWActionList[i]) == "A":
            GWChangeList[i] = "This groundwater monitoring location " + GWLocNoList[
                i] + " has been added to the permit through application " + str(AppNumber) + "."
        if str(GWActionList[i]) == "D":
            GWChangeList[i] = "This groundwater monitoring location has been deleted from this permit."
        elif str(GWActionList[i]) == "C" and str(GWMPIDList[i]) != "None" and str(GWMPIDList[i]) != "":
            GWChangeList[i] = ""
            sqlSearch = str(
                "select TblMsCode,MpCompId,MpFacilLoc,TblQuCode,MpFrqQtr,MpEasting,MpNorthing,MpElevation from DmlrMpids where MpNo = '" + str(
                    GWMPIDList[i]) + "'")
            cursor2.execute(sqlSearch)
            result = cursor2.fetchone()
            sqlSearch = str(
                "select Status,LocNo,FacLoc,TblQuCode,Frequency,Easting,Northing,Elevation from Hydro_GWMP where AppNo = '" + str(
                    AppNumber) + "' and RevNo = '" + str(RevisionNumber) + "' and MPIDNo = '" + str(
                    GWMPIDList[i]) + "'")
            cursor.execute(sqlSearch)
            result2 = cursor.fetchone()
            try:
                tempMsCode2 = str(result2[0])
                tempLocNo2 = str(result2[1])
                tempFacLoc2 = str(result2[2])
                tempQuCode2 = str(result2[3])
                tempFreq2 = str(result2[4])
                tempEasting2 = str(result2[5])
                tempNorthing2 = str(result2[6])
                tempElevation2 = str(result2[7])
                tempMsCode = str(result[0])
                tempLocNo = str(result[1])
                tempFacLoc = str(result[2])
                tempQuCode = str(result[3])
                tempFreq = str(result[4])
                tempEasting = str(result[5])
                tempNorthing = str(result[6])
                tempElevation = str(result[7])
                if tempLocNo != str(GWLocNoList[i]):
                    if tempLocNo == "None":
                        GWChangeList[i] += str(
                            "The name of this groundwater point has been added as " + str(GWLocNoList[i]) + ". ")
                    else:
                        GWChangeList[i] += str(
                            "The name of this groundwater point has been changed from " + tempLocNo + " to " + str(
                                GWLocNoList[i]) + ". ")
                else:
                    if tempLocNo2 != str(GWLocNoList[i]):
                        if tempLocNo2 == "None":
                            GWChangeList[i] += str(
                                "The name of this groundwater point has been added as " + str(GWLocNoList[i]) + ". ")
                        else:
                            GWChangeList[i] += str(
                                "The name of this groundwater point has been changed from " + tempLocNo2 + " to " + str(
                                    GWLocNoList[i]) + ". ")
                if tempEasting != str(GWEastingList[i]):
                    if tempEasting == "None":
                        GWChangeList[i] += str(
                            "The easting coordinate of the groundwater point (VASP) has been added as " + str(
                                GWEastingList[i]) + ". ")
                    else:
                        GWChangeList[i] += str(
                            "The easting coordinate of the groundwater point (VASP) has been changed from " + tempEasting + " to " + str(
                                GWEastingList[i]) + ". ")
                else:
                    if tempEasting2 != str(GWEastingList[i]):
                        if tempEasting2 == "None":
                            GWChangeList[i] += str(
                                "The easting coordinate of the groundwater point (VASP) has been added as " + str(
                                    GWEastingList[i]) + ". ")
                        else:
                            GWChangeList[i] += str(
                                "The easting coordinate of the groundwater point (VASP) has been changed from " + tempEasting2 + " to " + str(
                                    GWEastingList[i]) + ". ")
                if tempNorthing != str(GWNorthingList[i]):
                    if tempNorthing == "None":
                        GWChangeList[i] += str(
                            "The northing coordinate of the groundwater point (VASP) has been added as " + str(
                                GWNorthingList[i]) + ". ")
                    else:
                        GWChangeList[i] += str(
                            "The northing coordinate of the groundwater point (VASP) has been changed from " + tempNorthing + " to " + str(
                                GWNorthingList[i]) + ". ")
                else:
                    if tempNorthing2 != str(GWNorthingList[i]):
                        if tempNorthing2 == "None":
                            GWChangeList[i] += str(
                                "The northing coordinate of the groundwater point (VASP) has been added as " + str(
                                    GWNorthingList[i]) + ". ")
                        else:
                            GWChangeList[i] += str(
                                "The northing coordinate of the groundwater point (VASP) has been changed from " + tempNorthing2 + " to " + str(
                                    GWNorthingList[i]) + ". ")
                if tempElevation != str(GWElevationList[i]):
                    if tempElevation == "None":
                        GWChangeList[i] += str("The elevation of the groundwater point has been added as " + str(
                            GWElevationList[i]) + ". ")
                    else:
                        GWChangeList[i] += str(
                            "The elevation of the groundwater point has changed from " + tempElevation + " to " + str(
                                GWElevationList[i]) + ". ")
                else:
                    if tempElevation2 != str(GWElevationList[i]):
                        if tempElevation2 == "None":
                            GWChangeList[i] += str("The elevation of the groundwater point has been added as " + str(
                                GWElevationList[i]) + ". ")
                        else:
                            GWChangeList[i] += str(
                                "The elevation of the groundwater point has changed from " + tempElevation2 + " to " + str(
                                    GWElevationList[i]) + ". ")
            except:
                pass
        i += 1
        #####################################TMDL SELECTION MODULE#######################################
    counter = 0
    while counter < len(GWMPIDList):
        if GWEastingList[counter] == "None" or GWNorthingList[counter] == "None":
            GWWSList[counter] = "None"
            GWWSNameList[counter] = "No TMDL"
        else:
            point = ogr.Geometry(ogr.wkbPoint)
            point.AddPoint(float(GWEastingList[counter]), float(GWNorthingList[counter]))
            for wtsd in TMDLGeometries:
                w = ogr.CreateGeometryFromWkt(wtsd)
                if w.Contains(point):
                    GWWSList[counter] = str(TMDLWSCodeField[TMDLGeometries.index(wtsd)])
                    GWWSNameList[counter] = str(TMDLWSNameField[TMDLGeometries.index(wtsd)])
        counter += 1
    #####################################TMDL SELECTION MODULE#######################################
    #####################################Initial Assignments Module###################################
    GWFlowRatioList = []
    GWStressorList = []
    GWShortDict = {}
    searchString = ""
    paramIndex = []
    for each in GWWaterTransDict:
        if GWWaterTransDict[each] in WaterFieldList:
            paramIndex.append(GWWaterTransDict[each])
            GWShortDict[each] = each
            searchString += GWWaterTransDict[each]
            searchString += ","
    WriteFileString('Gathering Groundwater Parameter Data')
    i = 0
    while i < len(GWMPIDList):
        if GWMPIDList[i] != "None":
            sqlSearch = str(
                "select " + searchString + "WtDate from DmlrWaterTrans where MpNo = '" + str(GWMPIDList[i] + "'"))
            cursor2.execute(sqlSearch)
            result = cursor2.fetchall()
            for entry in GWShortDict:
                resultCount = 0
                ResultList = []
                DateList = []
                LoadResultList = []
                plotList = []
                plotLoadList = []
                while resultCount < len(result):
                    if type(result[resultCount][
                        int(paramIndex.index(GWWaterTransDict[entry]))]) is not types.NoneType and str(
                            result[resultCount][int(paramIndex.index(GWWaterTransDict[entry]))]).upper() not in ["",
                                                                                                                 "NONE",
                                                                                                                 "NULL"]:
                        ResultList.append(float(result[resultCount][int(paramIndex.index(GWWaterTransDict[entry]))]))
                        plotList.append([float(result[resultCount][int(paramIndex.index(GWWaterTransDict[entry]))]),
                                         str(result[resultCount][len(GWShortDict)])])
                        if type(result[resultCount][int(paramIndex.index('WtFlow'))]) is not types.NoneType and str(
                                result[resultCount][int(paramIndex.index('WtFlow'))]).upper() not in ["", "NONE",
                                                                                                      "NULL"]:
                            LoadResultList.append(
                                (float(result[resultCount][int(paramIndex.index(GWWaterTransDict[entry]))])) * (
                                float(result[resultCount][int(paramIndex.index('WtFlow'))])))
                            plotLoadList.append([
                                (float(result[resultCount][int(paramIndex.index(GWWaterTransDict[entry]))])) * (
                                float(result[resultCount][int(paramIndex.index('WtFlow'))])),
                                str(result[resultCount][len(GWShortDict)])])
                    resultCount += 1
                if len(ResultList) > 0:
                    GWParamPlotList[i][int(entry)] = plotList
                    meanResult = sum(ResultList) / len(ResultList)
                    GWBigList[i][int(entry)][5] = str(len(ResultList))
                    GWBigList[i][int(entry)][4] = str(np.std(ResultList))
                    GWBigList[i][int(entry)][3] = str(meanResult)
                    GWBigList[i][int(entry)][6] = str(min(ResultList))
                    GWBigList[i][int(entry)][7] = str(max(ResultList))
                    if len(LoadResultList) > 0:
                        if GWBigList[i][int(entry)][0] in ["mg/L", "mL/L"]:
                            for l in range(0, len(plotLoadList)):
                                plotLoadList[l][0] = plotLoadList[l][0] * .005451
                        elif GWBigList[i][int(entry)][0] == "ug/L":
                            for l in range(0, len(plotLoadList)):
                                plotLoadList[l][0] = plotLoadList[l][0] * .000005451
                        GWParamLoadPlotList[i][int(entry)] = plotLoadList
                        meanLoadResult = sum(LoadResultList) / len(LoadResultList)
                        if GWBigList[i][int(entry)][0] == "mg/L":
                            GWBigList[i][int(entry)][14] = str(meanLoadResult * .16591)
                        elif GWBigList[i][int(entry)][0] == "ug/L":
                            GWBigList[i][int(entry)][14] = str(meanLoadResult * .001659)
                    if int(entry) == 1:
                        if float(meanResult) > float(9.0):
                            GWAcidList[i] = "Alkaline"
                        elif float(meanResult) >= float(6.0) and float(meanResult) <= 9.0:
                            GWAcidList[i] = "Neutral"
                        elif float(meanResult) < float(6.0):
                            GWAcidList[i] = "Acidic"
        i += 1
    i = 0
    while i < len(GWFreqList):
        if str(GWFreqList[i]) == '1':
            j = 0
            while j < len(GWBigList[i]):
                if j < 5 or (j > 5 and j < 14):
                    GWBigList[i][j][8] = '1'
                    GWBigList[i][j][9] = 'Quarter'
                    GWBigList[i][j][11] = 'Yes'
                else:
                    GWBigList[i][j][8] = '1'
                    GWBigList[i][j][9] = 'Quarter'
                    GWBigList[i][j][11] = 'No'
                j += 1
        elif str(GWFreqList[i]) == '6':
            j = 0
            while j < len(GWBigList[i]):
                if j < 4 or j == 13:
                    GWBigList[i][j][8] = '6'
                    GWBigList[i][j][9] = 'Quarter'
                    GWBigList[i][j][11] = 'Yes'
                elif j > 3 and j != 5 and j < 13:
                    GWBigList[i][j][8] = '1'
                    GWBigList[i][j][9] = 'Quarter'
                    GWBigList[i][j][11] = 'Yes'
                j += 1
        i += 1
    mpGWAcidList.append(GWAcidList)
    mpGWWSList.append(GWWSList)
    mpGWWSNameList.append(GWWSNameList)
    mpGWChangeList.append(GWChangeList)
    mpGWBigList.append(GWBigList)
    mpGWParamPlotList.append(GWParamPlotList)
    mpGWParamLoadPlotList.append(GWParamLoadPlotList)
    WriteFileString('Finished Groundwater Data Thread')


def StreamDataThread(parent, AppNumber, RevisionNumber, StreamDictionary, mpStreamsFlowClass, mpBigStreamList,
                     mpStreamIndexList, mpWaterCompliance):
    WriteFileString('Starting Stream Data Thread')
    try:
        conn = odbc.odbc(DMMESDEConnection)
        conn2 = odbc.odbc(Dmlr_DB)
        conn3 = odbc.odbc(WaterQuality)
        wqConn = odbc.odbc(WaterQuality)
    except:
        conn = odbc.odbc(DMMESDEConnection)
        conn2 = odbc.odbc(Dmlr_DB)
        conn3 = odbc.odbc(WaterQuality)
        wqConn = odbc.odbc(WaterQuality)
    dxcursor = conn3.cursor()  #cursor for dxk_test database
    cursor2 = conn2.cursor()  #cursor for dmlr database
    cursor = conn.cursor()  #cursor for EP database
    wqCursor = wqConn.cursor()
    BigStreamList = []
    StreamIndexList = []
    StreamsFlowClass = []
    StreamIndexDictionary = {}
    WQISVIOLATIONFLAG = 0
    counter = 0
    for each in StreamDictionary:
        StreamIndexList.append(str(each))
        StreamIndexDictionary[str(counter)] = str(each)
        counter += 1
    for each in StreamIndexList:
        StreamParamList = []
        NumMPIDS = 0
        RecordCount = 0
        StreamMPIDS = []
        MPFlow = []
        MPFlowCount = 0
        MPFlowList = ["GPM", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPPh = []
        MPPhCount = 0
        MPPhList = ["Std", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPIron = []
        MPIronCount = 0
        MPIronList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPManganese = []
        MPManganeseCount = 0
        MPManganeseList = ["mg/L", "0.05", "0.05", "NA", "NA", "NA", "NA", "NA"]
        MPTss = []
        MPTssCount = 0
        MPTssList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPSs = []
        MPSsCount = 0
        MPSsList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPPrec = []
        MPPrecCount = 0
        MPPrecList = ["In", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPTemp = []
        MPTempCount = 0
        MPTempList = ["Celsius", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPAcid = []
        MPAcidCount = 0
        MPAcidList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPAlka = []
        MPAlkaCount = 0
        MPAlkaList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPConMic = []
        MPConMicCount = 0
        MPConMicList = ["uS/cm", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPTds = []
        MPTdsCount = 0
        MPTdsList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPSulf = []
        MPSulfCount = 0
        MPSulfList = ["mg/L", "250", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPHard = []
        MPHardCount = 0
        MPHardList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPChlor = []
        MPChlorCount = 0
        MPChlorList = ["mg/L", "860", "230", "NA", "NA", "NA", "NA", "NA"]
        MPAmmonia = []
        MPAmmoniaCount = 0
        MPAmmoniaList = ["mg/L", "NA", "2.0", "NA", "NA", "NA", "NA", "NA"]
        MPNitrite = []
        MPNitriteCount = 0
        MPNitriteList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPNitrate = []
        MPNitrateCount = 0
        MPNitrateList = ["mg/L", "10.0", "10.0", "NA", "NA", "NA", "NA", "NA"]
        MPAl = []
        MPAlCount = 0
        MPAlList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPPb = []
        MPPbCount = 0
        MPPbList = ["ug/L", "120.0", "14.0", "NA", "NA", "NA", "NA", "NA"]
        MPCu = []
        MPCuCount = 0
        MPCuList = ["ug/L", "13.0", "9.0", "NA", "NA", "NA", "NA", "NA"]
        MPNi = []
        MPNiCount = 0
        MPNiList = ["ug/L", "180", "20.0", "NA", "NA", "NA", "NA", "NA"]
        MPAs = []
        MPAsCount = 0
        MPAsList = ["ug/L", "340", "150", "NA", "NA", "NA", "NA", "NA"]
        MPBa = []
        MPBaCount = 0
        MPBaList = ["mg/L", "2.0", "2.0", "NA", "NA", "NA", "NA", "NA"]
        MPCd = []
        MPCdCount = 0
        MPCdList = ["ug/L", "3.9", "1.1", "NA", "NA", "NA", "NA", "NA"]
        MPCr = []
        MPCrCount = 0
        MPCrList = ["ug/L", "586", "85", "NA", "NA", "NA", "NA", "NA"]
        MPHg = []
        MPHgCount = 0
        MPHgList = ["ug/L", "1.4", "0.77", "NA", "NA", "NA", "NA", "NA"]
        MPSe = []
        MPSeCount = 0
        MPSeList = ["ug/L", "20", "5.0", "NA", "NA", "NA", "NA", "NA"]
        MPAg = []
        MPAgCount = 0
        MPAgList = ["ug/L", "3.4", "NA", "NA", "NA", "NA", "NA", "NA"]
        sqlSearch = str(
            "select MPIDNo,Action,Status from Hydro_SWMP where TblSrCode = '" + str(StreamDictionary[each]) + "'")
        cursor.execute(sqlSearch)
        result = cursor.fetchall()
        for r in result:
            if str(r[0]) not in StreamMPIDS and str(r[0]) != "None" and str(r[0]) != "" and str(r[1]) != "A" and str(
                    r[2]) == "A":
                StreamMPIDS.append(str(r[0]))
        for mp in StreamMPIDS:
            NumMPIDS += 1
            sqlSearch = str("select WtFlow,WtPh,WtIron,WtManganese,WtTss,WtSs,WtPrec,WtTemp,WtAcid,WtAlka,WtConMic,WtTds,WtSulf,WtHard,WtChlor,\
WtAmmonia,WtNitrite,WtNitrate,WtAl,WtPb,WtCu,WtNi,WtAs,WtBa,WtCd,WtCr,WtHg,WtSe,WtAg from DmlrWaterTrans where MpNo = " + str(
                mp))
            cursor2.execute(sqlSearch)
            WtResult = cursor2.fetchall()
            for rec in WtResult:
                RecordCount += 1
                if str(rec[0]) != "" and str(rec[0]) != "None" and rec[0] is not None:
                    MPFlow.append(rec[0])
                    MPFlowCount += 1
                if str(rec[1]) != "" and str(rec[1]) != "None" and rec[1] is not None:
                    MPPh.append(rec[1])
                    MPPhCount += 1
                if str(rec[2]) != "" and str(rec[2]) != "None" and rec[2] is not None:
                    MPIron.append(rec[2])
                    MPIronCount += 1
                if str(rec[3]) != "" and str(rec[3]) != "None" and rec[3] is not None:
                    MPManganese.append(rec[3])
                    MPManganeseCount += 1
                if str(rec[4]) != "" and str(rec[4]) != "None" and rec[4] is not None:
                    MPTss.append(rec[4])
                    MPTssCount += 1
                if str(rec[5]) != "" and str(rec[5]) != "None" and rec[5] is not None:
                    MPSs.append(rec[5])
                    MPSsCount += 1
                if str(rec[6]) != "" and str(rec[6]) != "None" and rec[6] is not None:
                    MPPrec.append(rec[6])
                    MPPrecCount += 1
                if str(rec[7]) != "" and str(rec[7]) != "None" and rec[7] is not None:
                    MPTemp.append(rec[7])
                    MPTempCount += 1
                if str(rec[8]) != "" and str(rec[8]) != "None" and rec[8] is not None:
                    MPAcid.append(rec[8])
                    MPAcidCount += 1
                if str(rec[9]) != "" and str(rec[9]) != "None" and rec[9] is not None:
                    MPAlka.append(rec[9])
                    MPAlkaCount += 1
                if str(rec[10]) != "" and str(rec[10]) != "None" and rec[10] is not None:
                    MPConMic.append(rec[10])
                    MPConMicCount += 1
                if str(rec[11]) != "" and str(rec[11]) != "None" and rec[11] is not None:
                    MPTds.append(rec[11])
                    MPTdsCount += 1
                if str(rec[12]) != "" and str(rec[12]) != "None" and rec[12] is not None:
                    MPSulf.append(rec[12])
                    MPSulfCount += 1
                if str(rec[13]) != "" and str(rec[13]) != "None" and rec[13] is not None:
                    MPHard.append(rec[13])
                    MPHardCount += 1
                if str(rec[14]) != "" and str(rec[14]) != "None" and rec[14] is not None:
                    MPChlor.append(rec[14])
                    MPChlorCount += 1
                if str(rec[15]) != "" and str(rec[15]) != "None" and rec[15] is not None:
                    MPAmmonia.append(rec[15])
                    MPAmmoniaCount += 1
                if str(rec[16]) != "" and str(rec[16]) != "None" and rec[16] is not None:
                    MPNitrite.append(rec[16])
                    MPNitriteCount += 1
                if str(rec[17]) != "" and str(rec[17]) != "None" and rec[17] is not None:
                    MPNitrate.append(rec[17])
                    MPNitrateCount += 1
                if str(rec[18]) != "" and str(rec[18]) != "None" and rec[18] is not None:
                    MPAl.append(rec[18])
                    MPAlCount += 1
                if str(rec[19]) != "" and str(rec[19]) != "None" and rec[19] is not None:
                    MPPb.append(rec[19])
                    MPPbCount += 1
                if str(rec[20]) != "" and str(rec[20]) != "None" and rec[20] is not None:
                    MPCu.append(rec[20])
                    MPCuCount += 1
                if str(rec[21]) != "" and str(rec[21]) != "None" and rec[21] is not None:
                    MPNi.append(rec[21])
                    MPNiCount += 1
                if str(rec[22]) != "" and str(rec[22]) != "None" and rec[22] is not None:
                    MPAs.append(rec[22])
                    MPAsCount += 1
                if str(rec[23]) != "" and str(rec[23]) != "None" and rec[23] is not None:
                    MPBa.append(rec[23])
                    MPBaCount += 1
                if str(rec[24]) != "" and str(rec[24]) != "None" and rec[24] is not None:
                    MPCd.append(rec[24])
                    MPCdCount += 1
                if str(rec[25]) != "" and str(rec[25]) != "None" and rec[25] is not None:
                    MPCr.append(rec[25])
                    MPCrCount += 1
                if str(rec[26]) != "" and str(rec[26]) != "None" and rec[26] is not None:
                    MPHg.append(rec[26])
                    MPHgCount += 1
                if str(rec[27]) != "" and str(rec[27]) != "None" and rec[27] is not None:
                    MPSe.append(rec[27])
                    MPSeCount += 1
                if str(rec[28]) != "" and str(rec[28]) != "None" and rec[28] is not None:
                    MPAg.append(rec[28])
                    MPAgCount += 1
        if MPHardCount > 0:
            MPX = float(sum(MPHard) / len(MPHard))
        else:
            MPX = float(100)
        if MPX < float(25):
            MPX = float(25)
        elif MPX > float(400):
            MPX = float(400)
        if MPFlowCount > 0:
            MPFlowList = ["GPM", "NA", "NA", str(sum(MPFlow) / len(MPFlow)), str(np.std(MPFlow)), str(min(MPFlow)),
                          str(max(MPFlow)), str(MPFlowCount)]
        if MPPhCount > 0:
            MPPhList = ["Std", "NA", "NA", str(sum(MPPh) / len(MPPh)), str(np.std(MPPh)), str(min(MPPh)),
                        str(max(MPPh)), str(MPPhCount)]
        if MPIronCount > 0:
            MPIronList = ["mg/L", "NA", "NA", str(sum(MPIron) / len(MPIron)), str(np.std(MPIron)), str(min(MPIron)),
                          str(max(MPIron)), str(MPIronCount)]
        if MPManganeseCount > 0:
            MPManganeseList = ["mg/L", "0.05", "0.05", str(sum(MPManganese) / len(MPManganese)),
                               str(np.std(MPManganese)), str(min(MPManganese)), str(max(MPManganese)),
                               str(MPManganeseCount)]
            if (float(MPManganeseList[3]) > float(MPManganeseList[2]) or float(MPManganeseList[6]) > float(
                    MPManganeseList[1])):
                WQISVIOLATIONFLAG = 1
        if MPTssCount > 0:
            MPTssList = ["mg/L", "NA", "NA", str(sum(MPTss) / len(MPTss)), str(np.std(MPTss)), str(min(MPTss)),
                         str(max(MPTss)), str(MPTssCount)]
        if MPSsCount > 0:
            MPSsList = ["mg/L", "NA", "NA", str(sum(MPSs) / len(MPSs)), str(np.std(MPSs)), str(min(MPSs)),
                        str(max(MPSs)), str(MPSsCount)]
        if MPPrecCount > 0:
            MPPrecList = ["In", "NA", "NA", str(sum(MPPrec) / len(MPPrec)), str(np.std(MPPrec)), str(min(MPPrec)),
                          str(max(MPPrec)), str(MPPrecCount)]
        if MPTempCount > 0:
            MPTempList = ["Celsius", "NA", "NA", str(sum(MPTemp) / len(MPTemp)), str(np.std(MPTemp)), str(min(MPTemp)),
                          str(max(MPTemp)), str(MPTempCount)]
        if MPAcidCount > 0:
            MPAcidList = ["mg/L", "NA", "NA", str(sum(MPAcid) / len(MPAcid)), str(np.std(MPAcid)), str(min(MPAcid)),
                          str(max(MPAcid)), str(MPAcidCount)]
        if MPAlkaCount > 0:
            MPAlkaList = ["mg/L", "NA", "NA", str(sum(MPAlka) / len(MPAlka)), str(np.std(MPAlka)), str(min(MPAlka)),
                          str(max(MPAlka)), str(MPAlkaCount)]
        if MPConMicCount > 0:
            MPConMicList = ["uS/cm", "NA", "NA", str(sum(MPConMic) / len(MPConMic)), str(np.std(MPConMic)),
                            str(min(MPConMic)), str(max(MPConMic)), str(MPConMicCount)]
        if MPTdsCount > 0:
            MPTdsList = ["mg/L", "NA", "NA", str(sum(MPTds) / len(MPTds)), str(np.std(MPTds)), str(min(MPTds)),
                         str(max(MPTds)), str(MPTdsCount)]
        if MPSulfCount > 0:
            MPSulfList = ["mg/L", "250", "NA", str(sum(MPSulf) / len(MPSulf)), str(np.std(MPSulf)), str(min(MPSulf)),
                          str(max(MPSulf)), str(MPSulfCount)]
            if (float(MPSulfList[3]) > float(MPSulfList[1]) or float(MPSulfList[6]) > float(MPSulfList[1])):
                WQISVIOLATIONFLAG = 1
        if MPHardCount > 0:
            MPHardList = ["mg/L", "NA", "NA", str(sum(MPHard) / len(MPHard)), str(np.std(MPHard)), str(min(MPHard)),
                          str(max(MPHard)), str(MPHardCount)]
        if MPChlorCount > 0:
            MPChlorList = ["mg/L", "860", "230", str(sum(MPChlor) / len(MPChlor)), str(np.std(MPChlor)),
                           str(min(MPChlor)), str(max(MPChlor)), str(MPChlorCount)]
            if (float(MPChlorList[3]) > float(MPChlorList[2]) or float(MPChlorList[6]) > float(MPChlorList[1])):
                WQISVIOLATIONFLAG = 1
        if MPAmmoniaCount > 0:
            MPAmmoniaList = ["mg/L", "NA", "2.0", str(sum(MPAmmonia) / len(MPAmmonia)), str(np.std(MPAmmonia)),
                             str(min(MPAmmonia)), str(max(MPAmmonia)), str(MPAmmoniaCount)]
            if (float(MPAmmoniaList[3]) > float(MPAmmoniaList[2])):
                WQISVIOLATIONFLAG = 1
        if MPNitriteCount > 0:
            MPNitriteList = ["ug/L", "NA", "NA", str(sum(MPNitrite) / len(MPNitrite)), str(np.std(MPNitrite)),
                             str(min(MPNitrite)), str(max(MPNitrite)), str(MPNitriteCount)]
        if MPNitrateCount > 0:
            MPNitrateList = ["mg/L", "10.0", "10.0", str(sum(MPNitrate) / len(MPNitrate)), str(np.std(MPNitrate)),
                             str(min(MPNitrate)), str(max(MPNitrate)), str(MPNitrateCount)]
            if (float(MPNitrateList[3]) > float(MPNitrateList[2]) or float(MPNitrateList[6]) > float(MPNitrateList[1])):
                WQISVIOLATIONFLAG = 1
        if MPAlCount > 0:
            MPAlList = ["mg/L", "NA", "NA", str(sum(MPAl) / len(MPAl)), str(np.std(MPAl)), str(min(MPAl)),
                        str(max(MPAl)), str(MPAlCount)]
        if MPPbCount > 0:
            MPPbList = ["ug/L", str(float(0.33824) * np.power(MPX, float(1.273))),
                        str(float(0.384268) * np.power(MPX, float(1.273))), str(sum(MPPb) / len(MPPb)),
                        str(np.std(MPPb)), str(min(MPPb)), str(max(MPPb)), str(MPPbCount)]
            if (float(MPPbList[3]) > float(MPPbList[2]) or float(MPPbList[6]) > float(MPPbList[1])):
                WQISVIOLATIONFLAG = 1
        if MPCuCount > 0:
            MPCuList = ["ug/L", str(float(0.175376) * np.power(MPX, float(.9422))),
                        str(float(0.175026) * np.power(MPX, float(0.8545))), str(sum(MPCu) / len(MPCu)),
                        str(np.std(MPCu)), str(min(MPCu)), str(max(MPCu)), str(MPCuCount)]
            if (float(MPCuList[3]) > float(MPCuList[2]) or float(MPCuList[6]) > float(MPCuList[1])):
                WQISVIOLATIONFLAG = 1
        if MPNiCount > 0:
            MPNiList = ["ug/L", str(float(3.70617) * np.power(MPX, float(.846))),
                        str(float(2.4133) * np.power(MPX, float(.846))), str(sum(MPNi) / len(MPNi)), str(np.std(MPNi)),
                        str(min(MPNi)), str(max(MPNi)), str(MPNiCount)]
            if (float(MPNiList[3]) > float(MPNiList[2]) or float(MPNiList[6]) > float(MPNiList[1])):
                WQISVIOLATIONFLAG = 1
        if MPAsCount > 0:
            MPAsList = ["ug/L", "340", "150", str(sum(MPAs) / len(MPAs)), str(np.std(MPAs)), str(min(MPAs)),
                        str(max(MPAs)), str(MPAsCount)]
            if (float(MPAsList[3]) > float(MPAsList[2]) or float(MPAsList[6]) > float(MPAsList[1])):
                WQISVIOLATIONFLAG = 1
        if MPBaCount > 0:
            MPBaList = ["mg/L", "2.0", "2.0", str(sum(MPBa) / len(MPBa)), str(np.std(MPBa)), str(min(MPBa)),
                        str(max(MPBa)), str(MPBaCount)]
            if (float(MPBaList[3]) > float(MPBaList[2]) or float(MPBaList[6]) > float(MPBaList[1])):
                WQISVIOLATIONFLAG = 1
        if MPCdCount > 0:
            MPCdList = ["ug/L", str(float(0.0217531) * np.power(MPX, float(1.218))),
                        str(float(0.0305009) * np.power(MPX, float(.7852))), str(sum(MPCd) / len(MPCd)),
                        str(np.std(MPCd)), str(min(MPCd)), str(max(MPCd)), str(MPCdCount)]
            if (float(MPCdList[3]) > float(MPCdList[2]) or float(MPCdList[6]) > float(MPCdList[1])):
                WQISVIOLATIONFLAG = 1
        if MPCrCount > 0:
            MPCrList = ["ug/L", str(float(13.1128) * np.power(MPX, float(.819)) + float(16)),
                        str(float(1.7057) * np.power(MPX, float(.819)) + float(11)), str(sum(MPCr) / len(MPCr)),
                        str(np.std(MPCr)), str(min(MPCr)), str(max(MPCr)), str(MPCrCount)]
            if (float(MPCrList[3]) > float(MPCrList[2]) or float(MPCrList[6]) > float(MPCrList[1])):
                WQISVIOLATIONFLAG = 1
        if MPHgCount > 0:
            MPHgList = ["ug/L", "1.4", "0.77", str(sum(MPHg) / len(MPHg)), str(np.std(MPHg)), str(min(MPHg)),
                        str(max(MPHg)), str(MPHgCount)]
            if (float(MPHgList[3]) > float(MPHgList[2]) or float(MPHgList[6]) > float(MPHgList[1])):
                WQISVIOLATIONFLAG = 1
        if MPSeCount > 0:
            MPSeList = ["ug/L", "20", "5.0", str(sum(MPSe) / len(MPSe)), str(np.std(MPSe)), str(min(MPSe)),
                        str(max(MPSe)), str(MPSeCount)]
            if (float(MPSeList[3]) > float(MPSeList[2]) or float(MPSeList[6]) > float(MPSeList[1])):
                WQISVIOLATIONFLAG = 1
        if MPAgCount > 0:
            MPAgList = ["ug/L", str(float(0.00125262) * np.power(MPX, float(1.72))), "NA", str(sum(MPAg) / len(MPAg)),
                        str(np.std(MPAg)), str(min(MPAg)), str(max(MPAg)), str(MPAgCount)]
            if (float(MPAgList[3]) > float(MPAgList[1]) or float(MPAgList[6]) > float(MPAgList[1])):
                WQISVIOLATIONFLAG = 1
        StreamParamList.append(MPFlowList)
        StreamParamList.append(MPPhList)
        StreamParamList.append(MPIronList)
        StreamParamList.append(MPManganeseList)
        StreamParamList.append(MPTssList)
        StreamParamList.append(MPSsList)
        StreamParamList.append(MPPrecList)
        StreamParamList.append(MPTempList)
        StreamParamList.append(MPAcidList)
        StreamParamList.append(MPAlkaList)
        StreamParamList.append(MPConMicList)
        StreamParamList.append(MPTdsList)
        StreamParamList.append(MPSulfList)
        StreamParamList.append(MPHardList)
        StreamParamList.append(MPChlorList)
        StreamParamList.append(MPAmmoniaList)
        StreamParamList.append(MPNitriteList)
        StreamParamList.append(MPNitrateList)
        StreamParamList.append(MPAlList)
        StreamParamList.append(MPPbList)
        StreamParamList.append(MPCuList)
        StreamParamList.append(MPNiList)
        StreamParamList.append(MPAsList)
        StreamParamList.append(MPBaList)
        StreamParamList.append(MPCdList)
        StreamParamList.append(MPCrList)
        StreamParamList.append(MPHgList)
        StreamParamList.append(MPSeList)
        StreamParamList.append(MPAgList)
        BigStreamList.append(StreamParamList)
        if RecordCount > 0:
            if float(MPFlowCount) / float(RecordCount) < .2:
                StreamsFlowClass.append("Ephemeral")
            elif float(MPFlowCount) / float(RecordCount) >= .2 and float(MPFlowCount) / float(RecordCount) <= .8:
                StreamsFlowClass.append("Intermittent")
            else:
                StreamsFlowClass.append("Perennial")
        else:
            StreamsFlowClass.append("Perennial")
    WaterCompliance = "Yes"
    if WQISVIOLATIONFLAG == 1:
        WaterCompliance = "No"
    ##    parent.StreamsFlowClass = StreamsFlowClass
    ##    parent.BigStreamList = BigStreamList
    ##    parent.StreamIndexList = StreamIndexList
    ##    parent.WaterCompliance=WaterCompliance
    mpStreamsFlowClass.append(StreamsFlowClass)
    mpBigStreamList.append(BigStreamList)
    mpStreamIndexList.append(StreamIndexList)
    mpWaterCompliance.append(WaterCompliance)
    WriteFileString('Finished Stream Data Thread')


def FlowClassDataThread(parent, AppNumber, RevisionNumber, ISWSNameList, UniqueTMDLS, StreamDictionary, NPTblSrNameList,
                        NPMPIDList, NPTierDesList, NPCauseName, StressorList, NPWSNameList, ISMPIDList, ISTblSrNameList,
                        ISTierDesList, ISCauseName, ISStressorList, StreamIndexList, StreamsFlowClass, ISDischargeType):
    WriteFileString('Starting Flow Classification Thread')
    try:
        conn = odbc.odbc(DMMESDEConnection)
        conn2 = odbc.odbc(Dmlr_DB)
        conn3 = odbc.odbc(WaterQuality)
        wqConn = odbc.odbc(WaterQuality)
    except:
        conn = odbc.odbc(DMMESDEConnection)
        conn2 = odbc.odbc(Dmlr_DB)
        conn3 = odbc.odbc(WaterQuality)
        wqConn = odbc.odbc(WaterQuality)
    dxcursor = conn3.cursor()  #cursor for dxk_test database
    cursor2 = conn2.cursor()  #cursor for dmlr database
    cursor = conn.cursor()  #cursor for EP database
    wqCursor = wqConn.cursor()
    WaterTableDictionary = {}
    WaterTableNameDictionary = {}
    BasinCodeDictionary = {}
    BasinNameDictionary = {}
    StreamTierDictionary = {}
    StreamTMDLDictionary = {}
    StressorListDictionary = {}
    InTMDLDictionary = {}
    WatershedNameDictionary = {}
    for each in ISWSNameList:
        UniqueTMDLS.append(each)
    UniqueTMDLS = list(set(UniqueTMDLS))
    if "No TMDL" in UniqueTMDLS:
        UniqueTMDLS.remove("No TMDL")
    for each in StreamDictionary:
        try:
            sqlSearch = str("select TblWtCode from StreamTbl where TblSrCode = '" + str(StreamDictionary[each]) + "'")
            cursor.execute(sqlSearch)
            result = cursor.fetchone()
            WaterTableDictionary[each] = result[0]
            if str(result[0]) != "None":
                sqlSearch = str(
                    "select TblWtName,TblBsCode from WatershedTbl where TblWtCode = '" + str(result[0]) + "'")
                cursor.execute(sqlSearch)
                result = cursor.fetchone()
                WaterTableNameDictionary[each] = str(result[0])
                BasinCodeDictionary[each] = str(result[1])
                sqlSearch = str("select TblBsName from BasinTbl where TblBsCode = '" + str(result[1]) + "'")
                cursor.execute(sqlSearch)
                result = cursor.fetchone()
                BasinNameDictionary[each] = str(result[0])
            else:
                WaterTableNameDictionary[each] = "NA"
                BasinCodeDictionary[each] = "NA"
                BasinNameDictionary[each] = "NA"
        except:
            WaterTableNameDictionary[each] = 'Unknown'
            WaterTableDictionary[each] = 'Unknown'
            BasinCodeDictionary[each] = 'Unknown'
            BasinNameDictionary[each] = 'Unknown'
        if each not in StreamTierDictionary:
            if each in NPTblSrNameList:
                iterator = 0
                while iterator < len(NPMPIDList):
                    if NPTblSrNameList[iterator] == each:
                        StreamTierDictionary[each] = NPTierDesList[iterator]
                        StreamTMDLDictionary[each] = NPCauseName[iterator]
                        StressorListDictionary[each] = StressorList[iterator]
                        WatershedNameDictionary[each] = NPWSNameList[iterator]
                        if NPWSNameList[iterator] == "No TMDL":
                            InTMDLDictionary[each] = "None"
                        else:
                            InTMDLDictionary[each] = str(NPWSNameList[iterator])
                        break;
                    iterator += 1
            else:
                iterator = 0
                while iterator < len(ISMPIDList):
                    if ISTblSrNameList[iterator] == each:
                        StreamTierDictionary[each] = ISTierDesList[iterator]
                        StreamTMDLDictionary[each] = ISCauseName[iterator]
                        StressorListDictionary[each] = ISStressorList[iterator]
                        WatershedNameDictionary[each] = ISWSNameList[iterator]
                        if ISWSNameList[iterator] == "No TMDL":
                            InTMDLDictionary[each] = "None"
                        else:
                            InTMDLDictionary[each] = str(ISWSNameList[iterator])
                        break;
                    iterator += 1
    uniquecounter = 0
    while uniquecounter < len(StreamIndexList):
        innercounter = 0
        while innercounter < len(ISTblSrNameList):
            if str(StreamIndexList[uniquecounter]) == str(ISTblSrNameList[innercounter]):
                ISDischargeType[innercounter] = StreamsFlowClass[uniquecounter]
            innercounter += 1
        uniquecounter += 1
    counter = 0
    dischargenumlist = []
    dischargeDict = {}
    instreamnumlist = []
    while counter < len(StreamIndexList):
        dischargenum = 0
        instreamnum = 0
        for each in NPTblSrNameList:
            if str(each).upper() == str(StreamIndexList[counter]).upper():
                dischargenum += 1
        dischargenumlist.append(dischargenum)
        dischargeDict[StreamIndexList[counter]] = dischargenum
        for inst in ISTblSrNameList:
            if str(inst).upper() == str(StreamIndexList[counter]).upper():
                instreamnum += 1
        instreamnumlist.append(instreamnum)
        counter += 1
    parent.InstreamNumList = instreamnumlist
    parent.DischargeNumList = dischargenumlist
    parent.DischargeDict = dischargeDict
    parent.ISDischargeType = ISDischargeType
    parent.WatershedNameDictionary = WatershedNameDictionary
    parent.StressorListDictionary = StressorListDictionary
    parent.InTMDLDictionary = InTMDLDictionary
    parent.StreamTierDictionary = StreamTierDictionary
    parent.StreamTMDLDictionary = StreamTMDLDictionary
    parent.WaterTableDictionary = WaterTableDictionary
    parent.WaterTableNameDictionary = WaterTableNameDictionary
    parent.BasinCodeDictionary = BasinCodeDictionary
    parent.BasinNameDictionary = BasinNameDictionary
    parent.UniqueTMDLS = UniqueTMDLS
    WriteFileString('Finished Flow Classification Thread')


def WatershedClassDataThread(parent, AppNumber, RevisionNumber, WaterTableDictionary, WaterTableNameDictionary):
    WriteFileString('Starting Watershed Classification Thread')
    try:
        conn = odbc.odbc(DMMESDEConnection)
        conn2 = odbc.odbc(Dmlr_DB)
        conn3 = odbc.odbc(WaterQuality)
        wqConn = odbc.odbc(WaterQuality)
    except:
        conn = odbc.odbc(DMMESDEConnection)
        conn2 = odbc.odbc(Dmlr_DB)
        conn3 = odbc.odbc(WaterQuality)
        wqConn = odbc.odbc(WaterQuality)
    dxcursor = conn3.cursor()  #cursor for dxk_test database
    cursor2 = conn2.cursor()  #cursor for dmlr database
    cursor = conn.cursor()  #cursor for EP database
    wqCursor = wqConn.cursor()
    WaterTableList = []
    BigWaterList = []
    WSAffectedAcresList = []
    WSBeginDateList = []
    WSEndDateList = []
    WSMinSizeList = []
    WSMaxSizeList = []
    WSAvgSizeList = []
    WSMinDistSizeList = []
    WSMaxDistSizeList = []
    WSAvgDistSizeList = []
    WSNumberOutfallsList = []
    WSOver10List = []
    WSOver50List = []
    WSOver75List = []
    WSAvgTimeToMaxList = []
    WSAvgMinFlowList = []
    WSAvgMaxFlowList = []
    WSAvgDropoffTimeList = []
    WSAvgFinalDischargeList = []
    WaterTableNameList = []
    for each in WaterTableDictionary:
        WaterTableList.append(WaterTableDictionary[each])
        WaterTableNameList.append(WaterTableNameDictionary[each])
    WaterTableList = list(set(WaterTableList))
    tablecounter = 0
    while tablecounter < len(WaterTableList):
        IStreamMPIDS = []
        IStreamAcres = []
        IStreamDistAcres = []
        StreamSearcherList = []
        NumMPIDS = 0
        StreamParamList = []
        NumMPIDS = 0
        RecordCount = 0
        StreamMPIDS = []
        MPFlow = []
        MPFlowCount = 0
        MPFlowList = ["GPM", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPPh = []
        MPPhCount = 0
        MPPhList = ["Std", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPIron = []
        MPIronCount = 0
        MPIronList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPManganese = []
        MPManganeseCount = 0
        MPManganeseList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPTss = []
        MPTssCount = 0
        MPTssList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPSs = []
        MPSsCount = 0
        MPSsList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPPrec = []
        MPPrecCount = 0
        MPPrecList = ["In", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPTemp = []
        MPTempCount = 0
        MPTempList = ["Celsius", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPAcid = []
        MPAcidCount = 0
        MPAcidList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPAlka = []
        MPAlkaCount = 0
        MPAlkaList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPConMic = []
        MPConMicCount = 0
        MPConMicList = ["uS/cm", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPTds = []
        MPTdsCount = 0
        MPTdsList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPSulf = []
        MPSulfCount = 0
        MPSulfList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPHard = []
        MPHardCount = 0
        MPHardList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPChlor = []
        MPChlorCount = 0
        MPChlorList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPAmmonia = []
        MPAmmoniaCount = 0
        MPAmmoniaList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPNitrite = []
        MPNitriteCount = 0
        MPNitriteList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPNitrate = []
        MPNitrateCount = 0
        MPNitrateList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPAl = []
        MPAlCount = 0
        MPAlList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPPb = []
        MPPbCount = 0
        MPPbList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPCu = []
        MPCuCount = 0
        MPCuList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPNi = []
        MPNiCount = 0
        MPNiList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPAs = []
        MPAsCount = 0
        MPAsList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPBa = []
        MPBaCount = 0
        MPBaList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPCd = []
        MPCdCount = 0
        MPCdList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPCr = []
        MPCrCount = 0
        MPCrList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPHg = []
        MPHgCount = 0
        MPHgList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPSe = []
        MPSeCount = 0
        MPSeList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        MPAg = []
        MPAgCount = 0
        MPAgList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA"]
        StreamParamList.append(MPFlowList)
        StreamParamList.append(MPPhList)
        StreamParamList.append(MPIronList)
        StreamParamList.append(MPManganeseList)
        StreamParamList.append(MPTssList)
        StreamParamList.append(MPSsList)
        StreamParamList.append(MPPrecList)
        StreamParamList.append(MPTempList)
        StreamParamList.append(MPAcidList)
        StreamParamList.append(MPAlkaList)
        StreamParamList.append(MPConMicList)
        StreamParamList.append(MPTdsList)
        StreamParamList.append(MPSulfList)
        StreamParamList.append(MPHardList)
        StreamParamList.append(MPChlorList)
        StreamParamList.append(MPAmmoniaList)
        StreamParamList.append(MPNitriteList)
        StreamParamList.append(MPNitrateList)
        StreamParamList.append(MPAlList)
        StreamParamList.append(MPPbList)
        StreamParamList.append(MPCuList)
        StreamParamList.append(MPNiList)
        StreamParamList.append(MPAsList)
        StreamParamList.append(MPBaList)
        StreamParamList.append(MPCdList)
        StreamParamList.append(MPCrList)
        StreamParamList.append(MPHgList)
        StreamParamList.append(MPSeList)
        StreamParamList.append(MPAgList)
        BigWaterList.append(StreamParamList)
        tablecounter += 1
    parent.BigWaterList = BigWaterList
    parent.WaterTableList = WaterTableList
    parent.WaterTableNameList = WaterTableNameList
    WriteFileString('Finished Watershed Classification Thread')


def TMDLTotalsDataThread(parent, AppNumber, RevisionNumber, NPWSList, NPWSNameList, UniqueTMDLS, NPStatusList,
                         NPFacLocList, NPMPIDList, NPLocNoList, NPWaterShedAcresList, NPNameList):
    WriteFileString('Starting TMDL Narrative Thread')
    try:
        conn = odbc.odbc(DMMESDEConnection)
        conn2 = odbc.odbc(Dmlr_DB)
        conn3 = odbc.odbc(WaterQuality)
        wqConn = odbc.odbc(WaterQuality)
    except:
        conn = odbc.odbc(DMMESDEConnection)
        conn2 = odbc.odbc(Dmlr_DB)
        conn3 = odbc.odbc(WaterQuality)
        wqConn = odbc.odbc(WaterQuality)
    dxcursor = conn3.cursor()  #cursor for dxk_test database
    cursor2 = conn2.cursor()  #cursor for dmlr database
    cursor = conn.cursor()  #cursor for EP database
    wqCursor = wqConn.cursor()
    i = 0
    TMDLCodesList = []
    TMDLNamesList = []
    BigTMDLList = []
    while i < len(NPWSList):
        if NPWSList[i] != "" and NPWSList[i] != "None" and NPWSList[i] is not None and NPWSList[i] not in TMDLCodesList:
            TMDLCodesList.append(NPWSList[i])
            TMDLNamesList.append(NPWSNameList[i])
        i += 1
    tablecounter = 0
    while tablecounter < len(TMDLNamesList):
        TStreamMPIDS = []
        TStreamAcres = []
        TStreamDistAcres = []
        StreamSearcherList = []
        NumMPIDS = 0
        StreamParamList = []
        RecordCount = 0
        StreamMPIDS = []
        MPFlow = []
        MPFlowCount = 0
        MPFlowList = ["GPM", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
                      "NA", "NA", "NA", "NA"]
        MPPh = []
        MPPhCount = 0
        MPPhList = ["Std", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
                    "NA", "NA", "NA", "NA"]
        MPIron = []
        MPIronCount = 0
        MPIronList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
                      "NA", "NA", "NA", "NA"]
        MPManganese = []
        MPManganeseCount = 0
        MPManganeseList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
                           "NA", "NA", "NA", "NA", "NA"]
        MPTss = []
        MPTssCount = 0
        MPTssList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
                     "NA", "NA", "NA", "NA"]
        MPSs = []
        MPSsCount = 0
        MPSsList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
                    "NA", "NA", "NA", "NA"]
        MPPrec = []
        MPPrecCount = 0
        MPPrecList = ["In", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
                      "NA", "NA", "NA", "NA"]
        MPTemp = []
        MPTempCount = 0
        MPTempList = ["Celsius", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
                      "NA", "NA", "NA", "NA", "NA"]
        MPAcid = []
        MPAcidCount = 0
        MPAcidList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
                      "NA", "NA", "NA", "NA"]
        MPAlka = []
        MPAlkaCount = 0
        MPAlkaList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
                      "NA", "NA", "NA", "NA"]
        MPConMic = []
        MPConMicCount = 0
        MPConMicList = ["uS/cm", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
                        "NA", "NA", "NA", "NA", "NA"]
        MPTds = []
        MPTdsCount = 0
        MPTdsList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
                     "NA", "NA", "NA", "NA"]
        MPSulf = []
        MPSulfCount = 0
        MPSulfList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
                      "NA", "NA", "NA", "NA"]
        MPHard = []
        MPHardCount = 0
        MPHardList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
                      "NA", "NA", "NA", "NA"]
        MPChlor = []
        MPChlorCount = 0
        MPChlorList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
                       "NA", "NA", "NA", "NA"]
        MPAmmonia = []
        MPAmmoniaCount = 0
        MPAmmoniaList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
                         "NA", "NA", "NA", "NA", "NA"]
        MPNitrite = []
        MPNitriteCount = 0
        MPNitriteList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
                         "NA", "NA", "NA", "NA", "NA"]
        MPNitrate = []
        MPNitrateCount = 0
        MPNitrateList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
                         "NA", "NA", "NA", "NA", "NA"]
        MPAl = []
        MPAlCount = 0
        MPAlList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
                    "NA", "NA", "NA", "NA"]
        MPPb = []
        MPPbCount = 0
        MPPbList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
                    "NA", "NA", "NA", "NA"]
        MPCu = []
        MPCuCount = 0
        MPCuList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
                    "NA", "NA", "NA", "NA"]
        MPNi = []
        MPNiCount = 0
        MPNiList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
                    "NA", "NA", "NA", "NA"]
        MPAs = []
        MPAsCount = 0
        MPAsList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
                    "NA", "NA", "NA", "NA"]
        MPBa = []
        MPBaCount = 0
        MPBaList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
                    "NA", "NA", "NA", "NA"]
        MPCd = []
        MPCdCount = 0
        MPCdList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
                    "NA", "NA", "NA", "NA"]
        MPCr = []
        MPCrCount = 0
        MPCrList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
                    "NA", "NA", "NA", "NA"]
        MPHg = []
        MPHgCount = 0
        MPHgList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
                    "NA", "NA", "NA", "NA"]
        MPSe = []
        MPSeCount = 0
        MPSeList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
                    "NA", "NA", "NA", "NA"]
        MPAg = []
        MPAgCount = 0
        MPAgList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
                    "NA", "NA", "NA", "NA"]
        StreamParamList.append(MPFlowList)
        StreamParamList.append(MPPhList)
        StreamParamList.append(MPIronList)
        StreamParamList.append(MPManganeseList)
        StreamParamList.append(MPTssList)
        StreamParamList.append(MPSsList)
        StreamParamList.append(MPPrecList)
        StreamParamList.append(MPTempList)
        StreamParamList.append(MPAcidList)
        StreamParamList.append(MPAlkaList)
        StreamParamList.append(MPConMicList)
        StreamParamList.append(MPTdsList)
        StreamParamList.append(MPSulfList)
        StreamParamList.append(MPHardList)
        StreamParamList.append(MPChlorList)
        StreamParamList.append(MPAmmoniaList)
        StreamParamList.append(MPNitriteList)
        StreamParamList.append(MPNitrateList)
        StreamParamList.append(MPAlList)
        StreamParamList.append(MPPbList)
        StreamParamList.append(MPCuList)
        StreamParamList.append(MPNiList)
        StreamParamList.append(MPAsList)
        StreamParamList.append(MPBaList)
        StreamParamList.append(MPCdList)
        StreamParamList.append(MPCrList)
        StreamParamList.append(MPHgList)
        StreamParamList.append(MPSeList)
        StreamParamList.append(MPAgList)
        BigTMDLList.append(StreamParamList)
        tablecounter += 1
    TMDLDict = {}
    TMDLDict["0"] = "Flow"
    TMDLDict["1"] = "pH"
    TMDLDict["2"] = "Iron"
    TMDLDict["3"] = "Manganese"
    TMDLDict["4"] = "TSS"
    TMDLDict["5"] = "SS"
    TMDLDict["6"] = "Precipitation"
    TMDLDict["7"] = "Temperature"
    TMDLDict["8"] = "Acidity"
    TMDLDict["9"] = "Alkalinity"
    TMDLDict["10"] = "Conductivity"
    TMDLDict["11"] = "TDS"
    TMDLDict["12"] = "Sulfates"
    TMDLDict["13"] = "Hardness"
    TMDLDict["14"] = "Chlorides"
    TMDLDict["15"] = "Ammonia"
    TMDLDict["16"] = "Nitrites"
    TMDLDict["17"] = "Nitrates"
    TMDLDict["18"] = "Aluminum"
    TMDLDict["19"] = "Lead"
    TMDLDict["20"] = "Copper"
    TMDLDict["21"] = "Nickel"
    TMDLDict["22"] = "Arsenic"
    TMDLDict["23"] = "Barium"
    TMDLDict["24"] = "Cadmium"
    TMDLDict["25"] = "Chromium"
    TMDLDict["26"] = "Mercury"
    TMDLDict["27"] = "Selenium"
    TMDLDict["28"] = "Silver"
    parent.TMDLDict = TMDLDict
    parent.BigTMDLList = BigTMDLList
    parent.TMDLCodesList = TMDLCodesList
    parent.TMDLNamesList = TMDLNamesList
    TMDLNarrative = ""
    UniqueTMDLList = UniqueTMDLS
    UniqueTMDLCodeList = []
    UniqueTMDLLDCode = []
    UniquePropList = []
    UniquePropFacLocList = []
    UniqueApprovedFacLocList = []
    UniqueApprovedList = []
    UniqueBSList = []
    UniqueTMDLAvgFlow = []
    UniqueTMDLEstParam = []
    UniqueTMDLTWLA = []
    UniqueApprovedAcresList = []
    UniquePropAcresList = []
    UniquePropNameList = []
    UniqueApprovedNameList = []
    UniqueTMDLPropWasteEst = []
    UniqueTMDLApprovedWasteEst = []
    UniqueTMDLsList2 = []
    LenUniqueTMDLS = len(UniqueTMDLList)
    if LenUniqueTMDLS == 0:
        TMDLNarrative += "The outfalls of the permit are not permitted to affect any Total Maximum Daily Load Watersheds or impaired segments."
    else:
        if LenUniqueTMDLS == 1:
            TMDLNarrative += ("There is one TMDL area which contains a waste load allocation for active coal mining facilities \
affected by the outfalls of this permit - " + UniqueTMDLList[0] + ".")
        else:
            TMDLNarrative += ("There are " + str(LenUniqueTMDLS) + " TMDL areas which contain a waste load allocation for active coal mining \
facilities affected by the outfalls of this permit - " + str(" ,".join(UniqueTMDLList)) + ".")
        UniqueTMDLsList2 = []
        for each in UniqueTMDLList:
            i = 0
            while i < len(NPMPIDList):
                if NPWSNameList[i] == each:
                    if NPWSList[i] not in UniqueTMDLCodeList:
                        UniqueTMDLCodeList.append(NPWSList[i])
                        UniqueTMDLsList2.append(each)
                        UniqueBSList.append([])
                        UniquePropList.append([])
                        UniqueApprovedList.append([])
                        UniqueApprovedAcresList.append([])
                        UniquePropAcresList.append([])
                        UniquePropNameList.append([])
                        UniquePropFacLocList.append([])
                        UniqueApprovedFacLocList.append([])
                        UniqueApprovedNameList.append([])
                        UniqueTMDLAvgFlow.append([])
                        UniqueTMDLEstParam.append([])
                        UniqueTMDLTWLA.append([])
                        UniqueTMDLPropWasteEst.append([])
                        UniqueTMDLApprovedWasteEst.append([])
                        UniqueTMDLLDCode.append([])
                i += 1
        i = 0
        while i < len(UniqueTMDLCodeList):
            sqlSearch = str(
                "select TblLdCode,TWsAvgFlow,TWsParamForEst,TWsWLA from DmlrTMDLWaterShed_Stressor where TWsCode = '" + str(
                    UniqueTMDLCodeList[i]) + "'")
            cursor2.execute(sqlSearch)
            result = cursor2.fetchall()
            for each in result:
                UniqueBSList[i].append(each)
                UniqueTMDLAvgFlow[i].append(each[1])
                UniqueTMDLEstParam[i].append(each[2])
                UniqueTMDLTWLA[i].append(each[3])
                UniqueTMDLLDCode[i].append(each[0])
                UniqueTMDLPropWasteEst[i].append(float(0))
                UniqueTMDLApprovedWasteEst[i].append(float(0))
            j = 0
            while j < len(NPStatusList):
                if (NPStatusList[j] == "A" or NPStatusList[j] == "NC" or NPStatusList[j] == "ND") and str(
                        NPWSList[j]) == str(UniqueTMDLCodeList[i]):
                    UniqueApprovedList[i].append(NPLocNoList[j])
                    UniqueApprovedAcresList[i].append(NPWaterShedAcresList[j])
                    UniqueApprovedNameList[i].append(NPNameList[j])

                    UniqueApprovedFacLocList[i].append(NPFacLocList[j])

                elif (NPStatusList[j] != "A" and NPStatusList[j] != "NC" and NPStatusList[j] != "ND") and str(
                        NPWSList[j]) == str(UniqueTMDLCodeList[i]):
                    UniquePropList[i].append(NPLocNoList[j])
                    UniquePropAcresList[i].append(NPWaterShedAcresList[j])
                    UniquePropNameList[i].append(NPNameList[j])

                    UniquePropFacLocList[i].append(NPFacLocList[j])
                j += 1
            if len(UniqueApprovedList[i]) > 0:
                TMDLNarrative += ("\nThe outfall(s) " + str(",".join(UniqueApprovedList[i])) + " are previously approved for this permit for discharge \
to the " + UniqueTMDLsList2[i].title() + " Watershed.")
            else:
                TMDLNarrative += ("\nThere are no currently approved discharges to the " + UniqueTMDLsList2[
                    i].title() + " Watershed from this permit.\n")
            if len(UniquePropList[i]) == 0:
                TMDLNarrative += ("\nThere are no proposed discharges to the " + UniqueTMDLsList2[
                    i].title() + " Watershed for this application.")
            else:
                TMDLNarrative += ("\nThe outfall(s) " + str(", ".join(UniquePropList[i])) + " are proposed to add to waste load within \
the " + UniqueTMDLsList2[i].title() + " Watershed.")
                TMDLNarrative += ("\nThis will add load to the TMDL(s) for the stressor(s) " + str(
                    " and ".join(UniqueTMDLLDCode[i])) + ".")
                k = 0
                while k < len(UniqueTMDLLDCode[i]):
                    TMDLNarrative += (
                    "\nFor " + str(UniqueTMDLLDCode[i][k]) + " in the " + str(UniqueTMDLsList2[i].title()) + " TMDL, \
the average flow is estimated at " + str(UniqueTMDLAvgFlow[i][k]) + " gallons per minute per acre, and the concentration estimation used for \
proposed or not constructed outfalls is " + str(UniqueTMDLEstParam[i][k]) + " mg/L.")
                    UniqueTMDLPropWasteEst[i][k] = float(UniqueTMDLEstParam[i][k]) * float(3.79) * float(
                        UniqueTMDLAvgFlow[i][k]) * float(525600) * float(0.000001)
                    TMDLNarrative += (
                    "\n\nTherefore, the calculation for additional waste load is " + str(UniqueTMDLEstParam[i][k]) + "mg/L X \
3.79 L/Gal X " + str(UniqueTMDLAvgFlow[i][k]) + " Gal/Min/Acre X 525,600 Min/Year X 10e-6 kg/mg \
= " + str(float(UniqueTMDLEstParam[i][k]) * float(3.79) * float(UniqueTMDLAvgFlow[i][k]) * float(525600) * float(
                        0.000001)) + " kg/acre/year for each watershed acre.")
                    l = 0
                    propactotal = float(0)
                    while l < len(UniquePropList[i]):
                        propactotal += float(UniquePropAcresList[i][l])
                        l += 1
                    TMDLNarrative += (
                    "\n\nThe total watershed area of " + str(",".join(UniquePropNameList[i])) + " equals " + str(
                        propactotal) + " \
acres. Therefore, the total additional waste load proposed is " + str(
                        propactotal * UniqueTMDLPropWasteEst[i][k]) + " kilograms per year.\n\n")
                    k += 1
                TMDLNarrative += ("\n\nTables summarizing the proposed outfalls are included below.")
            i += 1
    parent.UniqueApprovedList = UniqueApprovedList
    parent.UniquePropFacLocList = UniquePropFacLocList
    parent.UniqueApprovedFacLocList = UniqueApprovedFacLocList
    parent.UniqueApprovedAcresList = UniqueApprovedAcresList
    parent.UniqueApprovedNameList = UniqueApprovedNameList
    parent.UniqueTMDLApprovedWasteEst = UniqueTMDLApprovedWasteEst
    parent.UniquePropList = UniquePropList
    parent.UniquePropAcresList = UniquePropAcresList
    parent.UniquePropNameList = UniquePropNameList
    parent.UniqueTMDLPropWasteEst = UniqueTMDLPropWasteEst
    parent.UniqueTMDLLDCode = UniqueTMDLLDCode
    parent.TMDLNarrative = TMDLNarrative
    parent.UniqueTMDLList = UniqueTMDLList
    parent.UniqueTMDLsList2 = UniqueTMDLsList2
    if len(UniqueApprovedList) > 0 or len(UniquePropList) > 0:
        FutureGrowthNarrative = "The Department will track the future growth balance given in the TMDL for this watershed \
utilizing the Department TMDL Reporting System. The future growth allocation will be managed in a manner similar to an offset \
where new applications will draw from future growth if mining waste load is not available for the watershed. If the future growth \
is utilized as well as the mining waste load for the watershed, the permit will be required to have a mining waste load offset in order to discharge."
        if "Levisa River" in UniqueTMDLS:
            PCBNarrative = "PCBs were widely used as dielectric and coolant fluids in transformers, capacitors, and electric \
motors from approximately 1920 until regulated by the Toxic Substance Control Act in 1978. Subsequently, production was banned in the \
United States in 1979 and equipment containing PCBs was required to be registered by EPA. Most PCB use in the Virginia coalfields would \
be associated with power reticulation and industrial electrical applications of which underground mining and prep plants would have been included."
        else:
            PCBNarrative = "The permit is not expected to have a direct effect within the Levisa River watershed; therefore, \
PCB monitoring is not mandated for the permit."
    else:
        FutureGrowthNarrative = "Not Applicable"
        PCBNarrative = "The permit is not expected to have a direct effect within the Levisa River watershed; therefore, \
PCB monitoring is not mandated for the permit."
    parent.FutureGrowthNarrative = FutureGrowthNarrative
    parent.PCBNarrative = PCBNarrative
    WriteFileString('Finished TMDL Narrative Thread')


################DATA THREADS############DATA THREADS#################DATA THREADS###############
def PopulateFields(GetApp, parent, AppNumber, connList, rList, methodList, searchList):
    WriteFileString('Gathering Administrative Data')
    UserName = getpass.getuser()
    parent.UserName = UserName
    ExactDate = str(datetime.datetime.today())
    parent.ExactDate = ExactDate
    found = 0
    cursor2 = connList[0].cursor()  #cursor for dmlr database
    dxcursor = connList[1].cursor()  #cursor for waterquality database
    variableList = []
    selectedRev = GetApp.ReviewSelection
    try:
        wqConn = odbc.odbc(WaterQuality)
        wqCursor = wqConn.cursor()
    except:
        wqConn = odbc.odbc(WaterQuality)
        wqCursor = wqConn.cursor()
    if type(searchList) is str:
        sqlSearch = str("select LineageNo,OrderNo,ParentNo,SessionNo from SessionsTable where AppNo = '" + str(
            AppNumber) + "' order by ABS(LineageNo) desc")
        wqCursor.execute(sqlSearch)
        result = wqCursor.fetchone()
        if type(result) is not types.NoneType:
            if len(result) > 0:
                Lineage = str(int(result[0]) + 1)
                Order = str(1)
                ParentNo = str(0)
            else:
                Lineage = str(1)
                Order = str(1)
                ParentNo = str(0)
        else:
            Lineage = str(1)
            Order = str(1)
            ParentNo = str(0)
    else:
        Lineage = str(searchList[4])
        Order = str(int(searchList[5]) + 1)
        ParentNo = str(int(searchList[2]))
    sqlSearch = str("select ExactDate from SessionsTable where AppNo = '" + str(AppNumber) + "'")
    wqCursor.execute(sqlSearch)
    result = wqCursor.fetchall()
    if type(result) is not types.NoneType:
        lenresult = len(result)
        Session = str(lenresult + 1)
    else:
        Session = str(1)
    parent.Session = Session
    if selectedRev == 0 or selectedRev != 0:
        cursor = connList[2].cursor()  #cursor for EP database
        sqlSearch = str("select RevNo,TblSeCode,TblWhCode,TblWhName from Dmlr_AppTracking where AppNo = '" + str(
            AppNumber) + "' order by ABS(RevNo) desc, AtStart desc")
        cursor.execute(sqlSearch)
        parent.ReviewNumber = "None"
        ReviewerCode = "None"
        result = cursor.fetchall()
        if type(result) is not types.NoneType:
            parent.MaxReviews = str(result[0][0])
            for each in result:
                if str(each[1]) == 'H2O ':
                    parent.ReviewNumber = str(each[0])
                    ReviewerCode = each[2]
                    ReviewerName = each[3].title()
                    break;
                if str(each[2]) == 'STW' or str(each[2]) == 'WWW':
                    parent.ReviewNumber = str(each[0])
                    ReviewerCode = each[2]
                    ReviewerName = each[3].title()
                    break;
        if ReviewerCode == "None":
            for each in result:
                if str(each[1]) == 'PERM':
                    parent.ReviewNumber = str(each[0])
                    ReviewerCode = each[2]
                    ReviewerName = each[3].title()
        RevisionNumber = parent.MaxReviews
        StoreSession(UserName, ExactDate, AppNumber, RevisionNumber, Session, Lineage, Order, ParentNo)
        ReviewerPhoneNumber = "(276)523-8100"
        sqlSearch = str("select PeNo,TblApCode from vw_Dmlr_Applications where AppNo = '" + str(
            AppNumber) + "'  order by ABS(RevNo) desc")
        cursor.execute(sqlSearch)
        result = cursor.fetchone()
        CSMOPermitNumber = result[0]
        parent.CSMOPermitNumber = CSMOPermitNumber
        tempAppType = result[1]
        sqlSearch = str(
            "select TblApDesc,TblApCategory from ApplicTypeTbl where TblApCode = '" + str(tempAppType) + "'")
        cursor.execute(sqlSearch)
        result = cursor.fetchone()
        PermitType = str(result[0]).title()
        PermitCat = str(result[1])
        if PermitCat == "NEW":
            PermitType = "New Permit"
        elif PermitCat == "REV":
            PermitType = "Modification"
        elif PermitCat == "REN":
            PermitType = "Renewal"
        sqlSearch = str(
            "select PermitNo, PrPermitNo,ExpireDt,TblApCode,TblApDesc,Operation,ApName,ApAddr,ApCity,ApState,ApZip,ApDesc,ApComment from GenInfo where AppNo = '" + str(
                AppNumber) + "' and RevNo = " + str(RevisionNumber))
        cursor.execute(sqlSearch)
        result = cursor.fetchone()
        PermitHistoryList = []
        if str(result[0]).rstrip().upper() not in ["", "None", "NULL"]:
            past = []
            c = str(result[0])
            while c.rstrip().upper() not in ["", "None", "NULL"]:
                past.append(c)
                sqlSearch = str("select PeTransferFrom from DmlrPermits where PeNo = '" + c + "'")
                cursor2.execute(sqlSearch)
                r = cursor2.fetchone()
                c = ""
                if type(r) is not types.NoneType:
                    if type(r[0]) is not types.NoneType:
                        c = str(r[0])
            future = []
            c = str(result[0])
            while c.rstrip().upper() not in ["", "None", "NULL"]:
                future.append(c)
                sqlSearch = str("select PeTransferTo from DmlrPermits where PeNo = '" + c + "'")
                cursor2.execute(sqlSearch)
                r = cursor2.fetchone()
                c = ""
                if type(r) is not types.NoneType:
                    if type(r[0]) is not types.NoneType:
                        c = str(r[0])
            PermitHistoryList = list(set(past + future))
        else:
            if str(result[1]).rstrip().upper() not in ["", "None", "NULL"]:
                previous = []
                c = str(result[0])
                while c.rstrip().upper() not in ["", "None", "NULL"]:
                    previous.append(c)
                    sqlSearch = str("select PeTransferFrom from DmlrPermits where PeNo = '" + c + "'")
                    cursor2.execute(sqlSearch)
                    r = cursor2.fetchone()
                    c = ""
                    if type(r) is not types.NoneType:
                        if type(r[0]) is not types.NoneType:
                            c = str(r[0])
                PermitHistoryList = list(set(past))
        PHL = ["'" + x + "'" for x in PermitHistoryList]
        PermitHistoryList = ",".join(PHL)
        parent.PermitHistoryList = PermitHistoryList
        FormerCSMOPermitNumber = result[1]
        if result[2] is not None and PermitCat == "REN":
            ExpDate = datetime.date(result[2].year + 5, result[2].month, result[2].day)
            ExpirationDate = ExpDate.isoformat()
        else:
            ExpirationDate = result[2]
        parent.ExpirationDateHeld = ExpirationDate
        ApplicationTypeCode = result[3]
        ApplicationType = result[4]
        FacilityName = result[5]
        PermitteeName = result[6]
        PermitteeAddress = result[7]
        PermitteeCity = result[8]
        PermitteeState = result[9]
        PermitteeZip = result[10]
        PermitDescription = result[11]
        FacilityDescription = result[12]  #added
        found = 1
        sqlSearch = str(
            "select AmlTele from AdminInfo where AppNo = " + str(AppNumber) + " and RevNo = " + str(RevisionNumber))
        cursor.execute(sqlSearch)
        result = cursor.fetchone()
        OperatorPhone = result[0]
        if found != 1:
            parent.StatusBar.SetStatusText("Error Occurred, please check Application Number")
        else:
            found = 0
            sqlSearch = str(
                "select AtInspector,CAST(AtDescription as varchar(8000)) as AtDescription,AtPublicationNo,AtInspApprvDate,AtPubActDate,AtCommentExpDate,AtAdminDecDate,AtIssueDate,AtOperator from Dmlr_AppData where AppNo = '" + str(
                    AppNumber) + "' and RevNo = " + str(parent.MaxReviews))
            cursor.execute(sqlSearch)
            result = cursor.fetchone()
            InspectorCode = result[0]
            ApplicationDescription = result[1]
            FacilityDescription = ApplicationDescription
            PublicationNumber = result[2]
            if result[3] is not None:
                RevBeginDate = result[3].isoformat()
            else:
                RevBeginDate = result[3]
            if result[4] is not None:
                CommentBegin = result[4].isoformat()
            else:
                CommentBegin = result[4]
            if result[5] is not None:
                CommentEnd = result[5].isoformat()
            else:
                CommentEnd = result[5]
            if result[6] is not None:
                AdminDecisionDate = result[6]
            else:
                AdminDecisionDate = result[6]
            if result[7] is not None:
                PermitIssueDate = result[7]
            else:
                PermitIssueDate = result[7]
            OperatorName = result[8]
            found = 1
            sqlSearch = str(
                "select Northing,Easting,OpLoc from SiteInfo where AppNo = '" + str(AppNumber) + "' and RevNo = " + str(
                    RevisionNumber))
            cursor.execute(sqlSearch)
            result = cursor.fetchone()
            PermitNorthing = result[0]
            PermitEasting = result[1]
            PermitLocation = result[2]
            sqlSearch = str("select TblNpName from AdminInfo where AppNo = '" + str(AppNumber) + "' and RevNo = " + str(
                RevisionNumber))
            cursor.execute(sqlSearch)
            result = cursor.fetchone()
            if result is not None:
                NewspaperName = str(result[0])
                NewspaperName = NewspaperName.rstrip("-")
            else:
                NewspaperName = " "
            sqlSearch = str("select TblQuCode,TblQuDesc from SiteInfo_OpQuad where AppNo = '" + str(
                AppNumber) + "' and RevNo = " + str(RevisionNumber))
            cursor.execute(sqlSearch)
            result = cursor.fetchone()
            QuadCode = result[0]
            QuadName = result[1]
            sqlSearch = str("select Result,TblCnCode,TblCnName from SiteInfo_PropAcres where AppNo = '" + str(
                AppNumber) + "' and RevNo = " + str(RevisionNumber))
            cursor.execute(sqlSearch)
            result = cursor.fetchall()
            tempPermAcres = []
            tempPermCountyName = []
            tempPermCountyCode = []
            for i in range(0, len(result)):
                tempPermAcres.append(str(result[i][0]))
                tempPermCountyCode.append(str(result[i][1]))
                tempPermCountyName.append(str(result[i][2]))
            PermitAcres = ",".join(tempPermAcres)
            PermitCountyCode = ",".join(tempPermCountyCode)
            PermitCountyName = ",".join(tempPermCountyName)
            OriginalIssueDate = ""
            NPDESNumber = "N/A"
            if CSMOPermitNumber is not None and CSMOPermitNumber != "":
                sqlSearch = str("select PeOrgIssueDt, PeIssueDt, PeNpdesNo from DmlrPermits where PeNo = '" + str(
                    CSMOPermitNumber) + "'")
                cursor2.execute(sqlSearch)
                result = cursor2.fetchone()
                if type(result[0]) is not None:
                    if result[0] is not None:
                        OriginalIssueDate = result[0]
                        if str(AdminDecisionDate) != "None":
                            higherYear = AdminDecisionDate.year
                            lowerYear = OriginalIssueDate.year
                            multiplier = int((higherYear - lowerYear) / 5) + 1
                            addYears = multiplier * 5
                            ExpDate = datetime.date(OriginalIssueDate.year + addYears, OriginalIssueDate.month,
                                                    OriginalIssueDate.day)
                            ExpirationDate = ExpDate.isoformat()
                            OriginalIssueDate = result[0].isoformat()
                            AdminDecisionDate = AdminDecisionDate.isoformat()
                    else:
                        OriginalIssueDate = result[0]
                        if str(PermitIssueDate) != "None" and str(AdminDecisionDate) != "None":
                            higherYear = AdminDecisionDate.year
                            lowerYear = OriginalIssueDate.year
                            multiplier = int((higherYear - lowerYear) / 5) + 1
                            addYears = multiplier * 5
                            ExpDate = datetime.date(PermitIssueDate.year + addYears, PermitIssueDate.month,
                                                    PermitIssueDate.day)
                            ExpirationDate = ExpDate.isoformat()
                            AdminDecisionDate = AdminDecisionDate.isoformat()
                            PermitIssueDate = PermitIssueDate.isoformat()
                NPDESNumber = result[2]
            parent.StatusBar.SetStatusText("Application #: " + str(AppNumber) + ", Review " + str(RevisionNumber))
            #GeneralInfo Variables Defined
            parent.ApplicationNumber = str(AppNumber)
            if str(parent.ApplicationNumber) == "" or str(parent.ApplicationNumber) == "None":
                parent.ApplicationNumber = "Pending"
            parent.FormerCSMONumber = str(FormerCSMOPermitNumber)
            if str(parent.FormerCSMONumber) == "" or str(parent.FormerCSMONumber) == "None":
                parent.FormerCSMONumber = "N/A"
            parent.ApplicationDescription = ApplicationDescription
            if parent.ApplicationDescription == "" or parent.ApplicationDescription == "None":
                parent.ApplicationDescription = "N/A"
            parent.ApplicationType = str(ApplicationType)
            if str(parent.ApplicationType) == "" or str(parent.ApplicationType) == "None":
                parent.ApplicationType = "N/A"
            temp = str(PermitIssueDate).replace("T00:00:00", "").replace("-", r"/").replace(" 00:00:00", "").replace(
                "00:00:00", "").split(r"/", 1)
            temp.reverse()
            parent.PermitIssueDate = r"/".join(temp)
            if str(parent.PermitIssueDate) == "" or str(parent.PermitIssueDate) == "None":
                parent.PermitIssueDate = "Pending"
            temp = str(AdminDecisionDate).replace("T00:00:00", "").replace("00:00:00", "").replace("-", r"/").split(
                r"/", 1)
            temp.reverse()
            parent.AdminDecisionDate = r"/".join(temp)
            if str(parent.AdminDecisionDate) == "" or str(parent.AdminDecisionDate) == "None":
                parent.AdminDecisionDate = "Pending"
            temp = str(CommentEnd).replace("T00:00:00", "").replace("00:00:00", "").replace("-", r"/").split(r"/", 1)
            temp.reverse()
            parent.CommentEnd = r"/".join(temp)
            if str(parent.CommentEnd) == "" or str(parent.CommentEnd) == "None":
                parent.CommentEnd = "Pending"
            temp = str(CommentBegin).replace("T00:00:00", "").replace("00:00:00", "").replace("-", r"/").split(r"/", 1)
            temp.reverse()
            parent.CommentBegin = r"/".join(temp)
            if str(parent.CommentBegin) == "" or str(parent.CommentBegin) == "None":
                parent.CommentBegin = "Pending"
            temp = str(RevBeginDate).replace("T00:00:00", "").replace("00:00:00", "").replace("-", r"/").split(r"/", 1)
            temp.reverse()
            parent.RevBeginDate = r"/".join(temp)
            temp = str(OriginalIssueDate).replace("T00:00:00", "").replace("00:00:00", "").replace("-", r"/").split(
                r"/", 1)
            temp.reverse()
            parent.OriginalIssueDate = r"/".join(temp)
            parent.AdminSignoffDate = parent.RevBeginDate
            if str(parent.RevBeginDate) == "" or str(parent.RevBeginDate) == "None":
                parent.RevBeginDate = "Pending"
                parent.AdminSignoffDate = "Pending"
            parent.ReviewerName = str(ReviewerName)
            if str(parent.ReviewerName) == "" or str(parent.ReviewerName) == "None":
                parent.ReviewerName = "N/A"
            temp = str(ExpirationDate).replace("T00:00:00", "").replace("00:00:00", "").replace("-", r"/").split(r"/",
                                                                                                                 1)
            temp.reverse()
            parent.ExpirationDate = r"/".join(temp)
            if str(parent.ExpirationDate) == "" or str(parent.ExpirationDate) == "None":
                parent.ExpirationDate = "Pending"
            temp = str(parent.ExpirationDateHeld).replace("T00:00:00", "").replace("00:00:00", "").replace("-",
                                                                                                           r"/").split(
                r"/", 1)
            temp.reverse()
            parent.ExpirationDateHeld = r"/".join(temp)
            parent.CSMOPermitNumber = str(CSMOPermitNumber)
            parent.PermitType = PermitType
            if parent.OriginalIssueDate == "" or str(parent.OriginalIssueDate) == "None":
                parent.OriginalIssueDate = "N/A"
            if str(parent.CSMOPermitNumber) == "" or str(parent.CSMOPermitNumber) == "None":
                parent.CSMOPermitNumber = "Pending"
            parent.FormerNPDESNumber = "N/A"
            parent.ReviewerPhoneNumber = ReviewerPhoneNumber
            parent.NewsPaper = str(NewspaperName)
            if FacilityDescription == "None":
                parent.MiningType = PermitDescription
            else:
                parent.MiningType = FacilityDescription
            parent.InformalConferenceDate = "N/A"
            parent.PermitRevisionDate = "N/A"
            parent.NPDESNumber = str(NPDESNumber)
            parent.FacilityQuad = str(QuadName)
            parent.FacilityEasting = str(PermitEasting)
            parent.FacilityNorthing = str(PermitNorthing)
            parent.AcresPermitted = str(PermitAcres)
            parent.FacilityLocation = str(PermitLocation)
            parent.FacilityCounty = str(PermitCountyName)
            parent.FacilityName = str(FacilityName)
            parent.OwnerPhoneNumber = str(OperatorPhone)
            parent.OwnerState = str(PermitteeState)
            parent.OwnerZip = str(PermitteeZip)
            parent.OwnerCity = str(PermitteeCity)
            parent.OperatorAddress = str(PermitteeAddress)
            parent.OperatorName = str(OperatorName)
            parent.OwnerName = str(PermitteeName)
            parent.PermitDescription = PermitDescription
            parent.AmbientWQDescription = ""
            parent.IndustEffCheck = False
            parent.PCBCheck = False
            parent.HazWasteCheck = False
            parent.FluidInjCheck = False
            parent.PubTreatCheck = False
            parent.AnimalFeedCheck = False
            #Worksheet Parameters Defined
            MineTypeList = []
            PrepPlantExists = "No"  #Query the facility type table, and if we have a prep plant, set this to yes
            UndergroundPrep = "No"
            sqlSearch = str(
                "select TblFaCode from OpPlan_Facilities where AppNo = '" + str(AppNumber) + "' and RevNo = " + str(
                    RevisionNumber))
            cursor.execute(sqlSearch)
            result = cursor.fetchall()
            for each in result:
                MineTypeList.append(each[0])
            if "CP" in MineTypeList:
                PrepPlantExists = "Yes"
                if "UE" in MineTypeList:
                    UndergroundPrep = "Yes"
            NearWaterIntake = "No"
            sqlSearch = str(
                "select EndangeredSpecies from FishWildlife where AppNo = '" + str(AppNumber) + "' and RevNo = " + str(
                    RevisionNumber))
            cursor.execute(sqlSearch)
            result = cursor.fetchone()
            if type(result) is not types.NoneType:
                if type(result[0]) is not types.NoneType:
                    if result[0] == "Y":
                        parent.SSPMRequirement = True
                        parent.SSPMRequirementText = "There is an identified species of concern within 5 miles of the permitted area."

            # Permit waivers/variances
            WaiverCodesList = []
            WaiverList = []
            sqlSearch = str(
                "select TblWvCode from GenInfo_Waivers where AppNo = '" + str(AppNumber) + "' and RevNo = " + str(
                    RevisionNumber))
            cursor.execute(sqlSearch)
            result = cursor.fetchall()
            for each in result:
                WaiverCodesList.append(each[0])
                sqlSearch = str(
                    "select CAST(TblWvDesc as varchar(8000)) as TblWvDesc  from WaiverVarianceTbl where TblWvCode = '" + str(
                        each[0]) + "'")
                cursor.execute(sqlSearch)
                waivers = cursor.fetchone()
                if type(waivers) is not types.NoneType:
                    WaiverList.append(str(waivers[0]))
                else:
                    WaiverList.append("None")
            if WaiverCodesList > 0:
                if "None" in WaiverList:
                    WaiverList.remove("None")
                if "none" in WaiverList:
                    WaiverList.remove("none")
                parent.PermitVariances = True
                WaiverCodesList = list(set(WaiverCodesList))
                if "None" in WaiverCodesList:
                    WaiverCodesList.remove("None")
                parent.PermitVariancesText = "This permit has applicable waiver variances. The permit standards with waivers and variances are as follows: "
                parent.PermitVariancesText += "\n"
                WaiverList = list(set(WaiverList))
                if "None" in WaiverList:
                    WaiverList.remove("None")
                if "none" in WaiverList:
                    WaiverList.remove("none")
                counter = 0
                while counter < len(WaiverList):
                    parent.PermitVariancesText += str(WaiverList[counter])
                    parent.PermitVariancesText += "\n"
                    counter += 1

            sqlSearch = str(
                "select PermitNo, PrPermitNo,ExpireDt,TblApCode,TblApDesc,Operation,ApName,ApAddr,ApCity,ApState,ApZip,Remining,RemAcres from GenInfo where AppNo = '" + str(
                    AppNumber) + "' and RevNo = " + str(RevisionNumber))
            cursor.execute(sqlSearch)
            result = cursor.fetchone()
            if str(result[11]).upper() == "Y":
                parent.ReminingCheckbox = True
                parent.ReminingConditionsText = "The permit is remining " + str(
                    result[12]) + " acres. Alternate effluent conditions for remining are applicable."
            sqlSearch = str(
                "select WiPSA from LandUse where AppNo = '" + str(AppNumber) + "' and RevNo = " + str(RevisionNumber))
            cursor.execute(sqlSearch)
            result = cursor.fetchone()
            if result[0] == "Y":
                NearWaterIntake = "Yes"
            NearCoast = "No"
            parent.PrepPlantExists = PrepPlantExists
            parent.NearWaterIntake = NearWaterIntake
            parent.UndergroundPrep = UndergroundPrep
            parent.NearCoast = NearCoast
            ########################################MPID INITIALIZATIONS#############################################
            WriteFileString('Creating MPID Tables')
            NPRepChem = []
            NPRepWET = []
            NPMPIDList = []
            NPActionList = []
            NPLocNoList = []
            NPFacLocList = []
            NPFreqList = []
            NPElevationList = []
            NPTblQuDescList = []
            NPNorthingList = []
            NPEastingList = []
            NPTblSrNameList = []
            NPTblSrCodeList = []
            NPWaterShedAcresList = []
            NPDisturbedAcresList = []
            NPNameList = []
            NPLister = []
            NPAcidList = []
            NPDrainCatList = []
            NPStatusList = []
            NPStatusNameList = []
            NPChangeList = []
            NPLimCodeList = []
            #Parameters for TMDL Module
            NPWSList = []  #TMDL Watershed code
            NPWSNameList = []  #Name of the TMDL Watershed
            NPWSFlowList = []  #Flow from TMDLWaterShed Table
            #Parameters for Tier Module
            NPTierDesList = []  #Tier Designation
            NPDistList = []  #303d or 305b disturbed type
            NPUseDescList = []  #Water use
            NPCauseName = []  #Impairment Cause
            NPImpairList = []  #Impairment List (or not)
            #NPDES MPID Parameter Limits List Initializations
            NPAgeList = []  #Age of MPID point
            NPFlowList = []  #Flow (GPM)
            NPTempList = []  #Temperature (Degrees Celsius)
            NPpHList = []  #pH (std)
            NPFEList = []  #Iron (mg/L)
            NPMNList = []  #Manganese (mg/L)
            NPSEList = []  #Selenium (ug/L)
            NPTSSList = []  #Total Suspended Solids (mg/L)
            NPTDSList = []  #Total Dissolved Solids (mg/L)
            NPCONList = []  #Conductivity (uS/cm)
            NPCLList = []  #Chlorides (mg/L)
            NPWETChronList = []  #WET Chronic
            NPWETAcuteList = []  #WET Acute
            NPSULFList = []  #Sulfates (mg/L)
            NPALList = []  #Aluminum (mg/L)
            NPMGList = []  #Magnesium (mg/L)
            NPACIDList = []  #Total Acidity (mg/L)
            NPALKList = []  #Total Alkalinity (mg/L)
            NPBiALKList = []  #Bicarbonate Alkalinity (mg/L)
            NPCarbALKList = []  #Carbonate Alkalinity (mg/L)
            NPHARDList = []  #Hardness (mg/L)
            NPZNList = []  #Zinc (ug/L)
            NPANList = []  #Antimony (ug/L)
            NPASList = []  #Arsenic (ug/L)
            NPBEList = []  #Beryllium (ug/L)
            NPCDList = []  #Cadmium (ug/L)
            NPCRList = []  #Chromium (ug/L)
            NPCUList = []  #Copper (ug/L)
            NPPBList = []  #Lead (ug/L)
            NPHGList = []  #Mercury (ug/L)
            NPNIList = []  #Nickel (ug/L)
            NPAGList = []  #Silver (ug/L)
            NPTHList = []  #Thallium (ug/L)
            NPBAList = []  #Barium (ug/L)
            NPBList = []  #Boron (ug/L)
            NPCOList = []  #Cobalt (ug/L)
            NPCNList = []  #Cyanide(ug/L)
            NPPhenolList = []  #Phenol (ug/L)
            NPNITRATEList = []  #Nitrates (mg/L)
            NPNITRITEList = []  #Nitrite (mg/L)
            NPDissOrgCarbonList = []  #Dissolved Organic Carbon (mg/L)
            NPSSList = []  #Settleable Solids (mg/L)
            NPPrecList = []
            NPLabList = []
            NPAmmoniaList = []
            NPBigList = []
            NPStressList = []
            StreamDictionary = {}
            StreamCodeDictionary = {}
            rrr = []

            sqlSearch = str("select MPIDNo,Action,LocNo,FacLoc,Frequency,Elevation,Northing,Easting,"
                            "TblSrName,TblSrCode,WaterShedAcres,DisturbedAcres,TblQuDesc,Status "
                            "from Hydro_PollutionDis "
                            "where AppNo = '" + str(AppNumber) + "' and RevNo = " + str(RevisionNumber))
            cursor.execute(sqlSearch)
            result = cursor.fetchall()
            for each in result:
                addflag = 0
                if type(each[0]) is not types.NoneType:
                    if str(each[0]) != "" and str(each[0]).upper() != "NONE" and str(each[1]).upper() != "A":
                        sqlSearch = str(
                            "select FsDsDeleted from DmlrFactSheets_NPDES where MpDsNo = '" + str(each[0]) + "'")
                        cursor2.execute(sqlSearch)
                        res = cursor2.fetchall()
                        if type(res) is not types.NoneType:
                            for eachrecord in res:
                                if type(eachrecord[0]) is not types.NoneType:
                                    if str(eachrecord[0]).upper() != "NONE":
                                        pass
                                else:
                                    addflag = 1
                        if addflag == 1:
                            rrr.append(each)
                        else:
                            rrr.append(each)
                    else:
                        rrr.append(each)
                else:
                    rrr.append(each)
            sdcounter = 2
            for each in rrr:
                #MPID Property Lists
                NPMPIDList.append(str(each[0]))
                if str(each[1]) == "None":
                    NPActionList.append("")
                else:
                    NPActionList.append(str(each[1]))
                NPLocNoList.append(str(each[2]))
                NPFacLocList.append(str(each[3]))
                NPFreqList.append(str(each[4]))
                NPElevationList.append(str(each[5]))
                NPTblQuDescList.append(str(each[12]))
                NPNorthingList.append(str(each[6]))
                NPEastingList.append(str(each[7]))
                NPTblSrNameList.append(str(each[8]))
                if str(each[8]) not in StreamDictionary:
                    StreamDictionary[str(each[8])] = str(each[9])
                    StreamCodeDictionary[str(each[9])] = str(each[8])
                if str(each[9]) not in StreamCodeDictionary:
                    StreamDictionary[str(each[8]) + "(" + str(sdcounter) + ")"] = str(each[9])
                    StreamCodeDictionary[str(each[9])] = str(each[8]) + "(" + str(sdcounter) + ")"
                    sdcounter += 1
                NPTblSrCodeList.append(str(each[9]))
                NPWaterShedAcresList.append(str(each[10]))
                NPDisturbedAcresList.append(str(each[11]))
                NPNameList.append(str(each[2]) + "-" + str(each[3]))
                NPLister.append(str(each[2]) + "-" + str(each[3]) + "," + str(each[7]) + "," + str(each[6]) + "," + " ")
                NPWSList.append("")
                NPWSNameList.append("No TMDL")
                NPWSFlowList.append("")
                NPTierDesList.append("Tier II")
                NPDistList.append("None")
                NPUseDescList.append("Not Listed")
                NPCauseName.append("Not Listed")
                NPImpairList.append("None")
                NPAgeList.append("New")
                NPAcidList.append("Acid")
                NPDrainCatList.append("1")
                NPStatusList.append(str(each[13]))
                NPStatusNameList.append("")
                NPRepWET.append("No")
                NPRepChem.append("No")
                NPChangeList.append("")
                NPLimCodeList.append("NA")
                #MPID Parameter Lists
                NPFlowList = ["GPM", "NL", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Estimate",
                              "NA", "NA", "Month", "NA", "NA"]  #Flow (GPM)
                NPTempList = ["Celsius", "NL", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab",
                              "NA", "NA", "NA", "NA", "NA"]  #Temperature (Degrees Celsius)
                NPpHList = ["Std", "NL", "NA", "NA", "NA", "NA", "6.0", "NA", "9.0", "NA", "2", "Month", "Grab", "NA",
                            "NA", "NA", "NA", "NA"]  #pH (std)
                NPFEList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "kg",
                            "NA", "Month", "NA", "NA"]  #Iron (mg/L)
                NPMNList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "kg",
                            "NA", "Month", "NA", "NA"]  #Manganese (mg/L)
                NPSEList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "kg",
                            "NA", "Month", "NA", "NA"]  #Selenium (ug/L)
                NPTSSList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "kg",
                             "NA", "Month", "NA", "NA"]  #Total Suspended Solids (mg/L)
                NPTDSList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "kg",
                             "NA", "Month", "NA", "NA"]  #Total Dissolved Solids (mg/L)
                NPCONList = ["uS/cm", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "NA",
                             "NA", "NA", "NA", "NA"]  #Conductivity (uS/cm)
                NPCLList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "kg",
                            "NA", "Month", "NA", "NA"]  #Chlorides (mg/L)
                NPWETChronList = ["TUc", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab",
                                  "NA", "NA", "NA", "NA", "NA"]  #WET Chronic
                NPWETAcuteList = ["TUa", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab",
                                  "NA", "NA", "NA", "NA", "NA"]  #WET Acute
                NPSULFList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "kg",
                              "NA", "Month", "NA", "NA"]  #Sulfates (mg/L)
                NPALList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "kg",
                            "NA", "Month", "NA", "NA"]  #Aluminum (mg/L)
                NPMGList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "kg",
                            "NA", "Month", "NA", "NA"]  #Magnesium (mg/L)
                NPACIDList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "kg",
                              "NA", "Month", "NA", "NA"]  #Total Acidity (mg/L)
                NPALKList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "kg",
                             "NA", "Month", "NA", "NA"]  #Total Alkalinity (mg/L)
                NPBiALKList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "kg",
                               "NA", "Month", "NA", "NA"]  #Bicarbonate Alkalinity (mg/L)
                NPCarbALKList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab",
                                 "kg", "NA", "Month", "NA", "NA"]  #Carbonate Alkalinity (mg/L)
                NPHARDList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "kg",
                              "NA", "Month", "NA", "NA"]  #Hardness (mg/L)
                NPZNList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "kg",
                            "NA", "Month", "NA", "NA"]  #Zinc (ug/L)
                NPANList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "kg",
                            "NA", "Month", "NA", "NA"]  #Antimony (ug/L)
                NPASList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "kg",
                            "NA", "Month", "NA", "NA"]  #Arsenic (ug/L)
                NPBEList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "kg",
                            "NA", "Month", "NA", "NA"]  #Beryllium (ug/L)
                NPCDList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "kg",
                            "NA", "Month", "NA", "NA"]  #Cadmium (ug/L)
                NPCRList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "kg",
                            "NA", "Month", "NA", "NA"]  #Chromium (ug/L)
                NPCUList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "kg",
                            "NA", "Month", "NA", "NA"]  #Copper (ug/L)
                NPPBList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "kg",
                            "NA", "Month", "NA", "NA"]  #Lead (ug/L)
                NPHGList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "kg",
                            "NA", "Month", "NA", "NA"]  #Mercury (ug/L)
                NPNIList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "kg",
                            "NA", "Month", "NA", "NA"]  #Nickel (ug/L)
                NPAGList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "kg",
                            "NA", "Month", "NA", "NA"]  #Silver (ug/L)
                NPTHList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "kg",
                            "NA", "Month", "NA", "NA"]  #Thallium (ug/L)
                NPBAList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "kg",
                            "NA", "Month", "NA", "NA"]  #Barium (ug/L)
                NPBList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "kg",
                           "NA", "Month", "NA", "NA"]  #Boron (ug/L)
                NPCOList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "kg",
                            "NA", "Month", "NA", "NA"]  #Cobalt (ug/L)
                NPCNList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "kg",
                            "NA", "Month", "NA", "NA"]  #Cyanide(ug/L)
                NPPhenolList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab",
                                "kg", "NA", "Month", "NA", "NA"]  #Phenol (ug/L)
                NPNITRATEList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab",
                                 "kg", "NA", "Month", "NA", "NA"]  #Nitrates (mg/L)
                NPNITRITEList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab",
                                 "kg", "NA", "Month", "NA", "NA"]  #Nitrite (mg/L)
                NPDissOrgCarbonList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month",
                                       "Grab", "kg", "NA", "Month", "NA", "NA"]  #Dissolved Organic Carbon (mg/L)
                NPSSList = ["mL/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "kg",
                            "NA", "Month", "NA", "NA"]  #Settleable Solids (mL/L)
                NPPrecList = ["In", "NL", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab", "NA",
                              "NA", "NA", "NA", "NA"]  #Precipitation
                NPAmmoniaList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "2", "Month", "Grab",
                                 "kg", "NA", "Month", "NA", "NA"]  #Ammonia
                NPDESParameterList = []
                NPDESParameterList.append(NPFlowList)
                NPDESParameterList.append(NPTempList)
                NPDESParameterList.append(NPpHList)
                NPDESParameterList.append(NPPrecList)
                NPDESParameterList.append(NPTSSList)
                NPDESParameterList.append(NPTDSList)
                NPDESParameterList.append(NPFEList)
                NPDESParameterList.append(NPMNList)
                NPDESParameterList.append(NPSEList)
                NPDESParameterList.append(NPSSList)
                NPDESParameterList.append(NPWETAcuteList)
                NPDESParameterList.append(NPWETChronList)
                NPDESParameterList.append(NPCONList)
                NPDESParameterList.append(NPCLList)
                NPDESParameterList.append(NPSULFList)
                NPDESParameterList.append(NPALList)
                NPDESParameterList.append(NPMGList)
                NPDESParameterList.append(NPACIDList)
                NPDESParameterList.append(NPALKList)
                NPDESParameterList.append(NPAmmoniaList)
                NPDESParameterList.append(NPBiALKList)
                NPDESParameterList.append(NPCarbALKList)
                NPDESParameterList.append(NPHARDList)
                NPDESParameterList.append(NPZNList)
                NPDESParameterList.append(NPANList)
                NPDESParameterList.append(NPASList)
                NPDESParameterList.append(NPBEList)
                NPDESParameterList.append(NPCDList)
                NPDESParameterList.append(NPCRList)
                NPDESParameterList.append(NPCUList)
                NPDESParameterList.append(NPPBList)
                NPDESParameterList.append(NPHGList)
                NPDESParameterList.append(NPNIList)
                NPDESParameterList.append(NPAGList)
                NPDESParameterList.append(NPTHList)
                NPDESParameterList.append(NPBAList)
                NPDESParameterList.append(NPBList)
                NPDESParameterList.append(NPCOList)
                NPDESParameterList.append(NPCNList)
                NPDESParameterList.append(NPPhenolList)
                NPDESParameterList.append(NPNITRATEList)
                NPDESParameterList.append(NPNITRITEList)
                NPDESParameterList.append(NPDissOrgCarbonList)
                NPBigList.append(NPDESParameterList)
            NPParamPlotList = []
            NPParamLoadPlotList = []
            for x in range(0, len(NPMPIDList)):
                NPParamPlotList.append([])
                NPParamLoadPlotList.append([])
                for y in range(0, len(NPBigList[x])):
                    NPParamPlotList[x].append([])
                    NPParamLoadPlotList[x].append([])
            #Data Dictionary Assignments
            WaterTransDict = {}
            LDTblDict = {}
            LabelDict = {}
            RevLabelDict = {}
            StressTranslator = {}
            StressTranslator['TSS'] = "Total Suspended Solids"
            StressTranslator['TDS'] = "Total Dissolved Solids"
            StressTranslator['MN'] = "Manganese"
            StressTranslator['CL'] = "Chloride"
            parent.StressTranslator = StressTranslator
            TechStandardsList = ["WtIron", "WtManganese", "WtSe", "WtPh", "WtFlow", "WtPrec", "WtTemp"]
            WETList = ["WtWETChron", "WtWETAcute"]
            SolidsList = ["WtTss", "WtTds", "WtSs"]
            LabelDict['Flow'] = "0"
            LabelDict['Temperature'] = "1"
            LabelDict['pH'] = "2"
            LabelDict['Precip'] = "3"
            LabelDict['TSS'] = "4"
            LabelDict['TDS'] = "5"
            LabelDict['Iron'] = "6"
            LabelDict['Manganese'] = "7"
            LabelDict['Selenium'] = "8"
            LabelDict['SS'] = "9"
            LabelDict['Acute WET'] = "10"
            LabelDict['Chron WET'] = "11"
            LabelDict['Conductivity'] = "12"
            LabelDict['Chloride'] = "13"
            LabelDict['Sulfates'] = "14"
            LabelDict['Aluminum'] = "15"
            LabelDict['Magnesium'] = "16"
            LabelDict['Acidity'] = "17"
            LabelDict['Alkalinity'] = "18"
            LabelDict['Ammonia'] = "19"
            LabelDict['Bicarbonate Alk'] = "20"
            LabelDict['Carbonate Alk'] = "21"
            LabelDict['Hardness'] = "22"
            LabelDict['Zinc'] = "23"
            LabelDict['Antimony'] = "24"
            LabelDict['Arsenic'] = "25"
            LabelDict['Beryllium'] = "26"
            LabelDict['Cadmium'] = "27"
            LabelDict['Chromium'] = "28"
            LabelDict['Copper'] = "29"
            LabelDict['Lead'] = "30"
            LabelDict['Mercury'] = "31"
            LabelDict['Nickel'] = "32"
            LabelDict['Silver'] = "33"
            LabelDict['Thallium'] = "34"
            LabelDict['Barium'] = "35"
            LabelDict['Boron'] = "36"
            LabelDict['Cobalt'] = "37"
            LabelDict['Cyanide'] = "38"
            LabelDict['Phenol'] = "39"
            LabelDict['Nitrates'] = "40"
            LabelDict['Nitrites'] = "41"
            LabelDict['Diss Org Carbon'] = "42"
            RevLabelDict['0'] = "Flow"
            RevLabelDict['1'] = "Temperature"
            RevLabelDict['2'] = "pH"
            RevLabelDict['3'] = "Precip"
            RevLabelDict['4'] = "TSS"
            RevLabelDict['5'] = "TDS"
            RevLabelDict['6'] = "Iron"
            RevLabelDict['7'] = "Manganese"
            RevLabelDict['8'] = "Selenium"
            RevLabelDict['9'] = "SS"
            RevLabelDict['10'] = "Acute WET"
            RevLabelDict['11'] = "Chron WET"
            RevLabelDict['12'] = "Conductivity"
            RevLabelDict['13'] = "Chloride"
            RevLabelDict['14'] = "Sulfates"
            RevLabelDict['15'] = "Aluminum"
            RevLabelDict['16'] = "Magnesium"
            RevLabelDict['17'] = "Acidity"
            RevLabelDict['18'] = "Alkalinity"
            RevLabelDict['19'] = "Ammonia"
            RevLabelDict['20'] = "Bicarbonate Alk"
            RevLabelDict['21'] = "Carbonate Alk"
            RevLabelDict['22'] = "Hardness"
            RevLabelDict['23'] = "Zinc"
            RevLabelDict['24'] = "Antimony"
            RevLabelDict['25'] = "Arsenic"
            RevLabelDict['26'] = "Beryllium"
            RevLabelDict['27'] = "Cadmium"
            RevLabelDict['28'] = "Chromium"
            RevLabelDict['29'] = "Copper"
            RevLabelDict['30'] = "Lead"
            RevLabelDict['31'] = "Mercury"
            RevLabelDict['32'] = "Nickel"
            RevLabelDict['33'] = "Silver"
            RevLabelDict['34'] = "Thallium"
            RevLabelDict['35'] = "Barium"
            RevLabelDict['36'] = "Boron"
            RevLabelDict['37'] = "Cobalt"
            RevLabelDict['38'] = "Cyanide"
            RevLabelDict['39'] = "Phenol"
            RevLabelDict['40'] = "Nitrates"
            RevLabelDict['41'] = "Nitrites"
            RevLabelDict['42'] = "Diss Org Carbon"
            LDTblDict['0'] = "FLOW"
            LDTblDict['1'] = "TEMP"
            LDTblDict['2'] = "PH"
            LDTblDict['3'] = "PREC"
            LDTblDict['4'] = "TSS"
            LDTblDict['5'] = "TDS"
            LDTblDict['6'] = "FE"
            LDTblDict['7'] = "MN"
            LDTblDict['8'] = "SE"
            LDTblDict['9'] = "SS"
            LDTblDict['10'] = "WETACUTE"
            LDTblDict['11'] = "WETCHRON"
            LDTblDict['12'] = "COND"
            LDTblDict['13'] = "CL"
            LDTblDict['14'] = "SULF"
            LDTblDict['15'] = "AL"
            LDTblDict['16'] = "MG"
            LDTblDict['17'] = "ACID"
            LDTblDict['18'] = "ALK"
            LDTblDict['19'] = "NH3"
            LDTblDict['20'] = "BIALK"
            LDTblDict['21'] = "CARBALK"
            LDTblDict['22'] = "HARD"
            LDTblDict['23'] = "ZN"
            LDTblDict['24'] = "AN"
            LDTblDict['25'] = "AS"
            LDTblDict['26'] = "BE"
            LDTblDict['27'] = "CD"
            LDTblDict['28'] = "CR"
            LDTblDict['29'] = "CU"
            LDTblDict['30'] = "PB"
            LDTblDict['31'] = "HG"
            LDTblDict['32'] = "NI"
            LDTblDict['33'] = "AG"
            LDTblDict['34'] = "TH"
            LDTblDict['35'] = "BA"
            LDTblDict['36'] = "B"
            LDTblDict['37'] = "CO"
            LDTblDict['38'] = "CN"
            LDTblDict['39'] = "PHEN"
            LDTblDict['40'] = "NITRATE"
            LDTblDict['41'] = "NITRITE"
            LDTblDict['42'] = "DORGC"
            RevLDTblDict = {}
            for dicentry in LDTblDict:
                RevLDTblDict[LDTblDict[dicentry]] = dicentry
            WaterTransDict['0'] = "WtFlow"
            WaterTransDict['1'] = "WtTemp"
            WaterTransDict['2'] = "WtPh"
            WaterTransDict['6'] = "WtIron"
            WaterTransDict['7'] = "WtManganese"
            WaterTransDict['8'] = "WtSe"
            WaterTransDict['4'] = "WtTss"
            WaterTransDict['5'] = "WtTds"
            WaterTransDict['12'] = "WtConMic"
            WaterTransDict['9'] = "WtSs"
            WaterTransDict['13'] = "WtChlor"
            WaterTransDict['11'] = "WtWETChron"  #None Current
            WaterTransDict['10'] = "WtWETAcute"  #None Current
            WaterTransDict['14'] = "WtSulf"
            WaterTransDict['15'] = "WtAl"
            WaterTransDict['16'] = "MG"  #None Current
            WaterTransDict['17'] = "WtAcid"
            WaterTransDict['18'] = "WtAlka"
            WaterTransDict['20'] = "BIALK"  #None Current
            WaterTransDict['21'] = "CARBALK"  #None Current
            WaterTransDict['22'] = "WtHard"
            WaterTransDict['23'] = "ZN"  #None Current
            WaterTransDict['24'] = "AN"  #None Current
            WaterTransDict['25'] = "WtAs"
            WaterTransDict['26'] = "BE"  #None Current
            WaterTransDict['27'] = "WtCd"
            WaterTransDict['28'] = "WtCr"
            WaterTransDict['29'] = "WtCu"
            WaterTransDict['30'] = "WtPb"
            WaterTransDict['31'] = "WtHg"
            WaterTransDict['32'] = "WtNi"
            WaterTransDict['33'] = "WtAg"
            WaterTransDict['34'] = "TH"  #None Current
            WaterTransDict['35'] = "WtBa"
            WaterTransDict['36'] = "WtB"
            WaterTransDict['37'] = "CO"  #None Current
            WaterTransDict['38'] = "CN"  #None Current
            WaterTransDict['39'] = "PHEN"  #None Current
            WaterTransDict['40'] = "WtNitrate"
            WaterTransDict['41'] = "WtNitrite"
            WaterTransDict['42'] = "DORGC"  #None Current
            WaterTransDict['3'] = "WtPrec"
            WaterTransDict['19'] = "WtAmmonia"
            parent.WaterTransDict = WaterTransDict
            parent.LabelDict = LabelDict
            parent.LDTblDict = LDTblDict
            parent.RevLabelDict = RevLabelDict
            parent.RevLDTblDict = RevLDTblDict
            OldLimCodes = ['21-05', '21-01', '21-06', '21-03', '30-05', '30-01', '30-06', '30-03']
            i = 0
            while i < len(NPMPIDList):
                NPTblSrNameList[i] = StreamCodeDictionary[NPTblSrCodeList[i]]
                i += 1
            i = 0
            while i < len(NPMPIDList):
                if str(NPMPIDList[i]) == "None":
                    sqlSearch = str("select MpNo from DmlrMpids where (MpCompId = '" + str(
                        NPLocNoList[i]) + "' or MpFacilLoc = '" + str(NPFacLocList[i]) + "') and (MPEasting = '" + str(
                        NPEastingList[i]) + "' or MPNorthing = '" + str(NPNorthingList[i]) + "')")
                    cursor2.execute(sqlSearch)
                    result = cursor2.fetchall()
                    if type(result) is not types.NoneType:
                        if len(result) == 1:
                            NPMPIDList[i] = result[0][0]
                i += 1
            for i in range(0, len(NPMPIDList)):
                if str(NPMPIDList[i]) != "None" and str(NPMPIDList[i]) != "":
                    tempEast = str(NPEastingList[i]).split(".")
                    tempNorth = str(NPNorthingList[i]).split(".")
                    if len(tempEast[0]) != 8 or len(tempNorth[0]) != 7:
                        sqlSearch = str(
                            "select MpEasting,MpNorthing from DmlrMpids where (MpNo = '" + str(NPMPIDList[i]) + "')")
                        cursor2.execute(sqlSearch)
                        result = cursor2.fetchone()
                        NPEastingList[i] = str(result[0])
                        NPNorthingList[i] = str(result[1])
            i = 0
            while i < len(NPMPIDList):
                if str(NPMPIDList[i]) == "None":
                    NPAgeList[i] = "New"
                    NPStatusList[i] = "NCP"
                    NPStatusNameList[i] = "NOT CONSTRUCTED-Proposed"
                else:
                    #get the limit code for each approved MPID
                    try:
                        sqlSearch = str("select TblLmCode from vw_DmlrMpids where MpNo = " + str(NPMPIDList[i]))
                        cursor2.execute(sqlSearch)
                        result = cursor2.fetchone()
                        limcode = str(result[0])
                        NPLimCodeList[i] = limcode
                        if limcode != '21-31' and limcode != '21-99':
                            sqlSearch = str(
                                "select TblLdCode,TblLmMin,TblLmAvg,TblLmMax,TblLmUnit from LimitTbl_Para where TblLmCode = '" + str(
                                    limcode) + "'")
                            cursor.execute(sqlSearch)
                            result = cursor.fetchall()
                            for lim in result:
                                molimflag = 0
                                minlimflag = 0
                                maxlimflag = 0
                                if str(lim[1]).upper() != "NONE":
                                    NPBigList[i][int(RevLDTblDict[lim[0]])][6] = str(float(lim[1]))
                                elif str(lim[1]).upper() == "NONE":
                                    minlimflag = 1
                                if str(lim[2]).upper() != "NONE":
                                    NPBigList[i][int(RevLDTblDict[lim[0]])][1] = str(float(lim[2]))
                                elif str(lim[2]).upper() == "NONE":
                                    molimflag = 1
                                if str(lim[3]).upper() != "NONE":
                                    NPBigList[i][int(RevLDTblDict[lim[0]])][8] = str(float(lim[3]))
                                elif str(lim[3]).upper() == "NONE":
                                    maxlimflag = 1
                                if minlimflag == 1 and molimflag == 1 and maxlimflag == 1:
                                    NPBigList[i][int(RevLDTblDict[lim[0]])][1] = 'NL'
                        elif limcode == '21-31':
                            sqlSearch = str(
                                "select TblLdCode,TblLmMin,TblLmAvg,TblLmMax,TblLmUnit from LimitTbl_Para where TblLmCode = '" + str(
                                    limcode) + "'")
                            cursor.execute(sqlSearch)
                            result = cursor.fetchall()
                            for lim in result:
                                if lim[0] != "FLOW":
                                    NPBigList[i][int(RevLDTblDict[lim[0]])][14] = "NL"
                    except:
                        pass
                    for j in range(0, len(NPMPIDList)):
                        if NPLimCodeList[j] in OldLimCodes:
                            NPAgeList[j] = "Old"
                        else:
                            NPAgeList[j] = "New"
                    sqlSearch = str("select TblLdCode from DmlrMpids_Parameters where MpNo = " + str(NPMPIDList[i]))
                    cursor2.execute(sqlSearch)
                    result = cursor2.fetchall()
                    x = 0
                    for each in result:
                        if "MN" in str(each[0]):
                            x = 1
                    if x != 1:
                        NPAcidList[i] = "Alkaline"
                    sqlSearch = str("select TblLmCode,TblMsCode from DmlrMpids where MpNo = " + str(NPMPIDList[i]))
                    cursor2.execute(sqlSearch)
                    result = cursor2.fetchone()
                    TblLmCodeVar = str(result[0])
                    NPStatusList[i] = str(result[1])
                    sqlSearch = str(
                        "select TblMsDesc from MpidStatusTbl where TblMsCode = '" + str(NPStatusList[i]) + "'")
                    cursor.execute(sqlSearch)
                    result = cursor.fetchone()
                    NPStatusNameList[i] = str(result[0])
                    sqlSearch = str("select TblLmCategory from LimitTbl where TblLmCode = '" + str(TblLmCodeVar) + "'")
                    cursor.execute(sqlSearch)
                    result = cursor.fetchone()
                    try:
                        NPDrainCatList[i] = str(result[0])
                    except:
                        NPDrainCatList[i] = str(1)
                i += 1
            parent.NPMPIDList = NPMPIDList
            parent.NPActionList = NPActionList
            parent.NPLocNoList = NPLocNoList
            parent.NPFacLocList = NPFacLocList
            parent.NPFreqList = NPFreqList
            parent.NPElevationList = NPElevationList
            parent.NPTblQuDescList = NPTblQuDescList
            parent.NPNorthingList = NPNorthingList
            parent.NPEastingList = NPEastingList
            parent.NPTblSrNameList = NPTblSrNameList
            parent.NPWaterShedAcresList = NPWaterShedAcresList
            parent.NPDisturbedAcresList = NPDisturbedAcresList
            parent.NPNameList = NPNameList
            parent.NPWSList = NPWSList
            parent.NPWSNameList = NPWSNameList
            parent.NPWSFlowList = NPWSFlowList
            parent.NPTblSrCodeList = NPTblSrCodeList
            parent.NPTierDesList = NPTierDesList
            parent.NPDistList = NPDistList
            parent.NPCauseName = NPCauseName
            parent.NPImpairList = NPImpairList
            parent.NPAgeList = NPAgeList
            parent.NPDrainCatList = NPDrainCatList
            parent.NPChangeList = NPChangeList
            parent.NPAcidList = NPAcidList
            parent.NPStatusList = NPStatusList
            parent.NPStatusNameList = NPStatusNameList
            parent.NPUseDescList = NPUseDescList
            parent.NPFlowList = NPFlowList
            parent.NPTempList = NPTempList
            parent.NPpHList = NPpHList
            parent.NPPrecList = NPPrecList
            parent.NPTSSList = NPTSSList
            parent.NPTDSList = NPTDSList
            parent.NPFEList = NPFEList
            parent.NPMNList = NPMNList
            parent.NPSEList = NPSEList
            parent.NPSSList = NPSSList
            parent.NPWETAcuteList = NPWETAcuteList
            parent.NPWETChronList = NPWETChronList
            parent.NPCONList = NPCONList
            parent.NPCLList = NPCLList
            parent.NPSULFList = NPSULFList
            parent.NPALList = NPALList
            parent.NPMGList = NPMGList
            parent.NPACIDList = NPACIDList
            parent.NPALKList = NPALKList
            parent.NPAmmoniaList = NPAmmoniaList
            parent.NPBiALKList = NPBiALKList
            parent.NPCarbALKList = NPCarbALKList
            parent.NPHARDList = NPHARDList
            parent.NPZNList = NPZNList
            parent.NPANList = NPANList
            parent.NPASList = NPASList
            parent.NPBEList = NPBEList
            parent.NPCDList = NPCDList
            parent.NPCRList = NPCRList
            parent.NPCUList = NPCUList
            parent.NPPBList = NPPBList
            parent.NPHGList = NPHGList
            parent.NPNIList = NPNIList
            parent.NPAGList = NPAGList
            parent.NPTHList = NPTHList
            parent.NPBAList = NPBAList
            parent.NPBList = NPBList
            parent.NPCOList = NPCOList
            parent.NPCNList = NPCNList
            parent.NPPhenolList = NPPhenolList
            parent.NPNITRATEList = NPNITRATEList
            parent.NPNITRITEList = NPNITRITEList
            parent.NPDissOrgCarbonList = NPDissOrgCarbonList
            parent.NPRepChem = NPRepChem
            parent.NPRepWET = NPRepWET
            parent.NPBigList = NPBigList
            parent.NPParamPlotList = NPParamPlotList
            parent.NPParamLoadPlotList = NPParamLoadPlotList
            parent.NPLimCodeList = NPLimCodeList
            ########Instream Initializations
            ISLabelDict = {}
            ISLDTblDict = {}
            RevISDict = {}
            ISWaterTransDict = {}
            RevISDict['0'] = "Flow"
            RevISDict['1'] = "Temperature"
            RevISDict['2'] = "pH"
            RevISDict['11'] = "Precip"
            RevISDict['3'] = "TSS"
            RevISDict['4'] = "TDS"
            RevISDict['5'] = "Iron"
            RevISDict['6'] = "Manganese"
            RevISDict['13'] = "Selenium"
            RevISDict['12'] = "SS"
            RevISDict['9'] = "Conductivity"
            RevISDict['14'] = "Chloride"
            RevISDict['10'] = "Sulfates"
            RevISDict['15'] = "Aluminum"
            RevISDict['16'] = "Magnesium"
            RevISDict['7'] = "Acidity"
            RevISDict['8'] = "Alkalinity"
            RevISDict['17'] = "Ammonia"
            RevISDict['18'] = "Bicarbonate Alk"
            RevISDict['19'] = "Carbonate Alk"
            RevISDict['20'] = "Hardness"
            RevISDict['21'] = "Zinc"
            RevISDict['22'] = "Antimony"
            RevISDict['23'] = "Arsenic"
            RevISDict['24'] = "Beryllium"
            RevISDict['25'] = "Cadmium"
            RevISDict['26'] = "Chromium"
            RevISDict['27'] = "Copper"
            RevISDict['28'] = "Lead"
            RevISDict['29'] = "Mercury"
            RevISDict['30'] = "Nickel"
            RevISDict['31'] = "Silver"
            RevISDict['32'] = "Thallium"
            RevISDict['33'] = "Barium"
            RevISDict['34'] = "Boron"
            RevISDict['35'] = "Cobalt"
            RevISDict['36'] = "Cyanide"
            RevISDict['37'] = "Phenol"
            RevISDict['38'] = "Nitrates"
            RevISDict['39'] = "Nitrites"
            RevISDict['40'] = "Diss Org Carbon"
            ISLabelDict['Flow'] = "0"
            ISLabelDict['Temperature'] = "1"
            ISLabelDict['pH'] = "2"
            ISLabelDict['Precip'] = "11"
            ISLabelDict['TSS'] = "3"
            ISLabelDict['TDS'] = "4"
            ISLabelDict['Iron'] = "5"
            ISLabelDict['Manganese'] = "6"
            ISLabelDict['Selenium'] = "13"
            ISLabelDict['SS'] = "12"
            ISLabelDict['Conductivity'] = "9"
            ISLabelDict['Chloride'] = "14"
            ISLabelDict['Sulfates'] = "10"
            ISLabelDict['Aluminum'] = "15"
            ISLabelDict['Magnesium'] = "16"
            ISLabelDict['Acidity'] = "7"
            ISLabelDict['Alkalinity'] = "8"
            ISLabelDict['Ammonia'] = "17"
            ISLabelDict['Bicarbonate Alk'] = "18"
            ISLabelDict['Carbonate Alk'] = "19"
            ISLabelDict['Hardness'] = "20"
            ISLabelDict['Zinc'] = "21"
            ISLabelDict['Antimony'] = "22"
            ISLabelDict['Arsenic'] = "23"
            ISLabelDict['Beryllium'] = "24"
            ISLabelDict['Cadmium'] = "25"
            ISLabelDict['Chromium'] = "26"
            ISLabelDict['Copper'] = "27"
            ISLabelDict['Lead'] = "28"
            ISLabelDict['Mercury'] = "29"
            ISLabelDict['Nickel'] = "30"
            ISLabelDict['Silver'] = "31"
            ISLabelDict['Thallium'] = "32"
            ISLabelDict['Barium'] = "33"
            ISLabelDict['Boron'] = "34"
            ISLabelDict['Cobalt'] = "35"
            ISLabelDict['Cyanide'] = "36"
            ISLabelDict['Phenol'] = "37"
            ISLabelDict['Nitrates'] = "38"
            ISLabelDict['Nitrites'] = "39"
            ISLabelDict['Diss Org Carbon'] = "40"
            ISLDTblDict['0'] = "FLOW"
            ISLDTblDict['1'] = "TEMP"
            ISLDTblDict['2'] = "PH"
            ISLDTblDict['3'] = "TSS"
            ISLDTblDict['4'] = "TDS"
            ISLDTblDict['5'] = "FE"
            ISLDTblDict['6'] = "MN"
            ISLDTblDict['7'] = "ACID"
            ISLDTblDict['8'] = "ALK"
            ISLDTblDict['9'] = "COND"
            ISLDTblDict['10'] = "SULF"
            ISLDTblDict['11'] = "PREC"
            ISLDTblDict['12'] = "SS"
            ISLDTblDict['13'] = "SE"
            ISLDTblDict['14'] = "CL"
            ISLDTblDict['15'] = "AL"
            ISLDTblDict['16'] = "MG"
            ISLDTblDict['17'] = "NH3"
            ISLDTblDict['18'] = "BIALK"
            ISLDTblDict['19'] = "CARBALK"
            ISLDTblDict['20'] = "HARD"
            ISLDTblDict['21'] = "ZN"
            ISLDTblDict['22'] = "AN"
            ISLDTblDict['23'] = "AS"
            ISLDTblDict['24'] = "BE"
            ISLDTblDict['25'] = "CD"
            ISLDTblDict['26'] = "CR"
            ISLDTblDict['27'] = "CU"
            ISLDTblDict['28'] = "PB"
            ISLDTblDict['29'] = "HG"
            ISLDTblDict['30'] = "NI"
            ISLDTblDict['31'] = "AG"
            ISLDTblDict['32'] = "TH"
            ISLDTblDict['33'] = "BA"
            ISLDTblDict['34'] = "B"
            ISLDTblDict['35'] = "CO"
            ISLDTblDict['36'] = "CN"
            ISLDTblDict['37'] = "PHEN"
            ISLDTblDict['38'] = "NITRATE"
            ISLDTblDict['39'] = "NITRITE"
            ISLDTblDict['40'] = "DORGC"
            ISWaterTransDict['0'] = "WtFlow"
            ISWaterTransDict['1'] = "WtTemp"
            ISWaterTransDict['2'] = "WtPh"
            ISWaterTransDict['3'] = "WtTss"
            ISWaterTransDict['4'] = "WtTds"
            ISWaterTransDict['5'] = "WtIron"
            ISWaterTransDict['6'] = "WtManganese"
            ISWaterTransDict['7'] = "WtAcid"
            ISWaterTransDict['8'] = "WtAlka"
            ISWaterTransDict['9'] = "WtConMic"
            ISWaterTransDict['10'] = "WtSulf"
            ISWaterTransDict['11'] = "WtPrec"
            ISWaterTransDict['12'] = "WtSs"
            ISWaterTransDict['13'] = "WtSe"
            ISWaterTransDict['14'] = "WtChlor"
            ISWaterTransDict['15'] = "WtAl"
            ISWaterTransDict['16'] = "MG"  #None Current
            ISWaterTransDict['17'] = "WtAmmonia"
            ISWaterTransDict['18'] = "BIALK"  #None Current
            ISWaterTransDict['19'] = "CARBALK"  #None Current
            ISWaterTransDict['20'] = "WtHard"
            ISWaterTransDict['21'] = "ZN"  #None Current
            ISWaterTransDict['22'] = "AN"  #None Current
            ISWaterTransDict['23'] = "WtAs"
            ISWaterTransDict['24'] = "BE"  #None Current
            ISWaterTransDict['25'] = "WtCd"
            ISWaterTransDict['26'] = "WtCr"
            ISWaterTransDict['27'] = "WtCu"
            ISWaterTransDict['28'] = "WtPb"
            ISWaterTransDict['29'] = "WtHg"
            ISWaterTransDict['30'] = "WtNi"
            ISWaterTransDict['31'] = "WtAg"
            ISWaterTransDict['32'] = "TH"  #None Current
            ISWaterTransDict['33'] = "WtBa"
            ISWaterTransDict['34'] = "WtB"
            ISWaterTransDict['35'] = "CO"  #None Current
            ISWaterTransDict['36'] = "CN"  #None Current
            ISWaterTransDict['37'] = "PHEN"  #None Current
            ISWaterTransDict['38'] = "WtNitrate"
            ISWaterTransDict['39'] = "WtNitrite"
            ISWaterTransDict['40'] = "DORGC"  #None Current            
            parent.ISWaterTransDict = ISWaterTransDict
            parent.ISLabelDict = ISLabelDict
            parent.ISLDTblDict = ISLDTblDict
            parent.RevISDict = RevISDict
            ISRepChem = []
            ISRepWET = []
            ISMPIDList = []
            ISActionList = []
            ISLocNoList = []
            ISFacLocList = []
            ISFreqList = []
            ISElevationList = []
            ISTblQuDescList = []
            ISNorthingList = []
            ISEastingList = []
            ISTblSrNameList = []
            ISTblSrCodeList = []
            ISWaterShedAcresList = []
            ISDisturbedAcresList = []
            ISNameList = []
            ISLister = []
            ISAcidList = []
            ISDrainCatList = []
            ISStatusList = []
            ISStatusNameList = []
            ISChangeList = []
            #Parameters for TMDL Module
            ISWSList = []  #TMDL Watershed code
            ISWSNameList = []  #Name of the TMDL Watershed
            ISWSFlowList = []  #Flow from TMDLWaterShed Table
            #Parameters for Tier Module
            ISTierDesList = []  #Tier Designation
            ISDistList = []  #303d or 305b disturbed type
            ISUseDescList = []  #Water use
            ISCauseName = []  #Impairment Cause
            ISImpairList = []  #Impairment List (or not)
            #NPDES MPID Parameter Limits List Initializations
            ISAgeList = []  #Age of MPID point
            ISFlowList = []  #Flow (GPM)
            ISTempList = []  #Temperature (Degrees Celsius)
            ISpHList = []  #pH (std)
            ISFEList = []  #Iron (mg/L)
            ISMNList = []  #Manganese (mg/L)
            ISSEList = []  #Selenium (ug/L)
            ISTSSList = []  #Total Suspended Solids (mg/L)
            ISTDSList = []  #Total Dissolved Solids (mg/L)
            ISCONList = []  #Conductivity (uS/cm)
            ISCLList = []  #Chlorides (mg/L)
            ISWETChronList = []  #WET Chronic
            ISWETAcuteList = []  #WET Acute
            ISSULFList = []  #Sulfates (mg/L)
            ISALList = []  #Aluminum (mg/L)
            ISMGList = []  #Magnesium (mg/L)
            ISACIDList = []  #Total Acidity (mg/L)
            ISALKList = []  #Total Alkalinity (mg/L)
            ISBiALKList = []  #Bicarbonate Alkalinity (mg/L)
            ISCarbALKList = []  #Carbonate Alkalinity (mg/L)
            ISHARDList = []  #Hardness (mg/L)
            ISZNList = []  #Zinc (ug/L)
            ISANList = []  #Antimony (ug/L)
            ISASList = []  #Arsenic (ug/L)
            ISBEList = []  #Beryllium (ug/L)
            ISCDList = []  #Cadmium (ug/L)
            ISCRList = []  #Chromium (ug/L)
            ISCUList = []  #Copper (ug/L)
            ISPBList = []  #Lead (ug/L)
            ISHGList = []  #Mercury (ug/L)
            ISNIList = []  #Nickel (ug/L)
            ISAGList = []  #Silver (ug/L)
            ISTHList = []  #Thallium (ug/L)
            ISBAList = []  #Barium (ug/L)
            ISBList = []  #Boron (ug/L)
            ISCOList = []  #Cobalt (ug/L)
            ISCNList = []  #Cyanide(ug/L)
            ISPhenolList = []  #Phenol (ug/L)
            ISNITRATEList = []  #Nitrates (mg/L)
            ISNITRITEList = []  #Nitrite (mg/L)
            ISDissOrgCarbonList = []  #Dissolved Organic Carbon (mg/L)
            ISSSList = []  #Settleable Solids (mg/L)
            ISPrecList = []
            ISLabList = []
            ISAmmoniaList = []
            ISBigList = []
            ISStressList = []
            ISDischargeType = []
            ISType = []
            ISTypeDescription = []
            ISTypeLabel = []
            ISChemRequired = []
            ISBioRequired = []
            ISSMCRARequired = []
            rrr = []
            sqlSearch = str("select MPIDNo,Action,LocNo,FacLoc,Frequency,Northing,Easting,TblSrName,"
                            "TblSrCode,TblQuDesc,Status,TblMdCode,TblMdDesc "
                            "from Hydro_SWMP where AppNo = '" + str(AppNumber) + "' and RevNo = " + str(RevisionNumber))
            cursor.execute(sqlSearch)
            result = cursor.fetchall()
            for each in result:
                addflag = 0
                if type(each[0]) is not types.NoneType:
                    if str(each[0]) != "" and str(each[0]).upper() != "NONE" and str(each[1]).upper() != "A":
                        sqlSearch = str(
                            "select FsIsDeleted from DmlrFactSheets_IS where MpIsNo = '" + str(each[0]) + "'")
                        cursor2.execute(sqlSearch)
                        res = cursor2.fetchall()
                        if type(res) is not types.NoneType:
                            for eachrecord in res:
                                if type(eachrecord[0]) is not types.NoneType:
                                    if str(eachrecord[0]).upper() != "NONE":
                                        pass
                                else:
                                    addflag = 1
                            if addflag == 1:
                                rrr.append(each)
                        else:
                            rrr.append(each)
                    else:
                        rrr.append(each)
                else:
                    rrr.append(each)
            sdcounter = 2
            for each in rrr:
                #MPID Property Lists
                ISMPIDList.append(str(each[0]))
                if str(each[1]) == "None":
                    ISActionList.append("")
                else:
                    ISActionList.append(str(each[1]))
                ISLocNoList.append(str(each[2]))
                ISFacLocList.append(str(each[3]))
                ISFreqList.append(str(each[4]))
                ISNorthingList.append(str(each[5]))
                ISEastingList.append(str(each[6]))
                ISTblSrNameList.append(str(each[7]))
                if str(each[7]) not in StreamDictionary:
                    StreamDictionary[str(each[7])] = str(each[8])
                    StreamCodeDictionary[str(each[8])] = str(each[7])
                if str(each[8]) not in StreamCodeDictionary:
                    StreamDictionary[str(each[7]) + "(" + str(sdcounter) + ")"] = str(each[8])
                    StreamCodeDictionary[str(each[8])] = str(each[7]) + "(" + str(sdcounter) + ")"
                    sdcounter += 1
                ISTblSrCodeList.append(str(each[8]))
                ISTblQuDescList.append(str(each[9]))
                ISType.append(str(each[11]))
                ISTypeDescription.append(str(each[12]))
                ISNameList.append(str(each[2]) + "-" + str(each[3]))
                ISWSList.append("")
                ISWSNameList.append("No TMDL")
                ISWSFlowList.append("")
                ISTierDesList.append("Tier II")
                ISDistList.append("None")
                ISUseDescList.append("Not Listed")
                ISCauseName.append("Not Listed")
                ISImpairList.append("None")
                ISAgeList.append("New")
                ISAcidList.append("Acidic")
                ISDrainCatList.append("1")
                ISStatusList.append(str(each[10]))
                ISStatusNameList.append("")
                ISRepWET.append("No")
                ISRepChem.append("No")
                ISWaterShedAcresList.append("Instream")
                ISDisturbedAcresList.append("Instream")
                ISDischargeType.append("Instream")
                ISTypeLabel.append("None Current")
                #MPID Parameter Lists
                ISFlowList = ["GPM", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Estimate", "No",
                              "Gallons", "Month", "NA"]  #Flow (GPM)
                ISTempList = ["Celsius", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "NA",
                              "NA", "NA"]  #Temperature (Degrees Celsius)
                ISpHList = ["Std", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "NA", "NA",
                            "NA"]  #pH (std)
                ISFEList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Iron (mg/L)
                ISMNList = ["mg/L", "5.0", "5.0", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Manganese (mg/L)
                ISSEList = ["ug/L", "20", "5.0", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Selenium (ug/L)
                ISTSSList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                             "Month", "NA"]  #Total Suspended Solids (mg/L)
                ISTDSList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                             "Month", "NA"]  #Total Dissolved Solids (mg/L)
                ISCONList = ["uS/cm", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "NA",
                             "NA", "NA"]  #Conductivity (uS/cm)
                ISCLList = ["mg/L", "860", "230", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Chlorides (mg/L)
                ISWETChronList = ["TUc", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "NA",
                                  "NA", "NA"]  #WET Chronic
                ISWETAcuteList = ["TUa", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "NA",
                                  "NA", "NA"]  #WET Acute
                ISSULFList = ["mg/L", "250", "NA", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                              "Month", "NA"]  #Sulfates (mg/L)
                ISALList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Aluminum (mg/L)
                ISMGList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Magnesium (mg/L)
                ISACIDList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                              "Month", "NA"]  #Total Acidity (mg/L)
                ISALKList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                             "Month", "NA"]  #Total Alkalinity (mg/L)
                ISBiALKList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                               "Month", "NA"]  #Bicarbonate Alkalinity (mg/L)
                ISCarbALKList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                                 "Month", "NA"]  #Carbonate Alkalinity (mg/L)
                ISHARDList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                              "Month", "NA"]  #Hardness (mg/L)
                ISZNList = ["ug/L", "120", "120", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Zinc (ug/L)
                ISANList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Antimony (ug/L)
                ISASList = ["ug/L", "340", "150", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Arsenic (ug/L)
                ISBEList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Beryllium (ug/L)
                ISCDList = ["ug/L", "3.9", "1.1", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Cadmium (ug/L)
                ISCRList = ["ug/L", "586", "85", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Chromium (ug/L)
                ISCUList = ["ug/L", "13", "9", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Copper (ug/L)
                ISPBList = ["ug/L", "120", "14", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Lead (ug/L)
                ISHGList = ["ug/L", "1.4", "0.77", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Mercury (ug/L)
                ISNIList = ["ug/L", "180", "20", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Nickel (ug/L)
                ISAGList = ["ug/L", "3.4", "NA", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Silver (ug/L)
                ISTHList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Thallium (ug/L)
                ISBAList = ["mg/L", "2", "2", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg", "Month",
                            "NA"]  #Barium (ug/L)
                ISBList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                           "Month", "NA"]  #Boron (ug/L)
                ISCOList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Cobalt (ug/L)
                ISCNList = ["ug/L", "22", "5.2", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Cyanide(ug/L)
                ISPhenolList = ["mg/L", "10", "10", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                                "Month", "NA"]  #Phenol (ug/L)
                ISNITRATEList = ["mg/L", "10", "10", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                                 "Month", "NA"]  #Nitrates (mg/L)
                ISNITRITEList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                                 "Month", "NA"]  #Nitrite (mg/L)
                ISDissOrgCarbonList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No",
                                       "kg", "Month", "NA"]  #Dissolved Organic Carbon (mg/L)
                ISSSList = ["mL/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "L",
                            "Month", "NA"]  #Settleable Solids (mg/L)
                ISPrecList = ["In", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "NA", "NA",
                              "NA"]  #Precipitation
                ISAmmoniaList = ["mg/L", "NA", "2.0", "NA", "NA", "NA", "NA", "NA", "3", "Quarter", "Grab", "No", "kg",
                                 "Month", "NA"]  #Ammonia
                ISParameterList = []
                ISParameterList.append(ISFlowList)
                ISParameterList.append(ISTempList)
                ISParameterList.append(ISpHList)
                ISParameterList.append(ISTSSList)
                ISParameterList.append(ISTDSList)
                ISParameterList.append(ISFEList)
                ISParameterList.append(ISMNList)
                ISParameterList.append(ISACIDList)
                ISParameterList.append(ISALKList)
                ISParameterList.append(ISCONList)
                ISParameterList.append(ISSULFList)
                ISParameterList.append(ISPrecList)
                ISParameterList.append(ISSSList)
                ISParameterList.append(ISSEList)
                ISParameterList.append(ISCLList)
                ISParameterList.append(ISALList)
                ISParameterList.append(ISMGList)
                ISParameterList.append(ISAmmoniaList)
                ISParameterList.append(ISBiALKList)
                ISParameterList.append(ISCarbALKList)
                ISParameterList.append(ISHARDList)
                ISParameterList.append(ISZNList)
                ISParameterList.append(ISANList)
                ISParameterList.append(ISASList)
                ISParameterList.append(ISBEList)
                ISParameterList.append(ISCDList)
                ISParameterList.append(ISCRList)
                ISParameterList.append(ISCUList)
                ISParameterList.append(ISPBList)
                ISParameterList.append(ISHGList)
                ISParameterList.append(ISNIList)
                ISParameterList.append(ISAGList)
                ISParameterList.append(ISTHList)
                ISParameterList.append(ISBAList)
                ISParameterList.append(ISBList)
                ISParameterList.append(ISCOList)
                ISParameterList.append(ISCNList)
                ISParameterList.append(ISPhenolList)
                ISParameterList.append(ISNITRATEList)
                ISParameterList.append(ISNITRITEList)
                ISParameterList.append(ISDissOrgCarbonList)
                ISBigList.append(ISParameterList)
                ISChangeList.append("")
            ISParamPlotList = []
            ISParamLoadPlotList = []
            for x in range(0, len(ISMPIDList)):
                ISParamPlotList.append([])
                ISParamLoadPlotList.append([])
                for y in range(0, len(ISBigList[x])):
                    ISParamPlotList[x].append([])
                    ISParamLoadPlotList[x].append([])
            i = 0
            while i < len(ISMPIDList):
                ISTblSrNameList[i] = StreamCodeDictionary[ISTblSrCodeList[i]]
                i += 1
            i = 0
            while i < len(ISMPIDList):
                if str(ISMPIDList[i]) == "None" or str(ISMPIDList[i]) == "":
                    try:
                        sqlSearch = str("select MpNo,TblMsCode from DmlrMpids where (MpCompId = '" + str(
                            ISLocNoList[i]) + "' or MpFacilLoc = '" + str(
                            ISFacLocList[i]) + "') and (MPEasting = '" + str(
                            ISEastingList[i]) + "' or MPNorthing = '" + str(ISNorthingList[i]) + "')")
                        cursor2.execute(sqlSearch)
                        result = cursor2.fetchall()
                        if type(result) is not types.NoneType:
                            if len(result) == 1:
                                ISMPIDList[i] = result[0][0]
                                ISStatusList[i] = result[0][1]
                            else:
                                sqlSearch = str("select MpNo,TblMsCode from DmlrMpids where TblMdCode = '" + str(
                                    ISType[i]) + "' and (MpCompId = '" + str(
                                    ISLocNoList[i]) + "' and MpFacilLoc = '" + str(
                                    ISFacLocList[i]) + "') and (MPEasting = '" + str(
                                    ISEastingList[i]) + "' and MPNorthing = '" + str(ISNorthingList[i]) + "')")
                                cursor2.execute(sqlSearch)
                                result = cursor2.fetchall()
                                if type(result) is not types.NoneType:
                                    if len(result) == 1:
                                        ISMPIDList[i] = result[0][0]
                                        ISStatusList[i] = result[0][1]
                                    else:
                                        sqlSearch = str(
                                            "select MpNo,TblMsCode from DmlrMpids where TblMdCode = '" + str(
                                                ISType[i]) + "' and (MPEasting = '" + str(
                                                ISEastingList[i]) + "' or MPNorthing = '" + str(
                                                ISNorthingList[i]) + "')")
                                        cursor2.execute(sqlSearch)
                                        result = cursor2.fetchall()
                                        if type(result) is not types.NoneType:
                                            if len(result) == 1:
                                                ISMPIDList[i] = result[0][0]
                                                ISStatusList[i] = result[0][1]
                                            else:
                                                sqlSearch = str(
                                                    "select MpNo,TblMsCode from DmlrMpids where (MpCompId = '" + str(
                                                        ISLocNoList[i]) + "' and MpFacilLoc = '" + str(
                                                        ISFacLocList[i]) + "') and (TblMdCode = '" + str(
                                                        ISType[i]) + "' and TblSrCode like '%" + str(
                                                        ISTblSrCodeList[i]) + "%')")
                                                cursor2.execute(sqlSearch)
                                                result = cursor2.fetchall()
                                                if type(result) is not types.NoneType:
                                                    if len(result) == 1:
                                                        ISMPIDList[i] = result[0][0]
                                                        ISStatusList[i] = result[0][1]
                                                    else:
                                                        for possISpt in result:
                                                            sqlSearch = str(
                                                                "select FsNo from DmlrFactSheets_IS where MpIsNo = '" + str(
                                                                    possISpt[0]) + "'")
                                                            cursor2.execute(sqlSearch)
                                                            result = cursor2.fetchone()
                                                            tfsno = result[0]
                                                            sqlSearch = str(
                                                                "select PeNo from DmlrFactSheets where FsNo = '" + str(
                                                                    tfsno) + "'")
                                                            cursor2.execute(sqlSearch)
                                                            result = cursor2.fetchone()
                                                            if str(result[0]) == str(CSMOPermitNumber):
                                                                ISMPIDList[i] = possISpt[0]
                                                                ISStatusList[i] = possISpt[1]
                                                                break;

                        else:
                            sqlSearch = str("select MpNo,TblMsCode from DmlrMpids where (MpCompId = '" + str(
                                ISLocNoList[i]) + "' and MpFacilLoc = '" + str(
                                ISFacLocList[i]) + "') and (TblMdCode = '" + str(
                                ISType[i]) + "' and TblSrCode like '%" + str(ISTblSrCodeList[i]) + "%')")
                            cursor2.execute(sqlSearch)
                            result = cursor2.fetchall()
                            if type(result) is not types.NoneType:
                                if len(result) == 1:
                                    ISMPIDList[i] = result[0][0]
                                    ISStatusList[i] = result[0][1]
                    except:
                        try:
                            sqlSearch = str("select MpNo,TblMsCode from DmlrMpids where (MpCompId = '" + str(
                                ISLocNoList[i]) + "' and MpFacilLoc = '" + str(
                                ISFacLocList[i]) + "') and (TblMdCode = '" + str(
                                ISType[i]) + "' and TblSrCode like '%" + str(ISTblSrCodeList[i]) + "%')")
                            cursor2.execute(sqlSearch)
                            result = cursor2.fetchall()
                            if type(result) is not types.NoneType:
                                if len(result) == 1:
                                    ISMPIDList[i] = result[0][0]
                                    ISStatusList[i] = result[0][1]
                                else:
                                    for possISpt in result:
                                        sqlSearch = str("select FsNo from DmlrFactSheets_IS where MpIsNo = '" + str(
                                            possISpt[0]) + "'")
                                        cursor2.execute(sqlSearch)
                                        result = cursor2.fetchone()
                                        tfsno = result[0]
                                        sqlSearch = str(
                                            "select PeNo from DmlrFactSheets where FsNo = '" + str(tfsno) + "'")
                                        cursor2.execute(sqlSearch)
                                        result = cursor2.fetchone()
                                        if str(result[0]) == str(CSMOPermitNumber):
                                            ISMPIDList[i] = possISpt[0]
                                            ISStatusList[i] = possISpt[1]
                                            break;
                        except:
                            pass
                i += 1
            for i in range(0, len(ISMPIDList)):
                if str(ISMPIDList[i]) != "None" and str(ISMPIDList[i]) != "":
                    tempEast = str(ISEastingList[i]).split(".")
                    tempNorth = str(ISNorthingList[i]).split(".")
                    if len(tempEast[0]) != 8 or len(tempNorth[0]) != 7:
                        sqlSearch = str(
                            "select MpEasting,MpNorthing from DmlrMpids where (MpNo = '" + str(ISMPIDList[i]) + "')")
                        cursor2.execute(sqlSearch)
                        result = cursor2.fetchone()
                        ISEastingList[i] = str(result[0])
                        ISNorthingList[i] = str(result[1])
            i = 0
            while i < len(ISMPIDList):
                if str(ISMPIDList[i]) == "":
                    ISMPIDList[i] = "None"
                if str(ISMPIDList[i]) == "None":
                    ISAgeList[i] = "New"
                    ISStatusList[i] = "NCP"
                    ISStatusNameList[i] = "NOT CONSTRUCTED-Proposed"
                else:
                    sqlSearch = str(
                        "select FsIsAdded from DmlrFactSheets_IS where MpIsNo = '" + str(ISMPIDList[i]) + "'")
                    cursor2.execute(sqlSearch)
                    result = cursor2.fetchone()
                    if type(result) is not types.NoneType:
                        if result[0].year < 1983:
                            ISAgeList[i] = "Old"
                        else:
                            ISAgeList[i] = "New"
                        if str(ISStatusList[i]) != "None":
                            sqlSearch = str(
                                "select TblMsDesc from MpidStatusTbl where TblMsCode = '" + str(ISStatusList[i]) + "'")
                            cursor.execute(sqlSearch)
                            result = cursor.fetchone()
                            ISStatusNameList[i] = str(result[0])
                        else:
                            ISStatusNameList[i] = "None"
                        sqlSearch = str("select TblLmCode from DmlrMpids where MpNo = " + str(ISMPIDList[i]))
                        cursor2.execute(sqlSearch)
                        result = cursor2.fetchone()
                        TblLmCodeVar = str(result[0])
                i += 1
            i = 0
            while i < len(ISMPIDList):
                if str(ISType[i]) == "None" or str(ISType[i]) is None or str(ISType[i]) == "" or str(
                        ISType[i]) == "Null":
                    ISTypeLabel[i] = "Baseline"
                    j = 0
                    while j < 11:
                        ISBigList[i][j][11] = "Yes"
                        j += 1
                elif str(ISType[i]).upper() == "BASEI" or str(ISType[i]).upper() == "SW":
                    ISTypeLabel[i] = "Baseline"
                    j = 0
                    while j < 11:
                        ISBigList[i][j][11] = "Yes"
                        j += 1
                elif str(ISType[i]).upper() == "BSIS":
                    ISTypeLabel[i] = "Bio and Chem"
                    j = 0
                    while j < len(ISBigList[i]):
                        if j != 12:
                            ISBigList[i][j][11] = "Yes"
                            ISBigList[i][j][9] = "Year"
                            ISBigList[i][j][8] = "2"
                        j += 1
                elif str(ISType[i]).upper() == "CHEM":
                    ISTypeLabel[i] = "Chemical"
                    j = 0
                    while j < len(ISBigList[i]):
                        if j != 12:
                            ISBigList[i][j][11] = "Yes"
                        j += 1
                elif str(ISType[i]).upper() == "FLOW":
                    ISTypeLabel[i] = "Flow Only"
                    ISBigList[i][0][11] = "Yes"
                elif str(ISType[i]).upper() == "ABS":
                    ISTypeLabel[i] = "Biological Only"
                    j = 0
                    while j < len(ISBigList[i]):
                        ISBigList[i][j][8] = "2"
                        ISBigList[i][j][9] = "Year"
                        j += 1
                i += 1
            parent.ISMPIDList = ISMPIDList
            parent.ISActionList = ISActionList
            parent.ISLocNoList = ISLocNoList
            parent.ISFacLocList = ISFacLocList
            parent.ISFreqList = ISFreqList
            parent.ISElevationList = ISElevationList
            parent.ISTblQuDescList = ISTblQuDescList
            parent.ISNorthingList = ISNorthingList
            parent.ISEastingList = ISEastingList
            parent.ISTblSrNameList = ISTblSrNameList
            parent.ISWaterShedAcresList = ISWaterShedAcresList
            parent.ISDisturbedAcresList = ISDisturbedAcresList
            parent.ISNameList = ISNameList
            parent.ISWSList = ISWSList
            parent.ISWSNameList = ISWSNameList
            parent.ISWSFlowList = ISWSFlowList
            parent.ISStressList = ISStressList
            parent.ISTblSrCodeList = ISTblSrCodeList
            parent.ISTierDesList = ISTierDesList
            parent.ISDistList = ISDistList
            parent.ISCauseName = ISCauseName
            parent.ISImpairList = ISImpairList
            parent.ISUseDescList = ISUseDescList
            parent.ISAgeList = ISAgeList
            parent.ISDrainCatList = ISDrainCatList
            parent.ISAcidList = ISAcidList
            parent.ISStatusList = ISStatusList
            parent.ISStatusNameList = ISStatusNameList
            parent.ISChangeList = ISChangeList
            parent.ISFlowList = ISFlowList
            parent.ISTempList = ISTempList
            parent.ISpHList = ISpHList
            parent.ISPrecList = ISPrecList
            parent.ISTSSList = ISTSSList
            parent.ISTDSList = ISTDSList
            parent.ISFEList = ISFEList
            parent.ISMNList = ISMNList
            parent.ISSEList = ISSEList
            parent.ISSSList = ISSSList
            parent.ISWETAcuteList = ISWETAcuteList
            parent.ISWETChronList = ISWETChronList
            parent.ISCONList = ISCONList
            parent.ISCLList = ISCLList
            parent.ISSULFList = ISSULFList
            parent.ISALList = ISALList
            parent.ISMGList = ISMGList
            parent.ISACIDList = ISACIDList
            parent.ISALKList = ISALKList
            parent.ISAmmoniaList = ISAmmoniaList
            parent.ISBiALKList = ISBiALKList
            parent.ISCarbALKList = ISCarbALKList
            parent.ISHARDList = ISHARDList
            parent.ISZNList = ISZNList
            parent.ISANList = ISANList
            parent.ISASList = ISASList
            parent.ISBEList = ISBEList
            parent.ISCDList = ISCDList
            parent.ISCRList = ISCRList
            parent.ISCUList = ISCUList
            parent.ISPBList = ISPBList
            parent.ISHGList = ISHGList
            parent.ISNIList = ISNIList
            parent.ISAGList = ISAGList
            parent.ISTHList = ISTHList
            parent.ISBAList = ISBAList
            parent.ISBList = ISBList
            parent.ISCOList = ISCOList
            parent.ISCNList = ISCNList
            parent.ISPhenolList = ISPhenolList
            parent.ISNITRATEList = ISNITRATEList
            parent.ISNITRITEList = ISNITRITEList
            parent.ISDissOrgCarbonList = ISDissOrgCarbonList
            parent.ISRepChem = ISRepChem
            parent.ISRepWET = ISRepWET
            parent.ISBigList = ISBigList
            parent.ISParamPlotList = ISParamPlotList
            parent.ISParamLoadPlotList = ISParamLoadPlotList
            parent.ISDischargeType = ISDischargeType
            parent.ISType = ISType
            parent.ISTypeDescription = ISTypeDescription
            parent.ISTypeLabel = ISTypeLabel
            ###################################Groundwater Table Assignments####################################
            GWLabelDict = {}
            GWLDTblDict = {}
            RevGWLabelDict = {}
            GWWaterTransDict = {}
            GWLabelDict['Flow'] = "0"
            GWLabelDict['Temperature'] = "1"
            GWLabelDict['pH'] = "2"
            GWLabelDict['Depth'] = "3"
            GWLabelDict['Hardness'] = "4"
            GWLabelDict['TSS'] = "5"
            GWLabelDict['TDS'] = "6"
            GWLabelDict['Sulfates'] = "7"
            GWLabelDict['Iron'] = "8"
            GWLabelDict['Acidity'] = "9"
            GWLabelDict['Alkalinity'] = "10"
            GWLabelDict['Manganese'] = "11"
            GWLabelDict['Chloride'] = "12"
            GWLabelDict['Conductivity'] = "13"
            GWLabelDict['Precip'] = "14"
            GWLabelDict['SS'] = "15"
            GWLabelDict['Selenium'] = "16"
            GWLabelDict['Aluminum'] = "17"
            GWLabelDict['Magnesium'] = "18"
            GWLabelDict['Ammonia'] = "19"
            GWLabelDict['Bicarbonate Alk'] = "20"
            GWLabelDict['Carbonate Alk'] = "21"
            GWLabelDict['Zinc'] = "22"
            GWLabelDict['Antimony'] = "23"
            GWLabelDict['Arsenic'] = "24"
            GWLabelDict['Beryllium'] = "25"
            GWLabelDict['Cadmium'] = "26"
            GWLabelDict['Chromium'] = "27"
            GWLabelDict['Copper'] = "28"
            GWLabelDict['Lead'] = "29"
            GWLabelDict['Mercury'] = "30"
            GWLabelDict['Nickel'] = "31"
            GWLabelDict['Silver'] = "32"
            GWLabelDict['Thallium'] = "33"
            GWLabelDict['Barium'] = "34"
            GWLabelDict['Boron'] = "35"
            GWLabelDict['Cobalt'] = "36"
            GWLabelDict['Cyanide'] = "37"
            GWLabelDict['Phenol'] = "38"
            GWLabelDict['Nitrates'] = "39"
            GWLabelDict['Nitrites'] = "40"
            GWLabelDict['Diss Org Carbon'] = "41"
            RevGWLabelDict['0'] = "Flow"
            RevGWLabelDict['1'] = "Temperature"
            RevGWLabelDict['2'] = "pH"
            RevGWLabelDict['3'] = "Depth"
            RevGWLabelDict['4'] = "Hardness"
            RevGWLabelDict['5'] = "TSS"
            RevGWLabelDict['6'] = "TDS"
            RevGWLabelDict['7'] = "Sulfates"
            RevGWLabelDict['8'] = "Iron"
            RevGWLabelDict['9'] = "Acidity"
            RevGWLabelDict['10'] = "Alkalinity"
            RevGWLabelDict['11'] = "Manganese"
            RevGWLabelDict['12'] = "Chloride"
            RevGWLabelDict['13'] = "Conductivity"
            RevGWLabelDict['14'] = "Precip"
            RevGWLabelDict['15'] = "SS"
            RevGWLabelDict['16'] = "Selenium"
            RevGWLabelDict['17'] = "Aluminum"
            RevGWLabelDict['18'] = "Magnesium"
            RevGWLabelDict['19'] = "Ammonia"
            RevGWLabelDict['20'] = "Bicarbonate Alk"
            RevGWLabelDict['21'] = "Carbonate Alk"
            RevGWLabelDict['22'] = "Zinc"
            RevGWLabelDict['23'] = "Antimony"
            RevGWLabelDict['24'] = "Arsenic"
            RevGWLabelDict['25'] = "Beryllium"
            RevGWLabelDict['26'] = "Cadmium"
            RevGWLabelDict['27'] = "Chromium"
            RevGWLabelDict['28'] = "Copper"
            RevGWLabelDict['29'] = "Lead"
            RevGWLabelDict['30'] = "Mercury"
            RevGWLabelDict['31'] = "Nickel"
            RevGWLabelDict['32'] = "Silver"
            RevGWLabelDict['33'] = "Thallium"
            RevGWLabelDict['34'] = "Barium"
            RevGWLabelDict['35'] = "Boron"
            RevGWLabelDict['36'] = "Cobalt"
            RevGWLabelDict['37'] = "Cyanide"
            RevGWLabelDict['38'] = "Phenol"
            RevGWLabelDict['39'] = "Nitrates"
            RevGWLabelDict['40'] = "Nitrites"
            RevGWLabelDict['41'] = "Diss Org Carbon"
            GWLDTblDict['0'] = "FLOW"
            GWLDTblDict['1'] = "TEMP"
            GWLDTblDict['2'] = "PH"
            GWLDTblDict['3'] = "DEPTH"
            GWLDTblDict['4'] = "HARD"
            GWLDTblDict['5'] = "TSS"
            GWLDTblDict['6'] = "TDS"
            GWLDTblDict['7'] = "SULF"
            GWLDTblDict['8'] = "FE"
            GWLDTblDict['9'] = "ACID"
            GWLDTblDict['10'] = "ALK"
            GWLDTblDict['11'] = "MN"
            GWLDTblDict['12'] = "CL"
            GWLDTblDict['13'] = "COND"
            GWLDTblDict['14'] = "PREC"
            GWLDTblDict['15'] = "SS"
            GWLDTblDict['16'] = "SE"
            GWLDTblDict['17'] = "AL"
            GWLDTblDict['18'] = "MG"
            GWLDTblDict['19'] = "NH3"
            GWLDTblDict['20'] = "BIALK"
            GWLDTblDict['21'] = "CARBALK"
            GWLDTblDict['22'] = "ZN"
            GWLDTblDict['23'] = "AN"
            GWLDTblDict['24'] = "AS"
            GWLDTblDict['25'] = "BE"
            GWLDTblDict['26'] = "CD"
            GWLDTblDict['27'] = "CR"
            GWLDTblDict['28'] = "CU"
            GWLDTblDict['29'] = "PB"
            GWLDTblDict['30'] = "HG"
            GWLDTblDict['31'] = "NI"
            GWLDTblDict['32'] = "AG"
            GWLDTblDict['33'] = "TH"
            GWLDTblDict['34'] = "BA"
            GWLDTblDict['35'] = "B"
            GWLDTblDict['36'] = "CO"
            GWLDTblDict['37'] = "CN"
            GWLDTblDict['38'] = "PHEN"
            GWLDTblDict['39'] = "NITRATE"
            GWLDTblDict['40'] = "NITRITE"
            GWLDTblDict['41'] = "DORGC"
            GWWaterTransDict['0'] = "WtFlow"
            GWWaterTransDict['1'] = "WtTemp"
            GWWaterTransDict['2'] = "WtPh"
            GWWaterTransDict['3'] = "WtDepth"
            GWWaterTransDict['4'] = "WtHard"
            GWWaterTransDict['5'] = "WtTss"
            GWWaterTransDict['6'] = "WtTds"
            GWWaterTransDict['7'] = "WtSulf"
            GWWaterTransDict['8'] = "WtIron"
            GWWaterTransDict['9'] = "WtAcid"
            GWWaterTransDict['10'] = "WtAlka"
            GWWaterTransDict['11'] = "WtManganese"
            GWWaterTransDict['12'] = "WtChlor"
            GWWaterTransDict['13'] = "WtConMic"
            GWWaterTransDict['14'] = "WtPrec"
            GWWaterTransDict['15'] = "WtSs"
            GWWaterTransDict['16'] = "WtSe"
            GWWaterTransDict['17'] = "WtAl"
            GWWaterTransDict['18'] = "MG"  #None Current
            GWWaterTransDict['19'] = "WtAmmonia"
            GWWaterTransDict['20'] = "BIALK"  #None Current
            GWWaterTransDict['21'] = "CARBALK"  #None Current            
            GWWaterTransDict['22'] = "ZN"  #None Current
            GWWaterTransDict['23'] = "AN"  #None Current
            GWWaterTransDict['24'] = "WtAs"
            GWWaterTransDict['25'] = "BE"  #None Current
            GWWaterTransDict['26'] = "WtCd"
            GWWaterTransDict['27'] = "WtCr"
            GWWaterTransDict['28'] = "WtCu"
            GWWaterTransDict['29'] = "WtPb"
            GWWaterTransDict['30'] = "WtHg"
            GWWaterTransDict['31'] = "WtNi"
            GWWaterTransDict['32'] = "WtAg"
            GWWaterTransDict['33'] = "TH"  #None Current
            GWWaterTransDict['34'] = "WtBa"
            GWWaterTransDict['35'] = "WtB"
            GWWaterTransDict['36'] = "CO"  #None Current
            GWWaterTransDict['37'] = "CN"  #None Current
            GWWaterTransDict['38'] = "PHEN"  #None Current
            GWWaterTransDict['39'] = "WtNitrate"
            GWWaterTransDict['40'] = "WtNitrite"
            GWWaterTransDict['41'] = "DORGC"  #None Current            
            parent.GWWaterTransDict = GWWaterTransDict
            parent.GWLabelDict = GWLabelDict
            parent.GWLDTblDict = GWLDTblDict
            parent.RevGWLabelDict = RevGWLabelDict
            GWMPIDList = []
            GWActionList = []
            GWLocNoList = []
            GWFacLocList = []
            GWFreqList = []
            GWElevationList = []
            GWTblQuDescList = []
            GWNorthingList = []
            GWEastingList = []
            GWNameList = []
            GWAcidList = []
            GWStatusList = []
            GWStatusNameList = []
            #Parameters for TMDL Module
            GWWSList = []  #TMDL Watershed code
            GWWSNameList = []  #Name of the TMDL Watershed
            #NPDES MPID Parameter Limits List Initializations
            GWAgeList = []  #Age of MPID point
            GWChangeList = []
            GWFlowList = []  #Flow (GPM)
            GWTempList = []
            GWDepthList = []
            GWpHList = []  #pH (std)
            GWFEList = []  #Iron (mg/L)
            GWMNList = []  #Manganese (mg/L)
            GWSEList = []  #Selenium (ug/L)
            GWTSSList = []  #Total Suspended Solids (mg/L)
            GWTDSList = []  #Total Dissolved Solids (mg/L)
            GWCONList = []  #Conductivity (uS/cm)
            GWCLList = []  #Chlorides (mg/L)
            GWSULFList = []  #Sulfates (mg/L)
            GWALList = []  #Aluminum (mg/L)
            GWMGList = []  #Magnesium (mg/L)
            GWACIDList = []  #Total Acidity (mg/L)
            GWALKList = []  #Total Alkalinity (mg/L)
            GWBiALKList = []  #Bicarbonate Alkalinity (mg/L)
            GWCarbALKList = []  #Carbonate Alkalinity (mg/L)
            GWHARDList = []  #Hardness (mg/L)
            GWZNList = []  #Zinc (ug/L)
            GWANList = []  #Antimony (ug/L)
            GWASList = []  #Arsenic (ug/L)
            GWBEList = []  #Beryllium (ug/L)
            GWCDList = []  #Cadmium (ug/L)
            GWCRList = []  #Chromium (ug/L)
            GWCUList = []  #Copper (ug/L)
            GWPBList = []  #Lead (ug/L)
            GWHGList = []  #Mercury (ug/L)
            GWNIList = []  #Nickel (ug/L)
            GWAGList = []  #Silver (ug/L)
            GWTHList = []  #Thallium (ug/L)
            GWBAList = []  #Barium (ug/L)
            GWBList = []  #Boron (ug/L)
            GWCOList = []  #Cobalt (ug/L)
            GWCNList = []  #Cyanide(ug/L)
            GWPhenolList = []  #Phenol (ug/L)
            GWNITRATEList = []  #Nitrates (mg/L)
            GWNITRITEList = []  #Nitrite (mg/L)
            GWDissOrgCarbonList = []  #Dissolved Organic Carbon (mg/L)
            GWSSList = []  #Settleable Solids (mg/L)
            GWPrecList = []
            GWLabList = []
            GWAmmoniaList = []
            GWBigList = []
            GWStressList = []
            GWType = []
            rrr = []
            sqlSearch = str(
                "select MPIDNo,Action,LocNo,FacLoc,Frequency,Northing,Easting,Elevation,TblQuDesc,Status,TblMdDesc from Hydro_GWMP where AppNo = '" + str(
                    AppNumber) + "' and RevNo = " + str(RevisionNumber))
            cursor.execute(sqlSearch)
            result = cursor.fetchall()
            for each in result:
                addflag = 0
                if type(each[0]) is not types.NoneType:
                    if str(each[0]) != "" and str(each[0]).upper() != "NONE" and str(each[1]).upper() != "A":
                        sqlSearch = str(
                            "select FsGwDeleted from DmlrFactSheets_GW where MpGwNo = '" + str(each[0]) + "'")
                        cursor2.execute(sqlSearch)
                        res = cursor2.fetchall()
                        if type(res) is not types.NoneType:
                            for eachrecord in res:
                                if type(eachrecord[0]) is not types.NoneType:
                                    if str(eachrecord[0]).upper() != "NONE":
                                        pass
                                else:
                                    addflag = 1
                            if addflag == 1:
                                rrr.append(each)
                        else:
                            rrr.append(each)
                    else:
                        rrr.append(each)
                else:
                    rrr.append(each)
            for each in rrr:
                #MPID Property Lists
                GWMPIDList.append(str(each[0]))
                if str(each[1]) == "None":
                    GWActionList.append("")
                else:
                    GWActionList.append(str(each[1]))
                GWLocNoList.append(str(each[2]))
                GWFacLocList.append(str(each[3]))
                GWNameList.append(str(each[2]) + "-" + str(each[3]))
                GWFreqList.append(str(each[4]))
                GWNorthingList.append(str(each[5]))
                GWEastingList.append(str(each[6]))
                GWElevationList.append(str(each[7]))
                GWTblQuDescList.append(str(each[8]))
                GWStatusList.append(str(each[9]))
                GWStatusNameList.append("")
                GWType.append(str(each[10]).title())
                GWWSList.append("")
                GWWSNameList.append("No TMDL")
                GWAgeList.append("New")
                GWAcidList.append("Acidic")
                #MPID Parameter Lists
                GWFlowList = ["GPM", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Estimate", "No",
                              "Gallons", "Month", "NA"]  #Flow (GPM)
                GWTempList = ["Celsius", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "NA",
                              "NA", "NA"]  #Temp (GPM)
                GWDepthList = ["Feet", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "NA",
                               "NA", "NA"]  #Temperature (Degrees Celsius)
                GWpHList = ["Std", "6.0-9.0", "6.0-9.0", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No",
                            "NA", "NA", "NA"]  #pH (std)
                GWFEList = ["mg/L", "10.0", "0.3", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Iron (mg/L)
                GWMNList = ["mg/L", "5.0", "1.0", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Manganese (mg/L)
                GWSEList = ["ug/L", "10.0", "10.0", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Selenium (ug/L)
                GWTSSList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                             "Month", "NA"]  #Total Suspended Solids (mg/L)
                GWTDSList = ["mg/L", "500", "500", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                             "Month", "NA"]  #Total Dissolved Solids (mg/L)
                GWCONList = ["uS/cm", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "NA",
                             "NA", "NA"]  #Conductivity (uS/cm)
                GWCLList = ["mg/L", "25", "25", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Chlorides (mg/L)
                GWSULFList = ["mg/L", "150", "100", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                              "Month", "NA"]  #Sulfates (mg/L)
                GWALList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Aluminum (mg/L)
                GWMGList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Magnesium (mg/L)
                GWACIDList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                              "Month", "NA"]  #Total Acidity (mg/L)
                GWALKList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                             "Month", "NA"]  #Total Alkalinity (mg/L)
                GWBiALKList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                               "Month", "NA"]  #Bicarbonate Alkalinity (mg/L)
                GWCarbALKList = ["mg/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                                 "Month", "NA"]  #Carbonate Alkalinity (mg/L)
                GWHARDList = ["mg/L", "300", "180", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                              "Month", "NA"]  #Hardness (mg/L)
                GWZNList = ["ug/L", "50.0", "50.0", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Zinc (ug/L)
                GWANList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Antimony (ug/L)
                GWASList = ["ug/L", "50.0", "50.0", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Arsenic (ug/L)
                GWBEList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Beryllium (ug/L)
                GWCDList = ["ug/L", "0.4", "0.4", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Cadmium (ug/L)
                GWCRList = ["ug/L", "50.0", "50.0", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Chromium (ug/L)
                GWCUList = ["mg/L", "1.0", "1.0", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Copper (ug/L)
                GWPBList = ["ug/L", "50.0", "50.0", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Lead (ug/L)
                GWHGList = ["ug/L", "0.05", "0.05", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Mercury (ug/L)
                GWNIList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Nickel (ug/L)
                GWAGList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Silver (ug/L)
                GWTHList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Thallium (ug/L)
                GWBAList = ["mg/L", "1.0", "1.0", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Barium (ug/L)
                GWBList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                           "Month", "NA"]  #Boron (ug/L)
                GWCOList = ["ug/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Cobalt (ug/L)
                GWCNList = ["ug/L", "5.0", "5.0", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                            "Month", "NA"]  #Cyanide(ug/L)
                GWPhenolList = ["ug/L", "1.0", "1.0", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                                "Month", "NA"]  #Phenol (ug/L)
                GWNITRATEList = ["mg/L", "5.0", "5.0", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "kg",
                                 "Month", "NA"]  #Nitrates (mg/L)
                GWNITRITEList = ["mg/L", "0.025", "0.025", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No",
                                 "kg", "Month", "NA"]  #Nitrite (mg/L)
                GWDissOrgCarbonList = ["mg/L", "10.0", "10.0", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab",
                                       "No", "kg", "Month", "NA"]  #Dissolved Organic Carbon (mg/L)
                GWSSList = ["mL/L", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "L",
                            "Month", "NA"]  #Settleable Solids (mg/L)
                GWPrecList = ["In", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No", "NA", "NA",
                              "NA"]  #Precipitation
                GWAmmoniaList = ["mg/L", "0.025", "0.025", "NA", "NA", "NA", "NA", "NA", "1", "Quarter", "Grab", "No",
                                 "kg", "Month", "NA"]  #Ammonia
                GWParameterList = []
                GWParameterList.append(GWFlowList)
                GWParameterList.append(GWTempList)
                GWParameterList.append(GWpHList)
                GWParameterList.append(GWDepthList)
                GWParameterList.append(GWHARDList)
                GWParameterList.append(GWTSSList)
                GWParameterList.append(GWTDSList)
                GWParameterList.append(GWSULFList)
                GWParameterList.append(GWFEList)
                GWParameterList.append(GWACIDList)
                GWParameterList.append(GWALKList)
                GWParameterList.append(GWMNList)
                GWParameterList.append(GWCLList)
                GWParameterList.append(GWCONList)
                GWParameterList.append(GWPrecList)
                GWParameterList.append(GWSSList)
                GWParameterList.append(GWSEList)
                GWParameterList.append(GWALList)
                GWParameterList.append(GWMGList)
                GWParameterList.append(GWAmmoniaList)
                GWParameterList.append(GWBiALKList)
                GWParameterList.append(GWCarbALKList)
                GWParameterList.append(GWZNList)
                GWParameterList.append(GWANList)
                GWParameterList.append(GWASList)
                GWParameterList.append(GWBEList)
                GWParameterList.append(GWCDList)
                GWParameterList.append(GWCRList)
                GWParameterList.append(GWCUList)
                GWParameterList.append(GWPBList)
                GWParameterList.append(GWHGList)
                GWParameterList.append(GWNIList)
                GWParameterList.append(GWAGList)
                GWParameterList.append(GWTHList)
                GWParameterList.append(GWBAList)
                GWParameterList.append(GWBList)
                GWParameterList.append(GWCOList)
                GWParameterList.append(GWCNList)
                GWParameterList.append(GWPhenolList)
                GWParameterList.append(GWNITRATEList)
                GWParameterList.append(GWNITRITEList)
                GWParameterList.append(GWDissOrgCarbonList)
                GWBigList.append(GWParameterList)
                GWChangeList.append("")
            GWParamPlotList = []
            GWParamLoadPlotList = []
            for x in range(0, len(GWMPIDList)):
                GWParamPlotList.append([])
                GWParamLoadPlotList.append([])
                for y in range(0, len(GWBigList[x])):
                    GWParamPlotList[x].append([])
                    GWParamLoadPlotList[x].append([])
            i = 0
            while i < len(GWMPIDList):
                if str(GWMPIDList[i]) == "None" or str(GWMPIDList[i]) == "":
                    sqlSearch = str("select MpNo,TblMsCode from DmlrMpids where (MpCompId = '" + str(
                        GWLocNoList[i]) + "' or MpFacilLoc = '" + str(GWFacLocList[i]) + "') and (MPEasting = '" + str(
                        GWEastingList[i]) + "' or MPNorthing = '" + str(GWNorthingList[i]) + "')")
                    cursor2.execute(sqlSearch)
                    result = cursor2.fetchall()
                    if type(result) is not types.NoneType:
                        if len(result) == 1:
                            GWMPIDList[i] = result[0][0]
                            GWStatusList[i] = result[0][1]
                i += 1
            for i in range(0, len(GWMPIDList)):
                if str(GWMPIDList[i]) != "None" and str(GWMPIDList[i]) != "":
                    tempEast = str(GWEastingList[i]).split(".")
                    tempNorth = str(GWNorthingList[i]).split(".")
                    if len(tempEast[0]) != 8 or len(tempNorth[0]) != 7:
                        sqlSearch = str(
                            "select MpEasting,MpNorthing from DmlrMpids where (MpNo = '" + str(GWMPIDList[i]) + "')")
                        cursor2.execute(sqlSearch)
                        result = cursor2.fetchone()
                        GWEastingList[i] = str(result[0])
                        GWNorthingList[i] = str(result[1])
            i = 0
            while i < len(GWMPIDList):
                if str(GWStatusList[i]).upper() == "NONE" or str(GWStatusList[i]) == "":
                    sqlSearch = str("select TblMsCode from DmlrMpids where MpNo = '" + str(GWMPIDList[i]) + "'")
                    cursor2.execute(sqlSearch)
                    result = cursor2.fetchall()
                    if type(result) is not types.NoneType:
                        if len(result) == 1:
                            GWStatusList[i] = result[0][0]
                i += 1
            i = 0
            while i < len(GWMPIDList):
                if str(GWMPIDList[i]) == "None":
                    GWAgeList[i] = "New"
                    GWStatusList[i] = "NCP"
                    GWStatusNameList[i] = "NOT CONSTRUCTED-Proposed"
                else:
                    sqlSearch = str(
                        "select TblMsDesc from MpidStatusTbl where TblMsCode = '" + str(GWStatusList[i]) + "'")
                    cursor.execute(sqlSearch)
                    result = cursor.fetchone()
                    GWStatusNameList[i] = str(result[0])
                i += 1
            parent.GWMPIDList = GWMPIDList
            parent.GWActionList = GWActionList
            parent.GWLocNoList = GWLocNoList
            parent.GWFacLocList = GWFacLocList
            parent.GWFreqList = GWFreqList
            parent.GWElevationList = GWElevationList
            parent.GWTblQuDescList = GWTblQuDescList
            parent.GWNorthingList = GWNorthingList
            parent.GWEastingList = GWEastingList
            parent.GWNameList = GWNameList
            parent.GWAcidList = GWAcidList
            parent.GWStatusList = GWStatusList
            parent.GWStatusNameList = GWStatusNameList
            parent.GWWSList = GWWSList
            parent.GWWSNameList = GWWSNameList
            parent.GWAgeList = GWAgeList
            parent.GWChangeList = GWChangeList
            parent.GWFlowList = GWFlowList
            parent.GWTempList = GWTempList
            parent.GWDepthList = GWDepthList
            parent.GWpHList = GWpHList
            parent.GWFEList = GWFEList
            parent.GWMNList = GWMNList
            parent.GWSEList = GWSEList
            parent.GWTSSList = GWTSSList
            parent.GWTDSList = GWTDSList
            parent.GWCONList = GWCONList
            parent.GWCLList = GWCLList
            parent.GWSULFList = GWSULFList
            parent.GWALList = GWALList
            parent.GWMGList = GWMGList
            parent.GWACIDList = GWACIDList
            parent.GWALKList = GWALKList
            parent.GWBiALKList = GWBiALKList
            parent.GWCarbALKList = GWCarbALKList
            parent.GWHARDList = GWHARDList
            parent.GWZNList = GWZNList
            parent.GWANList = GWANList
            parent.GWASList = GWASList
            parent.GWBEList = GWBEList
            parent.GWCDList = GWCDList
            parent.GWCRList = GWCRList
            parent.GWCUList = GWCUList
            parent.GWPBList = GWPBList
            parent.GWHGList = GWHGList
            parent.GWNIList = GWNIList
            parent.GWAGList = GWAGList
            parent.GWTHList = GWTHList
            parent.GWBAList = GWBAList
            parent.GWBList = GWBList
            parent.GWCOList = GWCOList
            parent.GWCNList = GWCNList
            parent.GWPhenolList = GWPhenolList
            parent.GWNITRATEList = GWNITRATEList
            parent.GWNITRITEList = GWNITRITEList
            parent.GWDissOrgCarbonList = GWDissOrgCarbonList
            parent.GWSSList = GWSSList
            parent.GWPrecList = GWPrecList
            parent.GWLabList = GWLabList
            parent.GWAmmoniaList = GWAmmoniaList
            parent.GWBigList = GWBigList
            parent.GWParamPlotList = GWParamPlotList
            parent.GWParamLoadPlotList = GWParamLoadPlotList
            parent.GWStressList = GWStressList
            parent.GWType = GWType
            #####################################Field List##################################################
            #Get the fields from watertrans into a list
            WaterFieldList = []
            sqlSearch = str("select column_name from information_schema.columns where table_name = 'DmlrWatertrans'")
            cursor2.execute(sqlSearch)
            result = cursor2.fetchall()
            for each in result:
                WaterFieldList.append(each[0])
            parent.WaterFieldList = WaterFieldList
            parent.StreamDictionary = StreamDictionary
            parent.StreamCodeDictionary = StreamCodeDictionary
    else:
        print "else"


def GetSpatialData():  # Replace this with tmdl logic
    #####################################Field List##################################################
    WriteFileString('Gathering Spatial Server Data')
    gdalAssignFlag = 0
    ##            for each in os.environ:
    ##                if each == 'GDAL_DRIVER_PATH':
    ##                    gdalAssignFlag = 1
    ##            if gdalAssignFlag == 0:

    # Still need these
    APermitGeometries = []
    APermitPeNoField = []
    TMDLGeometries = []
    TMDLWSCodeField = []
    TMDLWSNameField = []
    TMDLWSOBIDField = []
    try:
        from osgeo import gdal
        from osgeo import ogr
    except:
        print 'failed import'
    try:
        tmdllyr = ShapeLogic.GetLayer('TmdlWatersheds')
        for j in range(0, tmdllyr.GetFeatureCount()):
            t = tmdllyr.GetNextFeature()
            TMDLGeometries.append(t.GetGeometryRef().ExportToWkt())
            TMDLWSCodeField.append(t.items()['TWsCode'])
            TMDLWSNameField.append(t.items()['TWsDesc'])
            TMDLWSOBIDField.append('')
    except:
        print 'failed getting tmdl cursor'
    try:
        pelyr = ShapeLogic.GetLayer('PermitBoundaries')
        for j in range(0, pelyr.GetFeatureCount()):
            p = pelyr.GetNextFeature()
            APermitGeometries.append(p.GetGeometryRef().ExportToWkt())
            APermitPeNoField.append(p.items()['Permit'])
    except:
        print 'failed getting permit cursor'
    return TMDLGeometries, TMDLWSCodeField, TMDLWSNameField, TMDLWSOBIDField, APermitGeometries, APermitPeNoField


def MARILYN(parent, AppNumber, mpHistoryPermitList, mpHistoryAppList, mpHistoryNPDESList, mpHistoryISList,
            mpHistoryGWList, mpHistoryRGList,
            mpHistoryNPDESComments, mpHistoryISComments, mpHistoryGWComments, mpHistoryRGComments, mpSharedHistoryDict,
            mpPermitExists):
    import types
    import datetime
    from operator import itemgetter

    WriteFileString('Tracing Historical Permit Data')
    swdatadict = {}
    swdatadict["BSIS"] = "biological and chemical"
    swdatadict["ABS"] = "biological"
    swdatadict["CHEM"] = "chemical"
    swdatadict["BASEI"] = "baseline"
    swdatadict["FLOW"] = "flow only"
    swdatadict["SW"] = "surface water"
    swdatadict["INV"] = "amd inventory"
    swdatadict["MD"] = "Mine Discharge"
    swdatadict["NP"] = "NPDES point"  # Hack to fix a problem in AppNo 1008118 where a NPDES point was added as an instream point
                                      # A better fix needs to be found and this should be removed
    gwdatadict = {}
    gwdatadict["LY"] = "Lysimeter"
    gwdatadict["MD"] = "Mine Discharge"
    gwdatadict["OT"] = "Other"
    gwdatadict["PI"] = "Piezometer"
    gwdatadict["SP"] = "Spring"
    gwdatadict["UD"] = "Underdrain"
    gwdatadict["BASEG"] = "Baseline"
    gwdatadict["WE"] = "Well"
    found = 0
    try:
        conn = odbc.odbc(DMMESDEConnection)
        conn2 = odbc.odbc(Dmlr_DB)
        conn3 = odbc.odbc(WaterQuality)
        wqConn = odbc.odbc(WaterQuality)
    except:
        conn = odbc.odbc(DMMESDEConnection)
        conn2 = odbc.odbc(Dmlr_DB)
        conn3 = odbc.odbc(WaterQuality)
        wqConn = odbc.odbc(WaterQuality)
    dxcursor = conn3.cursor()  #cursor for dxk_test database
    cursor2 = conn2.cursor()  #cursor for dmlr database
    cursor = conn.cursor()  #cursor for EP database
    wqCursor = wqConn.cursor()
    sqlSearch = str(
        "select PeNo from vw_Dmlr_Applications where AppNo = '" + str(AppNumber) + "' order by ABS(RevNo) desc")
    cursor.execute(sqlSearch)
    result = cursor.fetchone()
    AppsList = []
    PermitExists = True
    Permit = []
    if type(result) is not types.NoneType:
        if type(result[0]) is not types.NoneType:
            if str(result[0]) != "" and str(result[0]) != "None":
                Permit.append(result[0])
            else:
                Permit.append("No Permit")
                PermitExists = False
        else:
            Permit.append("No Permit")
            PermitExists = False
    else:
        Permit.append("No Permit")
    if PermitExists == True:
        PermitDataList = []
        olderpermit = True
        newerpermit = False
        oldernewer = "current"
        oldernewerdict = {}
        if Permit[0] != "No Permit":
            NumRemoved = 0
            placeholder = "NA"
            while olderpermit == True:
                if NumRemoved == 0:
                    oldernewer = "current"
                else:
                    oldernewer = "older"
                sqlSearch = str(
                    "select TblPsCode,PePsDate,PeSitePhone,PeIssueDt,PeRenewalDt,PeOperator,PeOperation,PeDisturbed,PeRegraded,PeReleased,PeReclaimed,PeTobeDisturbed,PeTransferFrom,PeTransferTo,PeBonded,PeNpdesNo,PeNpdesIssue,PeNpdesRenew from DmlrPermits where PeNo = '" + str(
                        Permit[NumRemoved]) + "'")
                cursor2.execute(sqlSearch)
                pres = cursor2.fetchone()
                try:
                    sqlSearch = str("select TblPsDesc from PermitStatusTbl where TblPsCode = '" + str(pres[0]) + "'")
                    cursor.execute(sqlSearch)
                    psres = cursor.fetchone()
                    PermitStatTemp = str(psres[0])
                except:
                    PermitStatTemp = "NA"
                try:
                    if pres[1] is not None:
                        tempStatDate = pres[1].isoformat()
                    else:
                        tempStatDate = pres[1]
                    if pres[2] is not None:
                        tempPhoneNum = pres[2]
                    else:
                        tempPhoneNum = "NA"
                    if pres[3] is not None:
                        tempIssueDate = pres[3].isoformat()
                    else:
                        tempIssueDate = pres[3]
                    if pres[4] is not None:
                        tempRenewalDate = pres[4].isoformat()
                    else:
                        tempRenewalDate = pres[4]
                    if pres[5] is not None:
                        tempOperator = pres[5]
                    else:
                        tempOperator = "NA"
                    if pres[6] is not None:
                        tempOp = pres[6]
                    else:
                        tempOp = "NA"
                    if pres[7] is not None:
                        tempDistAcre = pres[7]
                    else:
                        tempDistAcre = "NA"
                    if pres[8] is not None:
                        tempRegradeAcre = pres[8]
                    else:
                        tempRegradeAcre = "NA"
                    if pres[9] is not None:
                        tempReleaseAcre = pres[9]
                    else:
                        tempReleaseAcre = "NA"
                    if pres[10] is not None:
                        tempReclaimAcre = pres[10]
                    else:
                        tempReclaimAcre = "NA"
                    if pres[11] is not None:
                        tempPotDistAcre = pres[11]
                    else:
                        tempPotDistAcre = "NA"
                    if pres[12] is not None and pres[12].rstrip() != "":
                        tempOldPermit = pres[12]
                        olderpermit = True
                        Permit.append(str(tempOldPermit))
                    else:
                        tempOldPermit = "NA"
                        olderpermit = False
                    if pres[13] is not None and oldernewer == "current":
                        tempNewPermit = pres[13]
                        newerpermit = True
                    else:
                        placeholder = "NA"
                    if pres[14] is not None:
                        tempBondedAcre = pres[14]
                    else:
                        pres[14] = "NA"
                    if pres[15] is not None:
                        tempNPDES = pres[15]
                    else:
                        tempNPDES = "NA"
                    if pres[16] is not None:
                        tempNPDESIssue = pres[16].isoformat()
                    else:
                        tempNPDESIssue = pres[16]
                    if pres[17] is not None:
                        tempNPDESRen = pres[17].isoformat()
                    else:
                        tempNPDESRen = pres[17]
                except:
                    tempStatDate = "NA"
                    tempPhoneNum = "NA"
                    tempIssueDate = "NA"
                    tempRenewalDate = "NA"
                    tempOperator = "NA"
                    tempOp = "NA"
                    tempDistAcre = "NA"
                    tempRegradeAcre = "NA"
                    tempReleaseAcre = "NA"
                    tempReclaimAcre = "NA"
                    tempPotDistAcre = "NA"
                    tempOldPermit = "NA"
                    olderpermit = False
                    tempNewPermit = "NA"
                    tempBondedAcre = "NA"
                    tempNPDES = "NA"
                    tempNPDESIssue = "NA"
                    tempNPDESRen = "NA"
                temp = str(tempStatDate).replace("T00:00:00", "").replace("00:00:00", "").replace("-", r"/").split(r"/",
                                                                                                                   1)
                temp.reverse()
                tempStatDate = r"/".join(temp)
                temp = str(tempIssueDate).replace("T00:00:00", "").replace("00:00:00", "").replace("-", r"/").split(
                    r"/", 1)
                temp.reverse()
                tempIssueDate = r"/".join(temp)
                temp = str(tempRenewalDate).replace("T00:00:00", "").replace("00:00:00", "").replace("-", r"/").split(
                    r"/", 1)
                temp.reverse()
                tempRenewalDate = r"/".join(temp)
                temp = str(tempNPDESIssue).replace("T00:00:00", "").replace("00:00:00", "").replace("-", r"/").split(
                    r"/", 1)
                temp.reverse()
                tempNPDESIssue = r"/".join(temp)
                temp = str(tempNPDESRen).replace("T00:00:00", "").replace("00:00:00", "").replace("-", r"/").split(r"/",
                                                                                                                   1)
                temp.reverse()
                tempNPDESRen = r"/".join(temp)
                oldernewerdict[Permit[NumRemoved]] = str(oldernewer)
                try:
                    PermitDataList.append(
                        [str(Permit[NumRemoved]), str(PermitStatTemp), str(tempIssueDate), str(tempRenewalDate),
                         str(tempNPDES), str(tempNPDESIssue), str(tempNPDESRen), str(tempOp), str(tempOperator),
                         str(tempPhoneNum), str(tempOldPermit), str(tempNewPermit), str(tempDistAcre),
                         str(tempRegradeAcre), str(tempReleaseAcre), str(tempPotDistAcre), str(tempBondedAcre),
                         str(NumRemoved), str(oldernewer)])
                except:
                    PermitDataList.append(
                        [str(Permit[NumRemoved]), str(PermitStatTemp), str(tempIssueDate), str(tempRenewalDate),
                         str(tempNPDES), str(tempNPDESIssue), str(tempNPDESRen), str(tempOp), str(tempOperator),
                         str(tempPhoneNum), str(tempOldPermit), str(placeholder), str(tempDistAcre),
                         str(tempRegradeAcre), str(tempReleaseAcre), str(tempPotDistAcre), str(tempBondedAcre),
                         str(NumRemoved), str(oldernewer)])
                NumRemoved += 1
            if newerpermit == True:
                numolder = NumRemoved - 1
                Permit.append(str(tempNewPermit))
                while newerpermit == True:
                    sqlSearch = str(
                        "select TblPsCode,PePsDate,PeSitePhone,PeIssueDt,PeRenewalDt,PeOperator,PeOperation,PeDisturbed,PeRegraded,PeReleased,PeReclaimed,PeTobeDisturbed,PeTransferFrom,PeTransferTo,PeBonded,PeNpdesNo,PeNpdesIssue,PeNpdesRenew from DmlrPermits where PeNo = '" + str(
                            tempNewPermit) + "'")
                    cursor2.execute(sqlSearch)
                    pres = cursor2.fetchone()
                    try:
                        sqlSearch = str(
                            "select TblPsDesc from PermitStatusTbl where TblPsCode = '" + str(pres[0]) + "'")
                        cursor.execute(sqlSearch)
                        psres = cursor.fetchone()
                        PermitStatTemp = str(psres[0])
                    except:
                        PermitStatTemp = "NA"
                    if pres[1] is not None:
                        tempStatDate = pres[1].isoformat()
                    else:
                        tempStatDate = pres[1]
                    if pres[2] is not None:
                        tempPhoneNum = pres[2]
                    else:
                        tempPhoneNum = "NA"
                    if pres[3] is not None:
                        tempIssueDate = pres[3].isoformat()
                    else:
                        tempIssueDate = pres[3]
                    if pres[4] is not None:
                        tempRenewalDate = pres[4].isoformat()
                    else:
                        tempRenewalDate = pres[4]
                    if pres[5] is not None:
                        tempOperator = pres[5]
                    else:
                        tempOperator = "NA"
                    if pres[6] is not None:
                        tempOp = pres[6]
                    else:
                        tempOp = "NA"
                    if pres[7] is not None:
                        tempDistAcre = pres[7]
                    else:
                        tempDistAcre = "NA"
                    if pres[8] is not None:
                        tempRegradeAcre = pres[8]
                    else:
                        tempRegradeAcre = "NA"
                    if pres[9] is not None:
                        tempReleaseAcre = pres[9]
                    else:
                        tempReleaseAcre = "NA"
                    if pres[10] is not None:
                        tempReclaimAcre = pres[10]
                    else:
                        tempReclaimAcre = "NA"
                    if pres[11] is not None:
                        tempPotDistAcre = pres[11]
                    else:
                        tempPotDistAcre = "NA"
                    if pres[12] is not None:
                        tempOldPermit = pres[12]
                    else:
                        tempOldPermit = "NA"
                    if pres[13] is not None:
                        tempNewPermit = pres[13]
                    else:
                        tempNewPermit = "NA"
                        newerpermit = False
                        Permit.append(newerpermit)
                    if pres[14] is not None:
                        tempBondedAcre = pres[14]
                    else:
                        pres[14] = "NA"
                    if pres[15] is not None:
                        tempNPDES = pres[15]
                    else:
                        tempNPDES = "NA"
                    if pres[16] is not None:
                        tempNPDESIssue = pres[16].isoformat()
                    else:
                        tempNPDESIssue = pres[16]
                    if pres[17] is not None:
                        tempNPDESRen = pres[17].isoformat()
                    else:
                        tempNPDESRen = pres[17]
                    temp = str(tempStatDate).replace("T00:00:00", "").replace("00:00:00", "").replace("-", r"/").split(
                        r"/", 1)
                    temp.reverse()
                    tempStatDate = r"/".join(temp)
                    temp = str(tempIssueDate).replace("T00:00:00", "").replace("00:00:00", "").replace("-", r"/").split(
                        r"/", 1)
                    temp.reverse()
                    tempIssueDate = r"/".join(temp)
                    temp = str(tempRenewalDate).replace("T00:00:00", "").replace("00:00:00", "").replace("-",
                                                                                                         r"/").split(
                        r"/", 1)
                    temp.reverse()
                    tempRenewalDate = r"/".join(temp)
                    temp = str(tempNPDESIssue).replace("T00:00:00", "").replace("00:00:00", "").replace("-",
                                                                                                        r"/").split(
                        r"/", 1)
                    temp.reverse()
                    tempNPDESIssue = r"/".join(temp)
                    temp = str(tempNPDESRen).replace("T00:00:00", "").replace("00:00:00", "").replace("-", r"/").split(
                        r"/", 1)
                    temp.reverse()
                    tempNPDESRen = r"/".join(temp)
                    if NumRemoved > numolder:
                        oldernewer = "newer"
                    else:
                        oldernewer = "current"
                    oldernewerdict[Permit[NumRemoved]] = str(oldernewer)
                    PermitDataList.append(
                        [str(Permit[NumRemoved]), str(PermitStatTemp), str(tempIssueDate), str(tempRenewalDate),
                         str(tempNPDES), str(tempNPDESIssue), str(tempNPDESRen), str(tempOp), str(tempOperator),
                         str(tempPhoneNum), str(tempOldPermit), str(tempNewPermit), str(tempDistAcre),
                         str(tempRegradeAcre), str(tempReleaseAcre), str(tempPotDistAcre), str(tempBondedAcre),
                         str(NumRemoved), str(oldernewer)])
                    NumRemoved += 1
        else:
            PermitDataList = ["No Current Permit", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA",
                              "NA", "NA", "NA", "NA", "NA", "NA", "current"]
        CPermitList = []
        OPermitList = []
        NPermitList = []
        NumPermits = len(PermitDataList)
        i = 0
        while i < NumPermits:
            if PermitDataList[i][18] == "current":
                CPermitList.append(PermitDataList[i])
            elif PermitDataList[i][18] == "older":
                OPermitList.append(PermitDataList[i])
            elif PermitDataList[i][18] == "newer":
                NPermitList.append(PermitDataList[i])
            i += 1
        OPermitList.reverse()
        PermitDataList = []
        for each in OPermitList:
            PermitDataList.append(each)
        for each in CPermitList:
            PermitDataList.append(each)
        for each in NPermitList:
            PermitDataList.append(each)
        Permit = []
        i = 0
        while i < NumPermits:
            Permit.append(PermitDataList[i][0])
            PermitDataList[i][17] = str(i)
            i += 1
        i = 0
        NumRemovedDict = {}
        OlderNewerDict = {}
        OlderNewerDict[AppNumber] = str("current")
        NumRemovedDict[AppNumber] = "0"
        while i < len(Permit):
            sqlSearch = str("select AppNo,RevNo,PeNo from vw_Dmlr_Applications where PeNo = '" + str(
                Permit[i]) + "' order by AtDecDt asc, AtRecDt asc, ABS(AppNo) asc,ABS(RevNo) desc")
            cursor.execute(sqlSearch)
            result = cursor.fetchall()
            if type(result) is not types.NoneType:
                for each in result:
                    if type(each) is not types.NoneType:
                        if type(each[0]) is not types.NoneType and each[0] not in AppsList:
                            sqlSearch = str("select RevNo,PeNo from vw_Dmlr_Applications where AppNo = '" + str(
                                each[0]) + "' order by ABS(RevNo) desc,PeNo desc")
                            cursor.execute(sqlSearch)
                            res = cursor.fetchone()
                            if res[0] == each[1]:
                                AppsList.append(each[0])
                                NumRemovedDict[each[0]] = str(i)
                                OlderNewerDict[each[0]] = str(PermitDataList[i][18])
            i += 1
        if AppNumber not in AppsList:
            AppsList.append(AppNumber)
        tempOlderApps = []
        tempNewerApps = []
        for each in AppsList:
            if str(each[0]) == '1' and str(each[1]) == '0' and str(each[2]) == '0':
                tempNewerApps.append(each)
            else:
                tempOlderApps.append(each)
        tempNewerApps.sort()
        AppsList = []
        for each in tempOlderApps:
            AppsList.append(each)
        for each in tempNewerApps:
            AppsList.append(each)
        MasterFSList = []
        MasterFSDict = {}
        MasterFSPermDict = {}
        for each in AppsList:
            sqlSearch = str("select FsNo,PeNo from DmlrFactSheets where ApNo = '" + str(each) + "'")
            cursor2.execute(sqlSearch)
            result = cursor2.fetchone()
            if type(result) is not types.NoneType:
                if type(result[0]) is not types.NoneType:
                    if result[0] not in MasterFSList:
                        MasterFSList.append(result[0])
                        MasterFSDict[result[0]] = str(result[1])
                        MasterFSPermDict[result[1]] = str(result[0])
        LastRevDict = {}
        PeNoDict = {}
        for each in AppsList:
            sqlSearch = str("select PeNo,RevNo from vw_Dmlr_Applications where AppNo = '" + str(
                each) + "' order by ABS(RevNo) desc")
            cursor.execute(sqlSearch)
            result = cursor.fetchone()
            LastRevDict[each] = str(result[1])
            PeNoDict[each] = str(result[0])
        AppFSDict = {}
        for each in AppsList:
            try:
                AppFSDict[each] = MasterFSPermDict[PeNoDict[each]]
            except:
                AppFSDict[each] = 'NA'
        AllGW = []
        AllGW1 = []
        AllGWAddDict = []
        AllGWDelDict = []
        AllGWAddDictNF = []
        AllGWDelDictNF = []
        AllNPDES = []
        AllNPDES1 = []
        AllNPDESAddDict = []
        AllNPDESDelDict = []
        AllNPDESAddDictNF = []
        AllNPDESDelDictNF = []
        AllIS = []
        AllIS1 = []
        AllISAddDict = []
        AllISDelDict = []
        AllISAddDictNF = []
        AllISDelDictNF = []
        AllRG = []
        AllRG1 = []
        AllRGAddDict = []
        AllRGDelDict = []
        AllRGAddDictNF = []
        AllRGDelDictNF = []
        for each in MasterFSList:
            AllIS.append([])
            AllISAddDict.append({})
            AllISDelDict.append({})
            AllISAddDictNF.append({})
            AllISDelDictNF.append({})
            sqlSearch = str(
                "select MpIsNo,FsIsAdded,FsIsDeleted "
                "from DmlrFactSheets_IS "
                "where FsNo = '" + str(each) + "'")
            cursor2.execute(sqlSearch)
            result = cursor2.fetchall()
            if type(result) is not types.NoneType:
                for i in result:
                    if type(i) is not types.NoneType:
                        if str(i[0]) not in AllIS1:
                            AllIS1.append((str(i[0])))
                        if str(i[0]) not in AllIS[MasterFSList.index(each)]:
                            AllIS[MasterFSList.index(each)].append(str(i[0]))
                            AllISAddDictNF[MasterFSList.index(each)][str(i[0])] = i[1]
                            AllISDelDictNF[MasterFSList.index(each)][str(i[0])] = i[2]
                            if type(i[1]) is not types.NoneType:
                                tempad = i[1].isoformat()
                                tempa = str(tempad).replace("T00:00:00", "").replace("00:00:00", "").replace("-",
                                                                                                             r"/").split(
                                    r"/", 1)
                                tempa.reverse()
                                tempadd = r"/".join(tempa)
                                AllISAddDict[MasterFSList.index(each)][str(i[0])] = tempadd
                            else:
                                AllISAddDict[MasterFSList.index(each)][str(i[0])] = "None"
                            if type(i[2]) is not types.NoneType:
                                tempad = i[2].isoformat()
                                tempa = str(tempad).replace("T00:00:00", "").replace("00:00:00", "").replace("-",
                                                                                                             r"/").split(
                                    r"/", 1)
                                tempa.reverse()
                                tempadd = r"/".join(tempa)
                                AllISDelDict[MasterFSList.index(each)][str(i[0])] = tempadd
                            else:
                                AllISDelDict[MasterFSList.index(each)][str(i[0])] = "None"
            AllGW.append([])
            AllGWAddDict.append({})
            AllGWDelDict.append({})
            AllGWAddDictNF.append({})
            AllGWDelDictNF.append({})
            sqlSearch = str(
                "select MpGwNo,FsGwAdded,FsGwDeleted from DmlrFactSheets_GW where FsNo = '" + str(each) + "'")
            cursor2.execute(sqlSearch)
            result = cursor2.fetchall()
            if type(result) is not types.NoneType:
                for i in result:
                    if type(i) is not types.NoneType:
                        if str(i[0]) not in AllGW1:
                            AllGW1.append((str(i[0])))
                        if str(i[0]) not in AllGW[MasterFSList.index(each)]:
                            AllGW[MasterFSList.index(each)].append(str(i[0]))
                            AllGWAddDictNF[MasterFSList.index(each)][str(i[0])] = i[1]
                            AllGWDelDictNF[MasterFSList.index(each)][str(i[0])] = i[2]
                            if type(i[1]) is not types.NoneType:
                                tempad = i[1].isoformat()
                                tempa = str(tempad).replace("T00:00:00", "").replace("00:00:00", "").replace("-",
                                                                                                             r"/").split(
                                    r"/", 1)
                                tempa.reverse()
                                tempadd = r"/".join(tempa)
                                AllGWAddDict[MasterFSList.index(each)][str(i[0])] = tempadd
                            else:
                                AllGWAddDict[MasterFSList.index(each)][str(i[0])] = "None"
                            if type(i[2]) is not types.NoneType:
                                tempad = i[2].isoformat()
                                tempa = str(tempad).replace("T00:00:00", "").replace("00:00:00", "").replace("-",
                                                                                                             r"/").split(
                                    r"/", 1)
                                tempa.reverse()
                                tempadd = r"/".join(tempa)
                                AllGWDelDict[MasterFSList.index(each)][str(i[0])] = tempadd
                            else:
                                AllGWDelDict[MasterFSList.index(each)][str(i[0])] = "None"
            AllNPDES.append([])
            AllNPDESAddDict.append({})
            AllNPDESDelDict.append({})
            AllNPDESAddDictNF.append({})
            AllNPDESDelDictNF.append({})
            sqlSearch = str(
                "select MpDsNo,FsDsAdded,FsDsDeleted from DmlrFactSheets_NPDES where FsNo = '" + str(each) + "'")
            cursor2.execute(sqlSearch)
            result = cursor2.fetchall()
            if type(result) is not types.NoneType:
                for i in result:
                    if type(i) is not types.NoneType:
                        if str(i[0]) not in AllNPDES1:
                            AllNPDES1.append((str(i[0])))
                        if str(i[0]) not in AllNPDES[MasterFSList.index(each)]:
                            AllNPDES[MasterFSList.index(each)].append(str(i[0]))
                            AllNPDESAddDictNF[MasterFSList.index(each)][str(i[0])] = i[1]
                            AllNPDESDelDictNF[MasterFSList.index(each)][str(i[0])] = i[2]
                            if type(i[1]) is not types.NoneType:
                                tempad = i[1].isoformat()
                                tempa = str(tempad).replace("T00:00:00", "").replace("00:00:00", "").replace("-",
                                                                                                             r"/").split(
                                    r"/", 1)
                                tempa.reverse()
                                tempadd = r"/".join(tempa)
                                AllNPDESAddDict[MasterFSList.index(each)][str(i[0])] = tempadd
                            else:
                                AllNPDESAddDict[MasterFSList.index(each)][str(i[0])] = "None"
                            if type(i[2]) is not types.NoneType:
                                tempad = i[2].isoformat()
                                tempa = str(tempad).replace("T00:00:00", "").replace("00:00:00", "").replace("-",
                                                                                                             r"/").split(
                                    r"/", 1)
                                tempa.reverse()
                                tempadd = r"/".join(tempa)
                                AllNPDESDelDict[MasterFSList.index(each)][str(i[0])] = tempadd
                            else:
                                AllNPDESDelDict[MasterFSList.index(each)][str(i[0])] = "None"
            AllRG.append([])
            AllRGAddDict.append({})
            AllRGDelDict.append({})
            AllRGAddDictNF.append({})
            AllRGDelDictNF.append({})
            sqlSearch = str("select MpRgNo,FsRgAdded,FsRgDeleted from DmlrFactSheets where FsNo = '" + str(each) + "'")
            cursor2.execute(sqlSearch)
            result = cursor2.fetchall()
            if type(result) is not types.NoneType:
                for i in result:
                    if type(i) is not types.NoneType:
                        if str(i[0]) not in AllRG1:
                            AllRG1.append((str(i[0])))
                        if str(i[0]) not in AllRG[MasterFSList.index(each)]:
                            AllRG[MasterFSList.index(each)].append(str(i[0]))
                            AllRGAddDictNF[MasterFSList.index(each)][str(i[0])] = i[1]
                            AllRGDelDictNF[MasterFSList.index(each)][str(i[0])] = i[2]
                            if type(i[1]) is not types.NoneType:
                                tempad = i[1].isoformat()
                                tempa = str(tempad).replace("T00:00:00", "").replace("00:00:00", "").replace("-",
                                                                                                             r"/").split(
                                    r"/", 1)
                                tempa.reverse()
                                tempadd = r"/".join(tempa)
                                AllRGAddDict[MasterFSList.index(each)][str(i[0])] = tempadd
                            else:
                                AllRGAddDict[MasterFSList.index(each)][str(i[0])] = "None"
                            if type(i[2]) is not types.NoneType:
                                tempad = i[2].isoformat()
                                tempa = str(tempad).replace("T00:00:00", "").replace("00:00:00", "").replace("-",
                                                                                                             r"/").split(
                                    r"/", 1)
                                tempa.reverse()
                                tempadd = r"/".join(tempa)
                                AllRGDelDict[MasterFSList.index(each)][str(i[0])] = tempadd
                            else:
                                AllRGDelDict[MasterFSList.index(each)][str(i[0])] = "None"
        BigAppList = []
        AppDescDict = {}
        AppDescriptionDict = {}
        AppStatDict = {}
        AppPermStatDict = {}
        CurrentAppDate = {}
        ReceivedAppDate = {}
        CurrAppFormatDict = {}
        AppWhoDict = {}
        for each in AppsList:
            sqlSearch = str(
                "select TblApCode,TblAsCode,AtRecDt,AtDecDt,AtCurAsDt from vw_Dmlr_Applications where AppNo = '" + str(
                    each) + "' and RevNo = '" + str(LastRevDict[each]) + "'")
            cursor.execute(sqlSearch)
            res = cursor.fetchone()
            tempAppCode = str(res[0])
            tempAppStatus = str(res[1])
            sqlSearch = str(
                "select AtDmlrStart from vw_Dmlr_Applications where AppNo = '" + str(each) + "' and RevNo = '1'")
            cursor.execute(sqlSearch)
            resF = cursor.fetchone()
            if type(resF) is not types.NoneType:
                if type(resF[0]) is not types.NoneType:
                    tempReceiveDate = resF[0].isoformat()
                else:
                    tempReceiveDate = resF[0]
                ReceivedAppDate[each] = resF[0]
            else:
                ReceivedAppDate[each] = "None"
                tempReceiveDate = "None"
            sqlSearch = str(
                "select AtIssueDate from Dmlr_AppData where AppNo = '" + str(each) + "' and RevNo = '" + str(
                    LastRevDict[each]) + "'")
            cursor.execute(sqlSearch)
            res = cursor.fetchone()
            if type(res[0]) is not types.NoneType:
                tempDecisionDate = res[0].isoformat()
            else:
                tempDecisionDate = res[0]
            if type(res[0]) is not types.NoneType:
                tempcurAppDate = res[0].isoformat()
            else:
                tempcurAppDate = res[0]
            CurrentAppDate[each] = res[0]
            temp = str(tempReceiveDate).replace("T00:00:00", "").replace("00:00:00", "").replace("-", r"/").split(r"/",
                                                                                                                  1)
            temp.reverse()
            tempReceiveDate = r"/".join(temp)
            temp = str(tempDecisionDate).replace("T00:00:00", "").replace("00:00:00", "").replace("-", r"/").split(r"/",
                                                                                                                   1)
            temp.reverse()
            tempDecisionDate = r"/".join(temp)
            temp = str(tempcurAppDate).replace("T00:00:00", "").replace("00:00:00", "").replace("-", r"/").split(r"/",
                                                                                                                 1)
            temp.reverse()
            tempcurAppDate = r"/".join(temp)
            CurrAppFormatDict[each] = tempcurAppDate
            sqlSearch = str(
                "select TblApDesc,TblPsCode from ApplicTypeTbl where TblApCode = '" + str(tempAppCode) + "'")
            cursor.execute(sqlSearch)
            r = cursor.fetchone()
            try:
                AppDescDict[each] = str(r[0])
                tempPSCode = r[1]
            except:
                AppDescDict[each] = str(tempAppCode)
                tempPSCode = ""
            sqlSearch = str("select TblAsDesc from ApplicStatusTbl where TblAsCode = '" + str(tempAppStatus) + "'")
            cursor.execute(sqlSearch)
            re = cursor.fetchone()
            try:
                AppStatDict[each] = str(re[0])
            except:
                AppStatDict[each] = str("Unknown")
            try:
                sqlSearch = str("select TblPsDesc from PermitStatusTbl where TblPsCode = '" + str(tempPSCode) + "'")
                cursor.execute(sqlSearch)
                resu = cursor.fetchone()
                AppPermStatDict[each] = str(resu[0])
            except:
                AppPermStatDict[each] = str("Unknown")
            try:
                sqlSearch = str("select TblWhName from Dmlr_AppTracking where AppNo = '" + str(
                    each) + "' and (TblSeCode = 'H2O ' or TblSeCode = 'H2O')")
                cursor.execute(sqlSearch)
                resu = cursor.fetchone()
                AppWhoDict[each] = str(resu[0].title())
            except:
                AppWhoDict[each] = "Unknown"
            try:
                sqlSearch = str(
                    "select PermitNo, PrPermitNo,ExpireDt,TblApCode,TblApDesc,Operation,ApName,ApAddr,ApCity,ApState,ApZip,ApDesc,ApComment from GenInfo where AppNo = '" + str(
                        each) + "' and RevNo = " + str(LastRevDict[each]))
                cursor.execute(sqlSearch)
                result = cursor.fetchone()
                AppDescriptionDict[each] = result[11]
            except:
                AppDescriptionDict[each] = "Not Available"
            BigAppList.append([str(each), str(LastRevDict[each]), str(AppDescDict[each]), str(AppStatDict[each]),
                               str(AppPermStatDict[each]), str(tempReceiveDate), str(tempDecisionDate),
                               str(NumRemovedDict[each]), str(OlderNewerDict[each]), str(AppWhoDict[each]),
                               AppDescriptionDict[each]])
            try:
                wqConn = odbc.odbc(WaterQuality)
                wq = wqConn.cursor()
            except:
                wqConn = odbc.odbc(WaterQuality)
                wq = wqConn.cursor()
        NewChangedApps = []
        NewChangedSessionDict = {}
        for each in BigAppList:
            wqSearch = str("select SessionNo,AppNo from FinalPermitsTable where AppNo = '" + str(each[0]) + "'")
            wq.execute(wqSearch)
            r = wq.fetchone()
            if type(r) is not types.NoneType:
                if type(r[0]) is not types.NoneType:
                    NewChangedApps.append(r[1])
                    NewChangedSessionDict[r[1]] = r[0]
        ChangedAppsMPIDS = []
        ChangedAppsMPIDWET = []
        ChangedAppsMPIDREP = []
        for each in NewChangedApps:
            ChangedAppsMPIDS.append([])
            ChangedAppsMPIDWET.append({})
            ChangedAppsMPIDREP.append({})
            osesh = []
            wqSearch = str("select LineageNo,ParentNo from SessionsTable where AppNo = '" + str(
                each) + "' and SessionNo = '" + str(NewChangedSessionDict[each]) + "'")
            wq.execute(wqSearch)
            r = wq.fetchone()
            if type(r) is not types.NoneType:
                par = r[1]
                lin = r[0]
                osesh.append(NewChangedSessionDict[each])
                osesh.append(par)
                while par != '0':
                    wqSearch = str(
                        "select ParentNo from SessionsTable where AppNo = '" + str(each) + "' and LineageNo = '" + str(
                            lin) + "' and SessionNo = '" + str(par) + "'")
                    wq.execute(wqSearch)
                    r = wq.fetchone()
                    if type(r) is not types.NoneType:
                        par = r[0]
                        osesh.append(par)
            oseshMPNOs = []
            for o in osesh:
                wqSearch = str(
                    "select MpidNo,CRep,WRep from MPIDTable where AppNo = '" + str(each) + "' and SessionNo = '" + str(
                        o) + "' and MpidType = 'NPDES' and ActionType = 'CHANGE' ORDER BY CAST (RecordNo as INT) desc")
                wq.execute(wqSearch)
                ores = wq.fetchall()
                for ore in ores:
                    if type(ore[0]) is not types.NoneType:
                        if len(ore[0]) > 0:
                            if ore[0] not in oseshMPNOs:
                                oseshMPNOs.append(ore[0])
                                ChangedAppsMPIDS[NewChangedApps.index(each)].append(ore[0])
                                ChangedAppsMPIDWET[NewChangedApps.index(each)][ore[0]] = ore[2]
                                ChangedAppsMPIDREP[NewChangedApps.index(each)][ore[0]] = ore[1]
        BigNPDESTable = []
        BigISTable = []
        BigGWTable = []
        BigRGTable = []
        for each in BigAppList:
            BigNPDESTable.append([])
            BigISTable.append([])
            BigGWTable.append([])
            BigRGTable.append([])
        for each in BigAppList:
            if each[0] == AppNumber:
                tempNPlist = []
                tempISlist = []
                tempGWlist = []
                tempRGlist = []


            # Get NPDES point data-----------------------------------------------
            sqlSearch = '''
            select Action, MPIDNo,TblMdCode,LocNo,FacLoc,Frequency,Elevation,TblQuDesc,
                   Northing,Easting, Status,TblSrName,WaterShedAcres,DisturbedAcres,TblMdCode
            from Hydro_PollutionDis
            where AppNo = {} and RevNo = {}
            '''.format(each[0], each[1])

            cursor.execute(sqlSearch)
            result = cursor.fetchall()
            for r in result:
                tempList = []
                tempList.append(str(r[0]))  #Action 0
                tempList.append(str(r[1]))  #MPID 1
                tempList.append(str(r[3]))  #LocNo 2
                tempList.append(str(r[4]))  #FacLoc 3
                tempList.append(str(r[5]))  #Freq 4
                tempList.append(str(r[6]))  #Elevation 5
                tempList.append(str(r[7]))  #Quad 6
                tempList.append(str(r[8]))  #North 7
                tempList.append(str(r[9]))  #East 8
                tempList.append(str(r[10]))  #Status 9
                tempList.append(str(r[11]))  #Stream 10
                tempList.append(str(r[12]))  #WSAcres 11
                tempList.append(str(r[13]))  #DistAcres 12
                tempList.append("NPDES")  #Type 13
                tempList.append("None")  #Add Date 14
                tempList.append("None")  #Delete Date 15
                tempList.append(each[0])  #Application Number 16
                tempList.append(str(r[14]))  # Type code 17
                tempList.append(PeNoDict[each[0]])  #Permit Number 18
                tempList.append(AppFSDict[each[0]])  #FS Number 19
                tempList.append("NA")  #Chemical Effluent Representative 20
                tempList.append("NA")  #WET Testing Effluent Representative 21
                tempList.append("NA")  #limit code 22
                if str(tempList[1]) == "None" or str(tempList[1]) == "":
                    try:
                        sqlSearch = str("select MpNo,TblMsCode from DmlrMpids where (MpCompId = '" + str(
                            tempList[2]) + "' or MpFacilLoc = '" + str(tempList[3]) + "') and (MPEasting = '" + str(
                            tempList[8]) + "' or MPNorthing = '" + str(tempList[7]) + "')")
                        cursor2.execute(sqlSearch)
                    except:
                        sqlSearch = str("select MpNo,TblMsCode from DmlrMpids where (MpCompId = '" + str(
                            tempList[2]) + "' and MpFacilLoc = '" + str(tempList[3]) + "')")
                        cursor2.execute(sqlSearch)
                    result = cursor2.fetchall()
                    if type(result) is not types.NoneType:
                        if len(result) == 1:
                            tempList[1] = str(result[0][0])
                            tempList[9] = str(result[0][1]) # Append new status
                if tempList[1] is not None and tempList[1] != "" and str(tempList[1]) != "None":
                    try:
                        tempList[14] = AllNPDESAddDict[MasterFSList.index(tempList[19])][str(tempList[1])]
                        tempList[15] = AllNPDESDelDict[MasterFSList.index(tempList[19])][str(tempList[1])]
                        if each[0] in NewChangedApps:
                            if tempList[1] in ChangedAppsMPIDS[NewChangedApps.index(each[0])]:
                                tempList[20] = ChangedAppsMPIDREP[NewChangedApps.index(each[0])][str(tempList[1])]
                                tempList[21] = ChangedAppsMPIDWET[NewChangedApps.index(each[0])][str(tempList[1])]
                        BigNPDESTable[BigAppList.index(each)].append(tempList)
                        if each[0] == AppNumber:
                            tempNPlist.append(tempList[1])
                    except:
                        pass
                if str(tempList[22]) == "NA":
                    try:
                        sqlSearch = str("select TblLmCode from vw_DmlrMpids where MpNo = '" + str(tempList[1]) + "'")
                        cursor2.execute(sqlSearch)
                        re = cursor2.fetchone()
                        tempList[22] = str(re[0])
                    except:
                        pass
            if each[0] == AppNumber:
                NPremainder = list(set(AllNPDES1) - set(tempNPlist))
                if len(NPremainder) > 0:
                    for np in NPremainder:
                        tempList = []
                        sqlSearch = str("select MpCompId,MpFacilLoc,MpFrqQtr,MpElevation,TblQuDesc,MpNorthing,"
                                        "MpEasting,TblMsCode,TblSrName,MpWtsdAcre,MpDistAcre,TblMdCode,TblLmCode "
                                        "from vw_DmlrMpids where MpNo = '" + str(np) + "'")
                        cursor2.execute(sqlSearch)
                        r = cursor2.fetchone()
                        try:
                            if type(r) is not types.NoneType:
                                tempList.append("None")
                                tempList.append(str(np))
                                tempList.append(str(r[0]))  #locno
                                tempList.append(str(r[1]))  #facloc
                                tempList.append(str(r[2]))  #frequency
                                tempList.append(str(r[3]))  #elevation
                                tempList.append(str(r[4]))  #quad
                                tempList.append(str(r[5]))  #northing
                                tempList.append(str(r[6]))  #easting
                                tempList.append(str(r[7]))  #status
                                tempList.append(str(r[8]))  #stream
                                tempList.append(str(r[9]))  #wtsdacres
                                tempList.append(str(r[10]))  #distacres
                                tempList.append("NPDES")  #type
                                tempList.append(
                                    AllNPDESAddDict[MasterFSList.index(AppFSDict[each[0]])][str(np)])  #add date
                                tempList.append(
                                    AllNPDESDelDict[MasterFSList.index(AppFSDict[each[0]])][str(np)])  #del date
                                tempList.append(each[0])  #app number
                                tempList.append(str(r[11]))  #type code
                                tempList.append(PeNoDict[each[0]])  #Permit Number 18
                                tempList.append(AppFSDict[each[0]])  #FS Number 19
                                tempList.append("NA")  #Chemical Effluent Representative 20
                                tempList.append("NA")  #WET Testing Effluent Representative 21
                                tempList.append(str(r[12]))  #limit code 22
                            else:
                                tempList.append("None")
                                tempList.append(str(np))
                                tempList.append("NA")  #locno
                                tempList.append("NA")  #facloc
                                tempList.append("NA")  #frequency
                                tempList.append("NA")  #elevation
                                tempList.append("NA")  #quad
                                tempList.append("NA")  #northing
                                tempList.append("NA")  #easting
                                tempList.append("NA")  #status
                                tempList.append("NA")  #stream
                                tempList.append("NA")  #wtsdacres
                                tempList.append("NA")  #distacres
                                tempList.append("NPDES")  #type
                                tempList.append(
                                    AllNPDESAddDict[MasterFSList.index(AppFSDict[each[0]])][str(np)])  #add date
                                tempList.append(
                                    AllNPDESDelDict[MasterFSList.index(AppFSDict[each[0]])][str(np)])  #del date
                                tempList.append(each[0])  #app number
                                tempList.append("NA")  #type code
                                tempList.append(PeNoDict[each[0]])  #Permit Number 18
                                tempList.append(AppFSDict[each[0]])  #FS Number 19
                                tempList.append("NA")  #Chemical Effluent Representative 20
                                tempList.append("NA")  #WET Testing Effluent Representative 21
                                tempList.append("NA")  #limit code 22
                            if each[0] in NewChangedApps:
                                if tempList[1] in ChangedAppsMPIDS[NewChangedApps.index(each[0])]:
                                    tempList[20] = ChangedAppsMPIDREP[NewChangedApps.index(each[0])][str(tempList[1])]
                                    tempList[21] = ChangedAppsMPIDWET[NewChangedApps.index(each[0])][str(tempList[1])]
                            BigNPDESTable[BigAppList.index(each)].append(tempList)
                        except:
                            pass
            BigNPDESTable[BigAppList.index(each)].sort(key=itemgetter(1))



            # Get Surface water point data
            sqlSearch = str(
                "select Action,MPIDNo,TblMdCode,LocNo,FacLoc,Frequency,TblQuDesc,Northing,Easting,Status,TblSrName,TblMdCode from Hydro_SWMP where AppNo = '" + str(
                    each[0]) + "' and RevNo = '" + str(each[1]) + "'")
            cursor.execute(sqlSearch)
            result = cursor.fetchall()
            for r in result:
                tempList = []
                tempList.append(str(r[0]))  #Action 0
                tempList.append(str(r[1]))  #MPID 1
                tempList.append(str(r[3]))  #LocNo 2
                tempList.append(str(r[4]))  #FacLoc 3
                tempList.append(str(r[5]))  #Freq 4
                tempList.append("NA")  #Elevation 5
                tempList.append(str(r[6]))  #Quad 6
                tempList.append(str(r[7]))  #North 7
                tempList.append(str(r[8]))  #East 8
                tempList.append(str(r[9]))  #Status 9
                tempList.append(str(r[10]))  #Stream 10
                tempList.append("NA")  #WSAcres 11
                tempList.append("NA")  #DistAcres 12
                tempList.append("INSTREAM")  #Type 13
                tempList.append("None")  #Add Date 14
                tempList.append("None")  #Delete Date 15
                tempList.append(each[0])  #Application Number 16
                tempList.append(str(r[11]))  #Type code 17
                tempList.append(PeNoDict[each[0]])  #Permit Number 18
                tempList.append(AppFSDict[each[0]])  #FS Number 19
                tempList.append("NA")  #Chemical Effluent Representative 20
                tempList.append("NA")  #WET Testing Effluent Representative 21
                tempList.append("NA")  #limit code 22
                if str(tempList[1]) == "None" or str(tempList[1]) == "":
                    try:
                        sqlSearch = str("select MpNo,TblMsCode from DmlrMpids where (MpCompId = '" + str(
                            tempList[2]) + "' or MpFacilLoc = '" + str(tempList[3]) + "') and (MPEasting = '" + str(
                            tempList[8]) + "' or MPNorthing = '" + str(tempList[7]) + "')")
                        cursor2.execute(sqlSearch)
                        result = cursor2.fetchall()
                        if type(result) is not types.NoneType:
                            if len(result) == 1:
                                tempList[1] = str(result[0][0])
                                tempList[9] = str(result[0][1])
                    except:
                        pass
                if tempList[1] is not None and tempList[1] != "" and str(tempList[1]) != "None":
                    try:
                        tempList[14] = AllISAddDict[MasterFSList.index(tempList[19])][str(tempList[1])]
                        tempList[15] = AllISDelDict[MasterFSList.index(tempList[19])][str(tempList[1])]
                        BigISTable[BigAppList.index(each)].append(tempList)
                        if each[0] == AppNumber:
                            tempISlist.append(tempList[1])
                    except:
                        pass
            if each[0] == AppNumber:
                ISremainder = list(set(AllIS1) - set(tempISlist))
                if len(ISremainder) > 0:
                    for np in ISremainder:
                        tempList = []
                        sqlSearch = str("select MpCompId,MpFacilLoc,MpFrqQtr,MpElevation,TblQuDesc,"
                                        "MpNorthing,MpEasting,TblMsCode,TblSrName,MpWtsdAcre,MpDistAcre,TblMdCode "
                                        "from vw_DmlrMpids where MpNo = '" + str(np) + "'")
                        cursor2.execute(sqlSearch)
                        r = cursor2.fetchone()
                        try:
                            if type(r) is not types.NoneType:
                                tempList.append("None")
                                tempList.append(str(np))
                                tempList.append(str(r[0]))  #locno
                                tempList.append(str(r[1]))  #facloc
                                tempList.append(str(r[2]))  #frequency
                                tempList.append("NA")  #elevation
                                tempList.append(str(r[4]))  #quad
                                tempList.append(str(r[5]))  #northing
                                tempList.append(str(r[6]))  #easting
                                tempList.append(str(r[7]))  #status
                                tempList.append(str(r[8]))  #stream
                                tempList.append("NA")  #wtsdacres
                                tempList.append(str(r[10]))  #distacres
                                tempList.append("INSTREAM")  #type
                                tempList.append(
                                    AllISAddDict[MasterFSList.index(AppFSDict[each[0]])][str(np)])  #add date
                                tempList.append(
                                    AllISDelDict[MasterFSList.index(AppFSDict[each[0]])][str(np)])  #del date
                                tempList.append(each[0])  #app number
                                tempList.append(str(r[11]))  #type code
                                tempList.append(PeNoDict[each[0]])  #Permit Number 18
                                tempList.append(AppFSDict[each[0]])  #FS Number 19
                                tempList.append("NA")  #Chemical Effluent Representative 20
                                tempList.append("NA")  #WET Testing Effluent Representative 21
                                tempList.append("NA")  #limit code 22
                            else:
                                tempList.append("None")
                                tempList.append(str(np))
                                tempList.append("NA")  #locno
                                tempList.append("NA")  #facloc
                                tempList.append("NA")  #frequency
                                tempList.append("NA")  #elevation
                                tempList.append("NA")  #quad
                                tempList.append("NA")  #northing
                                tempList.append("NA")  #easting
                                tempList.append("NA")  #status
                                tempList.append("NA")  #stream
                                tempList.append("NA")  #wtsdacres
                                tempList.append("NA")  #distacres
                                tempList.append("INSTREAM")  #type
                                tempList.append(
                                    AllISAddDict[MasterFSList.index(AppFSDict[each[0]])][str(np)])  #add date
                                tempList.append(
                                    AllISDelDict[MasterFSList.index(AppFSDict[each[0]])][str(np)])  #del date
                                tempList.append(each[0])  #app number
                                tempList.append("NA")  #type code
                                tempList.append(PeNoDict[each[0]])  #Permit Number 18
                                tempList.append(AppFSDict[each[0]])  #FS Number 19
                                tempList.append("NA")  #Chemical Effluent Representative 20
                                tempList.append("NA")  #WET Testing Effluent Representative 21
                                tempList.append("NA")  #limit code 22
                            BigISTable[BigAppList.index(each)].append(tempList)
                        except:
                            pass
            BigISTable[BigAppList.index(each)].sort(key=itemgetter(1))

            # Get groundwater info -----------------------------------------------
            sqlSearch = str("select Action,MPIDNo,TblMdCode,LocNo,FacLoc,Frequency,"
                            "Elevation,TblQuDesc,Northing,Easting,Status,TblMdCode "
                            "from Hydro_GWMP where AppNo = '" + str(each[0]) + "' and RevNo = '" + str(each[1]) + "'")
            cursor.execute(sqlSearch)
            result = cursor.fetchall()
            for r in result:
                tempList = []
                tempList.append(str(r[0]))  #Action 0
                tempList.append(str(r[1]))  #MPID 1
                tempList.append(str(r[3]))  #LocNo 2
                tempList.append(str(r[4]))  #FacLoc 3
                tempList.append(str(r[5]))  #Freq 4
                tempList.append(str(r[6]))  #Elevation 5
                tempList.append(str(r[7]))  #Quad 6
                tempList.append(str(r[8]))  #North 7
                tempList.append(str(r[9]))  #East 8
                tempList.append(str(r[10]))  #Status 9
                tempList.append("NA")  #Stream 10
                tempList.append("NA")  #WSAcres 11
                tempList.append("NA")  #DistAcres 12
                tempList.append("GROUNDWATER")  #Type 13
                tempList.append("None")  #Add Date 14
                tempList.append("None")  #Delete Date 15
                tempList.append(each[0])  #Application Number 16
                tempList.append(str(r[11]))  #Code 17
                tempList.append(PeNoDict[each[0]])  #Permit Number 18
                tempList.append(AppFSDict[each[0]])  #FS Number 19
                tempList.append("NA")  #Chemical Effluent Representative 20
                tempList.append("NA")  #WET Testing Effluent Representative 21
                tempList.append("NA")  #limit code 22
                if str(tempList[1]) == "None" or str(tempList[1]) == "":  # If no MPID
                    try:
                        sqlSearch = str("select MpNo,TblMsCode "
                                        "from DmlrMpids "
                                        "where (MpCompId = '" + str(tempList[2]) + "' or MpFacilLoc = '" + str(
                            tempList[3]) + "') and (MPEasting = '" + str(tempList[8]) + "' or MPNorthing = '" + str(
                            tempList[7]) + "')")
                        cursor2.execute(sqlSearch)
                        result = cursor2.fetchall()
                        if type(result) is not types.NoneType:
                            if len(result) == 1:
                                tempList[1] = str(result[0][0])
                                tempList[9] = str(result[0][1])
                    except:
                        pass
                if tempList[1] is not None and tempList[1] != "" and str(tempList[1]) != "None":
                    try:
                        tempList[14] = AllGWAddDict[MasterFSList.index(tempList[19])][str(tempList[1])]
                        tempList[15] = AllGWDelDict[MasterFSList.index(tempList[19])][str(tempList[1])]
                        BigGWTable[BigAppList.index(each)].append(tempList)
                        if each[0] == AppNumber:
                            tempGWlist.append(tempList[1])
                    except:
                        pass
            if each[0] == AppNumber:
                GWremainder = list(set(AllGW1) - set(tempGWlist))
                if len(GWremainder) > 0:
                    for np in GWremainder:
                        tempList = []
                        sqlSearch = str(
                            "select MpCompId,MpFacilLoc,MpFrqQtr,MpElevation,TblQuDesc,MpNorthing,MpEasting,TblMsCode,TblSrName,MpWtsdAcre,MpDistAcre,TblMdCode from vw_DmlrMpids where MpNo = '" + str(
                                np) + "'")
                        cursor2.execute(sqlSearch)
                        r = cursor2.fetchone()
                        try:
                            if type(r) is not types.NoneType:
                                tempList.append("None")
                                tempList.append(str(np))
                                tempList.append(str(r[0]))  #locno
                                tempList.append(str(r[1]))  #facloc
                                tempList.append(str(r[2]))  #frequency
                                tempList.append(str(r[3]))  #elevation
                                tempList.append(str(r[4]))  #quad
                                tempList.append(str(r[5]))  #northing
                                tempList.append(str(r[6]))  #easting
                                tempList.append(str(r[7]))  #status
                                tempList.append("NA")  #stream
                                tempList.append("NA")  #wtsdacres
                                tempList.append("NA")  #distacres
                                tempList.append("GROUNDWATER")  #type
                                tempList.append(
                                    AllGWAddDict[MasterFSList.index(AppFSDict[each[0]])][str(np)])  #add date
                                tempList.append(
                                    AllGWDelDict[MasterFSList.index(AppFSDict[each[0]])][str(np)])  #del date
                                tempList.append(each[0])  #app number
                                tempList.append(str(r[11]))  #type code
                                tempList.append(PeNoDict[each[0]])  #Permit Number 18
                                tempList.append(AppFSDict[each[0]])  #FS Number 19
                                tempList.append("NA")  #Chemical Effluent Representative 20
                                tempList.append("NA")  #WET Testing Effluent Representative 21
                                tempList.append("NA")  #limit code 22
                            else:
                                tempList.append("None")
                                tempList.append(str(np))
                                tempList.append("NA")  #locno
                                tempList.append("NA")  #facloc
                                tempList.append("NA")  #frequency
                                tempList.append("NA")  #elevation
                                tempList.append("NA")  #quad
                                tempList.append("NA")  #northing
                                tempList.append("NA")  #easting
                                tempList.append("NA")  #status
                                tempList.append("NA")  #stream
                                tempList.append("NA")  #wtsdacres
                                tempList.append("NA")  #distacres
                                tempList.append("GROUNDWATER")  #type
                                tempList.append(
                                    AllGWAddDict[MasterFSList.index(AppFSDict[each[0]])][str(np)])  #add date
                                tempList.append(
                                    AllGWDelDict[MasterFSList.index(AppFSDict[each[0]])][str(np)])  #del date
                                tempList.append(each[0])  #app number
                                tempList.append("NA")  #type code
                                tempList.append(PeNoDict[each[0]])  #Permit Number 18
                                tempList.append(AppFSDict[each[0]])  #FS Number 19
                                tempList.append("NA")  #Chemical Effluent Representative 20
                                tempList.append("NA")  #WET Testing Effluent Representative 21
                                tempList.append("NA")  #limit code 22
                            BigGWTable[BigAppList.index(each)].append(tempList)
                        except:
                            pass
            BigGWTable[BigAppList.index(each)].sort(key=itemgetter(1))

            # Get Rain gauge data
            sqlSearch = str("select Action,MPIDNo,TblMdCode,LocNo,FacLoc,"
                            "TblQuDesc,Northing,Easting,Status,TblMdCode "
                            "from Hydro_CLMP "
                            "where AppNo = '" + str(each[0]) + "' and RevNo = '" + str(each[1]) + "'")
            cursor.execute(sqlSearch)
            result = cursor.fetchall()
            for r in result:
                tempList = []
                tempList.append(str(r[0]))  #Action 0
                tempList.append(str(r[1]))  #MPID 1
                tempList.append(str(r[3]))  #LocNo 2
                tempList.append(str(r[4]))  #FacLoc 3
                tempList.append("NA")       #Freq 4
                tempList.append("NA")       #Elevation 5
                tempList.append(str(r[5]))  #Quad 6
                tempList.append(str(r[6]))  #North 7
                tempList.append(str(r[7]))  #East 8
                tempList.append(str(r[8]))  #Status 9
                tempList.append("NA")       #Stream 10
                tempList.append("NA")       #WSAcres 11
                tempList.append("NA")       #DistAcres 12
                tempList.append("RAIN GAUGE")  #Type 13
                tempList.append("None")  #Add Date 14
                tempList.append("None")  #Delete Date 15
                tempList.append(each[0])  #Application Number 16
                tempList.append(str(r[9]))  #Type code 17
                tempList.append(PeNoDict[each[0]])  #Permit Number 18
                tempList.append(AppFSDict[each[0]])  #FS Number 19
                tempList.append("NA")  #Chemical Effluent Representative 20
                tempList.append("NA")  #WET Testing Effluent Representative 21
                tempList.append("NA")  #limit code 22
                if str(tempList[1]) == "None" or str(tempList[1]) == "": # If MPID number not found
                    try:
                        # Serach for it based on company id, coordinates, and name in DmlrMpids
                        sqlSearch = str("select MpNo,TblMsCode "
                                        "from DmlrMpids "
                                        "where (MpCompId = '" + str(tempList[2]) + "' or MpFacilLoc = '" + str(
                            tempList[3]) + "') and (MPEasting = '" + str(tempList[8]) + "' or MPNorthing = '" + str(
                            tempList[7]) + "')")
                        cursor2.execute(sqlSearch)
                        result = cursor2.fetchall()
                        if type(result) is not types.NoneType:
                            if len(result) == 1:
                                tempList[1] = str(result[0][0]) # Append the MPID number found in DmlrMpids
                                tempList[9] = str(result[0][1]) # Append the Status (TblMsCode) found in DmlrMpids
                    except:
                        pass
                if tempList[1] is not None and tempList[1] != "" and str(tempList[1]) != "None":
                    try:
                        tempList[14] = AllRGAddDict[MasterFSList.index(tempList[19])][str(tempList[1])]
                        tempList[15] = AllRGDelDict[MasterFSList.index(tempList[19])][str(tempList[1])]
                        BigRGTable[BigAppList.index(each)].append(tempList)
                        if each[0] == AppNumber:
                            tempRGlist.append(tempList[1])
                    except:
                        pass
            if each[0] == AppNumber:
                RGremainder = list(set(AllRG1) - set(tempRGlist))
                if len(RGremainder) > 0:
                    for np in RGremainder:
                        tempList = []
                        sqlSearch = str("select MpCompId,MpFacilLoc,MpFrqQtr,MpElevation,TblQuDesc,MpNorthing,"
                                        "MpEasting,TblMsCode,TblSrName,MpWtsdAcre,MpDistAcre,TblMdCode "
                                        "from vw_DmlrMpids where MpNo = '" + str(np) + "'")
                        cursor2.execute(sqlSearch)
                        r = cursor2.fetchone()
                        try:
                            if type(r) is not types.NoneType:
                                tempList.append("None")
                                tempList.append(str(np))
                                tempList.append(str(r[0]))  #locno
                                tempList.append(str(r[1]))  #facloc
                                tempList.append("NA")  #frequency
                                tempList.append("NA")  #elevation
                                tempList.append(str(r[4]))  #quad
                                tempList.append(str(r[5]))  #northing
                                tempList.append(str(r[6]))  #easting
                                tempList.append(str(r[7]))  #status
                                tempList.append("NA")  #stream
                                tempList.append("NA")  #wtsdacres
                                tempList.append("NA")  #distacres
                                tempList.append("RAIN GAUGE")  #type
                                tempList.append(
                                    AllRGAddDict[MasterFSList.index(AppFSDict[each[0]])][str(np)])  #add date
                                tempList.append(
                                    AllRGDelDict[MasterFSList.index(AppFSDict[each[0]])][str(np)])  #del date
                                tempList.append(each[0])  #app number
                                tempList.append(str(r[11]))  #type code
                                tempList.append(PeNoDict[each[0]])  #Permit Number 18
                                tempList.append(AppFSDict[each[0]])  #FS Number 19
                                tempList.append("NA")  #Chemical Effluent Representative 20
                                tempList.append("NA")  #WET Testing Effluent Representative 21
                                tempList.append("NA")  #limit code 22
                            else:
                                tempList.append("None")
                                tempList.append(str(np))
                                tempList.append("NA")  #locno
                                tempList.append("NA")  #facloc
                                tempList.append("NA")  #frequency
                                tempList.append("NA")  #elevation
                                tempList.append("NA")  #quad
                                tempList.append("NA")  #northing
                                tempList.append("NA")  #easting
                                tempList.append("NA")  #status
                                tempList.append("NA")  #stream
                                tempList.append("NA")  #wtsdacres
                                tempList.append("NA")  #distacres
                                tempList.append("RAIN GAUGE")  #type
                                tempList.append(
                                    AllRGAddDict[MasterFSList.index(AppFSDict[each[0]])][str(np)])  #add date
                                tempList.append(
                                    AllRGDelDict[MasterFSList.index(AppFSDict[each[0]])][str(np)])  #del date
                                tempList.append(each[0])  #app number
                                tempList.append("NA")  #type code
                                tempList.append(PeNoDict[each[0]])  #Permit Number 18
                                tempList.append(AppFSDict[each[0]])  #FS Number 19
                                tempList.append("NA")  #Chemical Effluent Representative 20
                                tempList.append("NA")  #WET Testing Effluent Representative 21
                                tempList.append("NA")  #limit code 22
                            BigRGTable[BigAppList.index(each)].append(tempList)
                        except:
                            pass
            BigRGTable[BigAppList.index(each)].sort(key=itemgetter(1))

        MasterNPDESList = AllNPDES1
        MasterISList = AllIS1
        MasterGWList = AllGW1
        MasterRGList = AllRG1
        f = 0
        while f < len(BigNPDESTable):
            g = 0
            while g < len(BigNPDESTable[f]):
                if (str(BigNPDESTable[f][g][1]).title() == "None" or str(BigNPDESTable[f][g][1]) == ""):
                    holdFacLoc = BigNPDESTable[f][g][3]
                    h = 0
                    while h < len(BigNPDESTable):
                        i = 0
                        while i < len(BigNPDESTable[h]):
                            if holdFacLoc == BigNPDESTable[h][i][3] and BigNPDESTable[h][i][1].title() != "None" and \
                                            BigNPDESTable[h][i][1] != "":
                                BigNPDESTable[f][g][1] = BigNPDESTable[h][i][1]
                                BigNPDESTable[f][g][22] = BigNPDESTable[h][i][22]
                                if BigNPDESTable[f][g][18] == BigNPDESTable[h][i][18]:
                                    BigNPDESTable[f][g][14] = BigNPDESTable[h][i][14]
                                    BigNPDESTable[f][g][15] = BigNPDESTable[h][i][15]
                                break;
                            i += 1
                        h += 1
                g += 1
            f += 1
        f = 0
        while f < len(BigISTable):
            g = 0
            while g < len(BigISTable[f]):
                if (str(BigISTable[f][g][1]).title() == "None" or str(BigISTable[f][g][1]) == ""):
                    holdFacLoc = BigISTable[f][g][3]
                    h = 0
                    while h < len(BigISTable):
                        i = 0
                        while i < len(BigISTable[h]):
                            if holdFacLoc == BigISTable[h][i][3] and BigISTable[h][i][1].title() != "None" and \
                                            BigISTable[h][i][1] != "":
                                BigISTable[f][g][1] = BigISTable[h][i][1]
                                if BigISTable[f][g][18] == BigISTable[h][i][18]:
                                    BigISTable[f][g][14] = BigISTable[h][i][14]
                                    BigISTable[f][g][15] = BigISTable[h][i][15]
                                break;
                            i += 1
                        h += 1
                g += 1
            f += 1
        f = 0
        while f < len(BigGWTable):
            g = 0
            while g < len(BigGWTable[f]):
                if (str(BigGWTable[f][g][1]).title() == "None" or str(BigGWTable[f][g][1]) == ""):
                    holdFacLoc = BigGWTable[f][g][3]
                    h = 0
                    while h < len(BigGWTable):
                        i = 0
                        while i < len(BigGWTable[h]):
                            if holdFacLoc == BigGWTable[h][i][3] and BigGWTable[h][i][1].title() != "None" and \
                                            BigGWTable[h][i][1] != "":
                                BigGWTable[f][g][1] = BigGWTable[h][i][1]
                                if BigGWTable[f][g][18] == BigGWTable[h][i][18]:
                                    BigGWTable[f][g][14] = BigGWTable[h][i][14]
                                    BigGWTable[f][g][15] = BigGWTable[h][i][15]
                                break;
                            i += 1
                        h += 1
                g += 1
            f += 1
        f = 0
        while f < len(BigRGTable):
            g = 0
            while g < len(BigRGTable[f]):
                if (str(BigRGTable[f][g][1]).title() == "None" or str(BigRGTable[f][g][1]) == ""):
                    holdFacLoc = BigRGTable[f][g][3]
                    h = 0
                    while h < len(BigRGTable):
                        i = 0
                        while i < len(BigRGTable[h]):
                            if holdFacLoc == BigRGTable[h][i][3] and BigRGTable[h][i][1].title() != "None" and \
                                            BigRGTable[h][i][1] != "":
                                BigRGTable[f][g][1] = BigRGTable[h][i][1]
                                if BigRGTable[f][g][18] == BigRGTable[h][i][18]:
                                    BigRGTable[f][g][14] = BigRGTable[h][i][14]
                                    BigRGTable[f][g][15] = BigRGTable[h][i][15]
                                break;
                            i += 1
                        h += 1
                g += 1
            f += 1
        BigAppNPDESCommentsList = []
        BigAppISCommentsList = []
        BigAppGWCommentsList = []
        BigAppRGCommentsList = []
        for each in BigAppList:
            BigAppNPDESCommentsList.append([])
            BigAppISCommentsList.append([])
            BigAppGWCommentsList.append([])
            BigAppRGCommentsList.append([])
        MasterMPIDSharedPermitDict = {}
        i = 0
        while i < len(MasterNPDESList):
            TPermList = []
            sqlSearch = str("select AppNo from Hydro_PollutionDis where MPIDNo = '" + str(MasterNPDESList[i]) + "'")
            cursor.execute(sqlSearch)
            results = cursor.fetchall()
            results = list(set(results))
            for each in results:
                sqlSearch = str("select PeNo from vw_Dmlr_Applications where AppNo = '" + str(each[0]) + "'")
                cursor.execute(sqlSearch)
                result = cursor.fetchall()
                result = list(set(result))
                for permit in result:
                    if permit[0] not in TPermList and permit[0] not in Permit and str(permit[0]).rstrip() != "" and str(
                            permit[0]) != "None":
                        TPermList.append(permit[0])
                MasterMPIDSharedPermitDict[MasterNPDESList[i]] = TPermList
            i += 1
        i = 0
        while i < len(MasterGWList):
            TPermList = []
            sqlSearch = str("select AppNo from Hydro_GWMP where MPIDNo = '" + str(MasterGWList[i]) + "'")
            cursor.execute(sqlSearch)
            results = cursor.fetchall()
            results = list(set(results))
            for each in results:
                sqlSearch = str("select PeNo from vw_Dmlr_Applications where AppNo = '" + str(each[0]) + "'")
                cursor.execute(sqlSearch)
                result = cursor.fetchall()
                result = list(set(result))
                for permit in result:
                    if permit[0] not in TPermList and permit[0] not in Permit and str(permit[0]).rstrip() != "" and str(
                            permit[0]) != "None":
                        TPermList.append(permit[0])
                MasterMPIDSharedPermitDict[MasterGWList[i]] = TPermList
            i += 1
        i = 0
        while i < len(MasterISList):
            TPermList = []
            sqlSearch = str("select AppNo from Hydro_SWMP where MPIDNo = '" + str(MasterISList[i]) + "'")
            cursor.execute(sqlSearch)
            results = cursor.fetchall()
            results = list(set(results))
            for each in results:
                sqlSearch = str("select PeNo from vw_Dmlr_Applications where AppNo = '" + str(each[0]) + "'")
                cursor.execute(sqlSearch)
                result = cursor.fetchall()
                result = list(set(result))
                for permit in result:
                    if permit[0] not in TPermList and permit[0] not in Permit and str(permit[0]).rstrip() != "" and str(
                            permit[0]) != "None":
                        TPermList.append(permit[0])
                MasterMPIDSharedPermitDict[MasterISList[i]] = TPermList
            i += 1
        i = 0
        while i < len(MasterRGList):
            TPermList = []
            sqlSearch = str("select AppNo from Hydro_CLMP where MPIDNo = '" + str(MasterRGList[i]) + "'")
            cursor.execute(sqlSearch)
            results = cursor.fetchall()
            results = list(set(results))
            for each in results:
                sqlSearch = str("select PeNo from vw_Dmlr_Applications where AppNo = '" + str(each[0]) + "'")
                cursor.execute(sqlSearch)
                result = cursor.fetchall()
                result = list(set(result))
                for permit in result:
                    if permit[0] not in TPermList and permit[0] not in Permit and str(permit[0]).rstrip() != "" and str(
                            permit[0]) != "None":
                        TPermList.append(permit[0])
                MasterMPIDSharedPermitDict[MasterRGList[i]] = TPermList
            i += 1
        i = len(BigAppList) - 1
        FSList = []
        NPDESAddList = []
        NPDESDelList = []
        GWAddList = []
        GWDelList = []
        ISAddList = []
        ISDelList = []
        RGAddList = []
        RGDelList = []
        for eachFS in MasterFSList:
            FSList.append(str(eachFS))
            NPDESAddList.append([])
            NPDESDelList.append([])
            GWAddList.append([])
            GWDelList.append([])
            ISAddList.append([])
            ISDelList.append([])
            RGAddList.append([])
            RGDelList.append([])
        WriteFileString('Writing Change Comments for MPID Histories')
        while i >= 0:
            j = 0
            while j < len(BigNPDESTable[i]):
                Match = False
                BigAppNPDESCommentsList[i].append([])
                if BigNPDESTable[i][j][14] != "None" and BigNPDESTable[i][j][1] not in NPDESAddList[
                    FSList.index(BigNPDESTable[i][j][19])]:
                    BigAppNPDESCommentsList[i][j].append([
                        "MPID " + str(BigNPDESTable[i][j][1]) + " was added to permit " + str(
                            PeNoDict[BigAppList[i][0]]) + ". ", str(BigNPDESTable[i][j][1]), str(BigAppList[i][0]),
                        str(BigNPDESTable[i][j][14])])
                    NPDESAddList[FSList.index(BigNPDESTable[i][j][19])].append(BigNPDESTable[i][j][1])
                if BigNPDESTable[i][j][15] != "None" and BigNPDESTable[i][j][1] not in NPDESDelList[
                    FSList.index(BigNPDESTable[i][j][19])]:
                    BigAppNPDESCommentsList[i][j].append([
                        "MPID " + str(BigNPDESTable[i][j][1]) + " was deleted from permit " + str(
                            PeNoDict[BigAppList[i][0]]) + ". ", str(BigNPDESTable[i][j][1]), str(BigAppList[i][0]),
                        str(BigNPDESTable[i][j][15])])
                    NPDESDelList[FSList.index(BigNPDESTable[i][j][19])].append(BigNPDESTable[i][j][1])
                k = i - 1
                while k >= 0:
                    l = 0
                    while l < len(BigNPDESTable[k]):
                        if BigNPDESTable[k][l][1] == BigNPDESTable[i][j][1] and Match == False and BigAppList[k][
                            2] != "N" and BigAppList[k][2] != "BOND REDUCTION" and BigAppList[k][2] != "CLEANUP" and \
                                        BigAppList[i][2] != "CLEANUP" and BigAppList[k][2] != "ANNIVERSARY RPT" and \
                                        BigAppList[i][2] != "ANNIVERSARY RPT" and BigAppList[i][2] != "N" and \
                                        BigAppList[i][2] != "BOND REDUCTION" and BigAppList[i][6] != 'None' and (
                                BigNPDESTable[i][j][15] == "None" or (
                            dparser.parse(BigNPDESTable[i][j][15]) > dparser.parse(BigAppList[i][6]))) and \
                                        BigAppList[i][3] != "DATA DUMP PROVIDED" and BigAppList[i][
                            3] != "WITHDRAWN BY APPLICANT":
                            if BigNPDESTable[k][l][2] != BigNPDESTable[i][j][2]:
                                BigAppNPDESCommentsList[i][j].append(["The location number of MPID " + str(
                                    BigNPDESTable[i][j][1]) + " was changed from " + str(
                                    BigNPDESTable[k][l][2]) + " in application " + str(BigAppList[k][0]) + " to " + str(
                                    BigNPDESTable[i][j][2]) + " in application " + str(BigAppList[i][0]) + ". ",
                                                                      str(BigNPDESTable[i][j][1]),
                                                                      str(BigAppList[i][0]),
                                                                      str(CurrAppFormatDict[BigNPDESTable[i][j][16]])])
                            if BigNPDESTable[k][l][3] != BigNPDESTable[i][j][3]:
                                BigAppNPDESCommentsList[i][j].append(["The facility location of MPID " + str(
                                    BigNPDESTable[i][j][1]) + " was changed from " + str(
                                    BigNPDESTable[k][l][3]) + " in application " + str(BigAppList[k][0]) + " to " + str(
                                    BigNPDESTable[i][j][3]) + " in application " + str(BigAppList[i][0]) + ". ",
                                                                      str(BigNPDESTable[i][j][1]),
                                                                      str(BigAppList[i][0]),
                                                                      str(CurrAppFormatDict[BigNPDESTable[i][j][16]])])
                            if BigNPDESTable[k][l][4] != BigNPDESTable[i][j][4]:
                                BigAppNPDESCommentsList[i][j].append(["The monitoring frequency of MPID " + str(
                                    BigNPDESTable[i][j][1]) + " was changed from " + str(
                                    BigNPDESTable[k][l][4]) + " in application " + str(BigAppList[k][0]) + " to " + str(
                                    BigNPDESTable[i][j][4]) + " in application " + str(BigAppList[i][0]) + ". ",
                                                                      str(BigNPDESTable[i][j][1]),
                                                                      str(BigAppList[i][0]),
                                                                      str(CurrAppFormatDict[BigNPDESTable[i][j][16]])])
                            if BigNPDESTable[k][l][5] != BigNPDESTable[i][j][5]:
                                BigAppNPDESCommentsList[i][j].append([
                                    "The elevation of MPID " + str(BigNPDESTable[i][j][1]) + " was changed from " + str(
                                        BigNPDESTable[k][l][5]) + " in application " + str(
                                        BigAppList[k][0]) + " to " + str(
                                        BigNPDESTable[i][j][5]) + " in application " + str(BigAppList[i][0]) + ". ",
                                    str(BigNPDESTable[i][j][1]), str(BigAppList[i][0]),
                                    str(CurrAppFormatDict[BigNPDESTable[i][j][16]])])
                            if BigNPDESTable[k][l][6] != BigNPDESTable[i][j][6]:
                                BigAppNPDESCommentsList[i][j].append(["The quadrangle of MPID " + str(
                                    BigNPDESTable[i][j][1]) + " was changed from " + str(
                                    BigNPDESTable[k][l][6]) + " in application " + str(BigAppList[k][0]) + " to " + str(
                                    BigNPDESTable[i][j][6]) + " in application " + str(BigAppList[i][0]) + ". ",
                                                                      str(BigNPDESTable[i][j][1]),
                                                                      str(BigAppList[i][0]),
                                                                      str(CurrAppFormatDict[BigNPDESTable[i][j][16]])])
                            if BigNPDESTable[k][l][7] != BigNPDESTable[i][j][7]:
                                BigAppNPDESCommentsList[i][j].append(["The northing coordinate of MPID " + str(
                                    BigNPDESTable[i][j][1]) + " was changed from " + str(
                                    BigNPDESTable[k][l][7]) + " in application " + str(BigAppList[k][0]) + " to " + str(
                                    BigNPDESTable[i][j][7]) + " in application " + str(BigAppList[i][0]) + ". ",
                                                                      str(BigNPDESTable[i][j][1]),
                                                                      str(BigAppList[i][0]),
                                                                      str(CurrAppFormatDict[BigNPDESTable[i][j][16]])])
                            if BigNPDESTable[k][l][8] != BigNPDESTable[i][j][8]:
                                BigAppNPDESCommentsList[i][j].append(["The easting coordinate of MPID " + str(
                                    BigNPDESTable[i][j][1]) + " was changed from " + str(
                                    BigNPDESTable[k][l][8]) + " in application " + str(BigAppList[k][0]) + " to " + str(
                                    BigNPDESTable[i][j][8]) + " in application " + str(BigAppList[i][0]) + ". ",
                                                                      str(BigNPDESTable[i][j][1]),
                                                                      str(BigAppList[i][0]),
                                                                      str(CurrAppFormatDict[BigNPDESTable[i][j][16]])])
                            if BigNPDESTable[k][l][9] != BigNPDESTable[i][j][9]:
                                BigAppNPDESCommentsList[i][j].append([
                                    "The status of MPID " + str(BigNPDESTable[i][j][1]) + " was changed from " + str(
                                        BigNPDESTable[k][l][9]) + " in application " + str(
                                        BigAppList[k][0]) + " to " + str(
                                        BigNPDESTable[i][j][9]) + " in application " + str(BigAppList[i][0]) + ". ",
                                    str(BigNPDESTable[i][j][1]), str(BigAppList[i][0]),
                                    str(CurrAppFormatDict[BigNPDESTable[i][j][16]])])
                            if BigNPDESTable[k][l][10] != BigNPDESTable[i][j][10]:
                                BigAppNPDESCommentsList[i][j].append([
                                    "The stream of MPID " + str(BigNPDESTable[i][j][1]) + " was changed from " + str(
                                        BigNPDESTable[k][l][10]) + " in application " + str(
                                        BigAppList[k][0]) + " to " + str(
                                        BigNPDESTable[i][j][10]) + " in application " + str(BigAppList[i][0]) + ". ",
                                    str(BigNPDESTable[i][j][1]), str(BigAppList[i][0]),
                                    str(CurrAppFormatDict[BigNPDESTable[i][j][16]])])
                            if BigNPDESTable[k][l][11] != BigNPDESTable[i][j][11]:
                                BigAppNPDESCommentsList[i][j].append(["The watershed acreage of MPID " + str(
                                    BigNPDESTable[i][j][1]) + " was changed from " + str(
                                    BigNPDESTable[k][l][11]) + " in application " + str(
                                    BigAppList[k][0]) + " to " + str(
                                    BigNPDESTable[i][j][11]) + " in application " + str(BigAppList[i][0]) + ". ",
                                                                      str(BigNPDESTable[i][j][1]),
                                                                      str(BigAppList[i][0]),
                                                                      str(CurrAppFormatDict[BigNPDESTable[i][j][16]])])
                            if BigNPDESTable[k][l][12] != BigNPDESTable[i][j][12]:
                                BigAppNPDESCommentsList[i][j].append(["The disturbed acreage of MPID " + str(
                                    BigNPDESTable[i][j][1]) + " was changed from " + str(
                                    BigNPDESTable[k][l][12]) + " in application " + str(
                                    BigAppList[k][0]) + " to " + str(
                                    BigNPDESTable[i][j][12]) + " in application " + str(BigAppList[i][0]) + ". ",
                                                                      str(BigNPDESTable[i][j][1]),
                                                                      str(BigAppList[i][0]),
                                                                      str(CurrAppFormatDict[BigNPDESTable[i][j][16]])])
                            if BigNPDESTable[i][j][20] != "NA" and BigNPDESTable[k][l][20] != BigNPDESTable[i][j][20]:
                                if BigNPDESTable[i][j][20] == "Yes":
                                    BigAppNPDESCommentsList[i][j].append([
                                        "Representative chemical effluent limitations were placed on MPID " + str(
                                            BigNPDESTable[i][j][1]) + " in application " + str(BigAppList[i][0]) + ". ",
                                        str(BigNPDESTable[i][j][1]), str(BigAppList[i][0]),
                                        str(CurrAppFormatDict[BigNPDESTable[i][j][16]])])
                                elif BigNPDESTable[k][l][20] == "Yes" and BigNPDESTable[i][j][20] == "No":
                                    BigAppNPDESCommentsList[i][j].append([
                                        "Representative chemical effluent limitations were removed from MPID " + str(
                                            BigNPDESTable[i][j][1]) + " in application " + str(BigAppList[i][0]) + ". ",
                                        str(BigNPDESTable[i][j][1]), str(BigAppList[i][0]),
                                        str(CurrAppFormatDict[BigNPDESTable[i][j][16]])])
                            if BigNPDESTable[i][j][21] != "NA" and BigNPDESTable[k][l][21] != BigNPDESTable[i][j][21]:
                                if BigNPDESTable[i][j][21] == "Acute":
                                    BigAppNPDESCommentsList[i][j].append(["MPID " + str(BigNPDESTable[i][j][
                                        1]) + " has acute WET testing requirements as of application " + str(
                                        BigAppList[i][0]) + ". ", str(BigNPDESTable[i][j][1]), str(BigAppList[i][0]),
                                                                          str(CurrAppFormatDict[
                                                                              BigNPDESTable[i][j][16]])])
                                elif BigNPDESTable[i][j][21] == "Chronic":
                                    BigAppNPDESCommentsList[i][j].append(["MPID " + str(BigNPDESTable[i][j][
                                        1]) + " has chronic WET testing requirements as of application " + str(
                                        BigAppList[i][0]) + ". ", str(BigNPDESTable[i][j][1]), str(BigAppList[i][0]),
                                                                          str(CurrAppFormatDict[
                                                                              BigNPDESTable[i][j][16]])])
                                elif BigNPDESTable[i][j][21] == "Both":
                                    BigAppNPDESCommentsList[i][j].append(["MPID " + str(BigNPDESTable[i][j][
                                        1]) + " has both acute and chronic WET testing requirements as of application " + str(
                                        BigAppList[i][0]) + ". ", str(BigNPDESTable[i][j][1]), str(BigAppList[i][0]),
                                                                          str(CurrAppFormatDict[
                                                                              BigNPDESTable[i][j][16]])])
                                elif BigNPDESTable[k][l][20] != "NA" and BigNPDESTable[i][j][21] == "No":
                                    BigAppNPDESCommentsList[i][j].append([
                                        "WET testing requirements were removed from MPID " + str(
                                            BigNPDESTable[i][j][1]) + " in application " + str(BigAppList[i][0]) + ". ",
                                        str(BigNPDESTable[i][j][1]), str(BigAppList[i][0]),
                                        str(CurrAppFormatDict[BigNPDESTable[i][j][16]])])
                            if BigNPDESTable[k][l][22] != BigNPDESTable[i][j][22]:
                                BigAppNPDESCommentsList[i][j].append(["The limit code of MPID " + str(
                                    BigNPDESTable[i][j][1]) + " was changed from " + str(
                                    BigNPDESTable[k][l][22]) + " in application " + str(
                                    BigAppList[k][0]) + " to " + str(
                                    BigNPDESTable[i][j][22]) + " in application " + str(BigAppList[i][0]) + ". ",
                                                                      str(BigNPDESTable[i][j][1]),
                                                                      str(BigAppList[i][0]),
                                                                      str(CurrAppFormatDict[BigNPDESTable[i][j][16]])])
                            Match = True
                        l += 1
                    k -= 1
                j += 1
            j = 0
            while j < len(BigGWTable[i]):
                Match = False
                BigAppGWCommentsList[i].append([])
                if BigGWTable[i][j][14] != "None" and BigGWTable[i][j][1] not in GWAddList[
                    FSList.index(BigGWTable[i][j][19])]:
                    BigAppGWCommentsList[i][j].append([
                        "MPID " + str(BigGWTable[i][j][1]) + " was added to permit " + str(
                            PeNoDict[BigAppList[i][0]]) + " as a " + str(
                            gwdatadict[BigGWTable[i][j][17]]) + " station. ", str(BigGWTable[i][j][1]),
                        str(BigAppList[i][0]), str(BigGWTable[i][j][14])])
                    GWAddList[FSList.index(BigGWTable[i][j][19])].append(BigGWTable[i][j][1])
                if BigGWTable[i][j][15] != "None" and BigGWTable[i][j][1] not in GWDelList[
                    FSList.index(BigGWTable[i][j][19])]:
                    BigAppGWCommentsList[i][j].append([
                        "MPID " + str(BigGWTable[i][j][1]) + " was deleted from permit " + str(
                            PeNoDict[BigAppList[i][0]]) + ". ", str(BigGWTable[i][j][1]), str(BigAppList[i][0]),
                        str(BigGWTable[i][j][15])])
                    GWDelList[FSList.index(BigGWTable[i][j][19])].append(BigGWTable[i][j][1])
                k = i - 1
                while k >= 0:
                    l = 0
                    while l < len(BigGWTable[k]):
                        if BigGWTable[k][l][1] == BigGWTable[i][j][1] and Match == False and BigAppList[k][2] != "N" and \
                                        BigAppList[k][2] != "BOND REDUCTION" and BigAppList[k][2] != "CLEANUP" and \
                                        BigAppList[i][2] != "CLEANUP" and BigAppList[k][2] != "ANNIVERSARY RPT" and \
                                        BigAppList[i][2] != "ANNIVERSARY RPT" and BigAppList[i][2] != "N" and \
                                        BigAppList[i][2] != "BOND REDUCTION" and BigAppList[i][6] != 'None' and (
                                BigGWTable[i][j][15] == "None" or (
                            dparser.parse(BigGWTable[i][j][15]) > dparser.parse(BigAppList[i][6]))) and BigAppList[i][
                            3] != "DATA DUMP PROVIDED" and BigAppList[i][3] != "WITHDRAWN BY APPLICANT":
                            FoundMatch = True
                            if BigGWTable[k][l][2] != BigGWTable[i][j][2]:
                                BigAppGWCommentsList[i][j].append(["The location number of MPID " + str(
                                    BigGWTable[i][j][1]) + " was changed from " + str(
                                    BigGWTable[k][l][2]) + " in application " + str(BigAppList[k][0]) + " to " + str(
                                    BigGWTable[i][j][2]) + " in application " + str(BigAppList[i][0]) + ". ",
                                                                   str(BigGWTable[i][j][1]), str(BigAppList[i][0]),
                                                                   str(CurrAppFormatDict[BigGWTable[i][j][16]])])
                            if BigGWTable[k][l][3] != BigGWTable[i][j][3]:
                                BigAppGWCommentsList[i][j].append(["The facility location of MPID " + str(
                                    BigGWTable[i][j][1]) + " was changed from " + str(
                                    BigGWTable[k][l][3]) + " in application " + str(BigAppList[k][0]) + " to " + str(
                                    BigGWTable[i][j][3]) + " in application " + str(BigAppList[i][0]) + ". ",
                                                                   str(BigGWTable[i][j][1]), str(BigAppList[i][0]),
                                                                   str(CurrAppFormatDict[BigGWTable[i][j][16]])])
                            if BigGWTable[k][l][4] != BigGWTable[i][j][4]:
                                BigAppGWCommentsList[i][j].append(["The monitoring frequency of MPID " + str(
                                    BigGWTable[i][j][1]) + " was changed from " + str(
                                    BigGWTable[k][l][4]) + " in application " + str(BigAppList[k][0]) + " to " + str(
                                    BigGWTable[i][j][4]) + " in application " + str(BigAppList[i][0]) + ". ",
                                                                   str(BigGWTable[i][j][1]), str(BigAppList[i][0]),
                                                                   str(CurrAppFormatDict[BigGWTable[i][j][16]])])
                            if BigGWTable[k][l][5] != BigGWTable[i][j][5]:
                                BigAppGWCommentsList[i][j].append([
                                    "The elevation of MPID " + str(BigGWTable[i][j][1]) + " was changed from " + str(
                                        BigGWTable[k][l][5]) + " in application " + str(
                                        BigAppList[k][0]) + " to " + str(
                                        BigGWTable[i][j][5]) + " in application " + str(BigAppList[i][0]) + ". ",
                                    str(BigGWTable[i][j][1]), str(BigAppList[i][0]),
                                    str(CurrAppFormatDict[BigGWTable[i][j][16]])])
                            if BigGWTable[k][l][6] != BigGWTable[i][j][6]:
                                BigAppGWCommentsList[i][j].append([
                                    "The quadrangle of MPID " + str(BigGWTable[i][j][1]) + " was changed from " + str(
                                        BigGWTable[k][l][6]) + " in application " + str(
                                        BigAppList[k][0]) + " to " + str(
                                        BigGWTable[i][j][6]) + " in application " + str(BigAppList[i][0]) + ". ",
                                    str(BigGWTable[i][j][1]), str(BigAppList[i][0]),
                                    str(CurrAppFormatDict[BigGWTable[i][j][16]])])
                            if BigGWTable[k][l][7] != BigGWTable[i][j][7]:
                                BigAppGWCommentsList[i][j].append(["The northing coordinate of MPID " + str(
                                    BigGWTable[i][j][1]) + " was changed from " + str(
                                    BigGWTable[k][l][7]) + " in application " + str(BigAppList[k][0]) + " to " + str(
                                    BigGWTable[i][j][7]) + " in application " + str(BigAppList[i][0]) + ". ",
                                                                   str(BigGWTable[i][j][1]), str(BigAppList[i][0]),
                                                                   str(CurrAppFormatDict[BigGWTable[i][j][16]])])
                            if BigGWTable[k][l][8] != BigGWTable[i][j][8]:
                                BigAppGWCommentsList[i][j].append(["The easting coordinate of MPID " + str(
                                    BigGWTable[i][j][1]) + " was changed from " + str(
                                    BigGWTable[k][l][8]) + " in application " + str(BigAppList[k][0]) + " to " + str(
                                    BigGWTable[i][j][8]) + " in application " + str(BigAppList[i][0]) + ". ",
                                                                   str(BigGWTable[i][j][1]), str(BigAppList[i][0]),
                                                                   str(CurrAppFormatDict[BigGWTable[i][j][16]])])
                            if BigGWTable[k][l][9] != BigGWTable[i][j][9]:
                                BigAppGWCommentsList[i][j].append([
                                    "The status of MPID " + str(BigGWTable[i][j][1]) + " was changed from " + str(
                                        BigGWTable[k][l][9]) + " in application " + str(
                                        BigAppList[k][0]) + " to " + str(
                                        BigGWTable[i][j][9]) + " in application " + str(BigAppList[i][0]) + ". ",
                                    str(BigGWTable[i][j][1]), str(BigAppList[i][0]),
                                    str(CurrAppFormatDict[BigGWTable[i][j][16]])])
                            if BigGWTable[k][l][10] != BigGWTable[i][j][10]:
                                BigAppGWCommentsList[i][j].append([
                                    "The stream of MPID " + str(BigGWTable[i][j][1]) + " was changed from " + str(
                                        BigGWTable[k][l][10]) + " in application " + str(
                                        BigAppList[k][0]) + " to " + str(
                                        BigGWTable[i][j][10]) + " in application " + str(BigAppList[i][0]) + ". ",
                                    str(BigGWTable[i][j][1]), str(BigAppList[i][0]),
                                    str(CurrAppFormatDict[BigGWTable[i][j][16]])])
                            if BigGWTable[k][l][11] != BigGWTable[i][j][11]:
                                BigAppGWCommentsList[i][j].append(["The watershed acreage of MPID " + str(
                                    BigGWTable[i][j][1]) + " was changed from " + str(
                                    BigGWTable[k][l][11]) + " in application " + str(BigAppList[k][0]) + " to " + str(
                                    BigGWTable[i][j][11]) + " in application " + str(BigAppList[i][0]) + ". ",
                                                                   str(BigGWTable[i][j][1]), str(BigAppList[i][0]),
                                                                   str(CurrAppFormatDict[BigGWTable[i][j][16]])])
                            if BigGWTable[k][l][12] != BigGWTable[i][j][12]:
                                BigAppGWCommentsList[i][j].append(["The disturbed acreage of MPID " + str(
                                    BigGWTable[i][j][1]) + " was changed from " + str(
                                    BigGWTable[k][l][12]) + " in application " + str(BigAppList[k][0]) + " to " + str(
                                    BigGWTable[i][j][12]) + " in application " + str(BigAppList[i][0]) + ". ",
                                                                   str(BigGWTable[i][j][1]), str(BigAppList[i][0]),
                                                                   str(CurrAppFormatDict[BigGWTable[i][j][16]])])
                            try:
                                if str(BigGWTable[k][l][17]) != str(BigGWTable[i][j][17]):
                                    BigAppGWCommentsList[i][j].append([
                                        "The station type of MPID " + str(BigGWTable[i][j][1]) + " was changed from " +
                                        gwdatadict[str(BigGWTable[k][l][17])] + " in application " + str(
                                            BigAppList[k][0]) + " to " + gwdatadict[
                                            str(BigGWTable[i][j][17])] + " in application " + str(
                                            BigAppList[i][0]) + ". ", str(BigGWTable[i][j][1]), str(BigAppList[i][0]),
                                        str(CurrAppFormatDict[BigGWTable[i][j][16]])])
                            except:
                                if BigGWTable[k][l][17] == 'None' and str(BigGWTable[i][j][17]) != 'None':
                                    BigGWTable[k][l][17] = BigGWTable[i][j][17]
                            Match = True
                        try:
                            if BigGWTable[k][l][17] == 'None' and str(BigGWTable[i][j][17]) != 'None':
                                BigGWTable[k][l][17] = BigGWTable[i][j][17]
                        except:
                            pass
                        l += 1
                    k -= 1
                j += 1
            j = 0
            while j < len(BigISTable[i]):
                Match = False
                BigAppISCommentsList[i].append([])
                if BigISTable[i][j][14] != "None" and BigISTable[i][j][1] not in ISAddList[
                    FSList.index(BigISTable[i][j][19])]:
                    BigAppISCommentsList[i][j].append([
                        "MPID " + str(BigISTable[i][j][1]) + " was added to permit " + str(
                            PeNoDict[BigAppList[i][0]]) + " as a " + str(
                            swdatadict[BigISTable[i][j][17]]) + " monitoring station. ", str(BigISTable[i][j][1]),
                        str(BigAppList[i][0]), str(BigISTable[i][j][14])])
                    ISAddList[FSList.index(BigISTable[i][j][19])].append(BigISTable[i][j][1])
                if BigISTable[i][j][15] != "None" and BigISTable[i][j][1] not in ISDelList[
                    FSList.index(BigISTable[i][j][19])]:
                    BigAppISCommentsList[i][j].append([
                        "MPID " + str(BigISTable[i][j][1]) + " was deleted from permit " + str(
                            PeNoDict[BigAppList[i][0]]) + ". ", str(BigISTable[i][j][1]), str(BigAppList[i][0]),
                        str(BigISTable[i][j][15])])
                    ISDelList[FSList.index(BigISTable[i][j][19])].append(BigISTable[i][j][1])
                k = i - 1
                while k >= 0:
                    l = 0
                    while l < len(BigISTable[k]):
                        if BigISTable[k][l][1] == BigISTable[i][j][1] and Match == False and BigAppList[k][2] != "N" and \
                                        BigAppList[k][2] != "BOND REDUCTION" and BigAppList[k][2] != "CLEANUP" and \
                                        BigAppList[i][2] != "CLEANUP" and BigAppList[k][2] != "ANNIVERSARY RPT" and \
                                        BigAppList[i][2] != "ANNIVERSARY RPT" and BigAppList[i][2] != "N" and \
                                        BigAppList[i][2] != "BOND REDUCTION" and BigAppList[i][6] != 'None' and (
                                BigISTable[i][j][15] == "None" or (
                            dparser.parse(BigISTable[i][j][15]) > dparser.parse(BigAppList[i][6]))) and BigAppList[i][
                            3] != "DATA DUMP PROVIDED" and BigAppList[i][3] != "WITHDRAWN BY APPLICANT":
                            if BigISTable[k][l][2] != BigISTable[i][j][2]:
                                BigAppISCommentsList[i][j].append(["The location number of MPID " + str(
                                    BigISTable[i][j][1]) + " was changed from " + str(
                                    BigISTable[k][l][2]) + " in application " + str(BigAppList[k][0]) + " to " + str(
                                    BigISTable[i][j][2]) + " in application " + str(BigAppList[i][0]) + ". ",
                                                                   str(BigISTable[i][j][1]), str(BigAppList[i][0]),
                                                                   str(CurrAppFormatDict[BigISTable[i][j][16]])])
                            if BigISTable[k][l][3] != BigISTable[i][j][3]:
                                BigAppISCommentsList[i][j].append(["The facility location of MPID " + str(
                                    BigISTable[i][j][1]) + " was changed from " + str(
                                    BigISTable[k][l][3]) + " in application " + str(BigAppList[k][0]) + " to " + str(
                                    BigISTable[i][j][3]) + " in application " + str(BigAppList[i][0]) + ". ",
                                                                   str(BigISTable[i][j][1]), str(BigAppList[i][0]),
                                                                   str(CurrAppFormatDict[BigISTable[i][j][16]])])
                            if BigISTable[k][l][4] != BigISTable[i][j][4]:
                                BigAppISCommentsList[i][j].append(["The monitoring frequency of MPID " + str(
                                    BigISTable[i][j][1]) + " was changed from " + str(
                                    BigISTable[k][l][4]) + " in application " + str(BigAppList[k][0]) + " to " + str(
                                    BigISTable[i][j][4]) + " in application " + str(BigAppList[i][0]) + ". ",
                                                                   str(BigISTable[i][j][1]), str(BigAppList[i][0]),
                                                                   str(CurrAppFormatDict[BigISTable[i][j][16]])])
                            if BigISTable[k][l][5] != BigISTable[i][j][5]:
                                BigAppISCommentsList[i][j].append([
                                    "The elevation of MPID " + str(BigISTable[i][j][1]) + " was changed from " + str(
                                        BigISTable[k][l][5]) + " in application " + str(
                                        BigAppList[k][0]) + " to " + str(
                                        BigISTable[i][j][5]) + " in application " + str(BigAppList[i][0]) + ". ",
                                    str(BigISTable[i][j][1]), str(BigAppList[i][0]),
                                    str(CurrAppFormatDict[BigISTable[i][j][16]])])
                            if BigISTable[k][l][6] != BigISTable[i][j][6]:
                                BigAppISCommentsList[i][j].append([
                                    "The quadrangle of MPID " + str(BigISTable[i][j][1]) + " was changed from " + str(
                                        BigISTable[k][l][6]) + " in application " + str(
                                        BigAppList[k][0]) + " to " + str(
                                        BigISTable[i][j][6]) + " in application " + str(BigAppList[i][0]) + ". ",
                                    str(BigISTable[i][j][1]), str(BigAppList[i][0]),
                                    str(CurrAppFormatDict[BigISTable[i][j][16]])])
                            if BigISTable[k][l][7] != BigISTable[i][j][7]:
                                BigAppISCommentsList[i][j].append(["The northing coordinate of MPID " + str(
                                    BigISTable[i][j][1]) + " was changed from " + str(
                                    BigISTable[k][l][7]) + " in application " + str(BigAppList[k][0]) + " to " + str(
                                    BigISTable[i][j][7]) + " in application " + str(BigAppList[i][0]) + ". ",
                                                                   str(BigISTable[i][j][1]), str(BigAppList[i][0]),
                                                                   str(CurrAppFormatDict[BigISTable[i][j][16]])])
                            if BigISTable[k][l][8] != BigISTable[i][j][8]:
                                BigAppISCommentsList[i][j].append(["The easting coordinate of MPID " + str(
                                    BigISTable[i][j][1]) + " was changed from " + str(
                                    BigISTable[k][l][8]) + " in application " + str(BigAppList[k][0]) + " to " + str(
                                    BigISTable[i][j][8]) + " in application " + str(BigAppList[i][0]) + ". ",
                                                                   str(BigISTable[i][j][1]), str(BigAppList[i][0]),
                                                                   str(CurrAppFormatDict[BigISTable[i][j][16]])])
                            if BigISTable[k][l][9] != BigISTable[i][j][9]:
                                BigAppISCommentsList[i][j].append([
                                    "The status of MPID " + str(BigISTable[i][j][1]) + " was changed from " + str(
                                        BigISTable[k][l][9]) + " in application " + str(
                                        BigAppList[k][0]) + " to " + str(
                                        BigISTable[i][j][9]) + " in application " + str(BigAppList[i][0]) + ". ",
                                    str(BigISTable[i][j][1]), str(BigAppList[i][0]),
                                    str(CurrAppFormatDict[BigISTable[i][j][16]])])
                            if BigISTable[k][l][10] != BigISTable[i][j][10]:
                                BigAppISCommentsList[i][j].append([
                                    "The stream of MPID " + str(BigISTable[i][j][1]) + " was changed from " + str(
                                        BigISTable[k][l][10]) + " in application " + str(
                                        BigAppList[k][0]) + " to " + str(
                                        BigISTable[i][j][10]) + " in application " + str(BigAppList[i][0]) + ". ",
                                    str(BigISTable[i][j][1]), str(BigAppList[i][0]),
                                    str(CurrAppFormatDict[BigISTable[i][j][16]])])
                            if BigISTable[k][l][11] != BigISTable[i][j][11]:
                                BigAppISCommentsList[i][j].append(["The watershed acreage of MPID " + str(
                                    BigISTable[i][j][1]) + " was changed from " + str(
                                    BigISTable[k][l][11]) + " in application " + str(BigAppList[k][0]) + " to " + str(
                                    BigISTable[i][j][11]) + " in application " + str(BigAppList[i][0]) + ". ",
                                                                   str(BigISTable[i][j][1]), str(BigAppList[i][0]),
                                                                   str(CurrAppFormatDict[BigISTable[i][j][16]])])
                            if BigISTable[k][l][12] != BigISTable[i][j][12]:
                                BigAppISCommentsList[i][j].append(["The disturbed acreage of MPID " + str(
                                    BigISTable[i][j][1]) + " was changed from " + str(
                                    BigISTable[k][l][12]) + " in application " + str(BigAppList[k][0]) + " to " + str(
                                    BigISTable[i][j][12]) + " in application " + str(BigAppList[i][0]) + ". ",
                                                                   str(BigISTable[i][j][1]), str(BigAppList[i][0]),
                                                                   str(CurrAppFormatDict[BigISTable[i][j][16]])])
                            try:
                                if str(BigISTable[k][l][17]) != str(BigISTable[i][j][17]):
                                    BigAppISCommentsList[i][j].append(["The monitoring type of MPID " + str(
                                        BigISTable[i][j][1]) + " was changed from " + swdatadict[str(
                                        BigISTable[k][l][17])] + " in application " + str(BigAppList[k][0]) + " to " +
                                                                       swdatadict[str(BigISTable[i][j][
                                                                           17])] + " in application " + str(
                                        BigAppList[i][0]) + ". ", str(BigISTable[i][j][1]), str(BigAppList[i][0]),
                                                                       str(CurrAppFormatDict[BigISTable[i][j][16]])])
                            except:
                                if str(BigISTable[k][l][17]) == 'None' and str(BigISTable[i][j][17]) != 'None':
                                    BigISTable[k][l][17] = BigISTable[i][j][17]
                            Match = True
                        try:
                            if str(BigISTable[k][l][17]) == 'None' and str(BigISTable[i][j][17]) != 'None':
                                BigISTable[k][l][17] = BigISTable[i][j][17]
                        except:
                            pass
                        l += 1
                    k -= 1
                j += 1
            j = 0
            while j < len(BigRGTable[i]):
                Match = False
                BigAppRGCommentsList[i].append([])
                if BigRGTable[i][j][14] != "None" and BigRGTable[i][j][1] not in RGAddList[
                    FSList.index(BigRGTable[i][j][19])]:
                    BigAppRGCommentsList[i][j].append([
                        "MPID " + str(BigRGTable[i][j][1]) + " was added to permit " + str(
                            PeNoDict[BigAppList[i][0]]) + ". ", str(BigRGTable[i][j][1]), str(BigAppList[i][0]),
                        str(BigRGTable[i][j][14])])
                    RGAddList[FSList.index(BigRGTable[i][j][19])].append(BigRGTable[i][j][1])
                if BigRGTable[i][j][15] != "None" and BigRGTable[i][j][1] not in RGDelList[
                    FSList.index(BigRGTable[i][j][19])]:
                    BigAppRGCommentsList[i][j].append([
                        "MPID " + str(BigRGTable[i][j][1]) + " was deleted from permit " + str(
                            PeNoDict[BigAppList[i][0]]) + ". ", str(BigRGTable[i][j][1]), str(BigAppList[i][0]),
                        str(BigRGTable[i][j][15])])
                    RGDelList[FSList.index(BigRGTable[i][j][19])].append(BigRGTable[i][j][1])
                k = i - 1
                while k >= 0:
                    l = 0
                    while l < len(BigRGTable[k]):
                        if BigRGTable[k][l][1] == BigRGTable[i][j][1] and Match == False and BigAppList[k][2] != "N" and \
                                        BigAppList[k][2] != "BOND REDUCTION" and BigAppList[k][2] != "CLEANUP" and \
                                        BigAppList[i][2] != "CLEANUP" and BigAppList[k][2] != "ANNIVERSARY RPT" and \
                                        BigAppList[i][2] != "ANNIVERSARY RPT" and BigAppList[i][2] != "N" and \
                                        BigAppList[i][2] != "BOND REDUCTION" and BigAppList[i][6] != 'None' and (
                                BigRGTable[i][j][15] == "None" or (
                            dparser.parse(BigRGTable[i][j][15]) > dparser.parse(BigAppList[i][6]))) and BigAppList[i][
                            3] != "DATA DUMP PROVIDED" and BigAppList[i][3] != "WITHDRAWN BY APPLICANT":
                            if BigRGTable[k][l][2] != BigRGTable[i][j][2]:
                                BigAppRGCommentsList[i][j].append(["The location number of MPID " + str(
                                    BigRGTable[i][j][1]) + " was changed from " + str(
                                    BigRGTable[k][l][2]) + " in application " + str(BigAppList[k][0]) + " to " + str(
                                    BigRGTable[i][j][2]) + " in application " + str(BigAppList[i][0]) + ". ",
                                                                   str(BigRGTable[i][j][1]), str(BigAppList[i][0]),
                                                                   str(CurrAppFormatDict[BigRGTable[i][j][16]])])
                            if BigRGTable[k][l][3] != BigRGTable[i][j][3]:
                                BigAppRGCommentsList[i][j].append(["The facility location of MPID " + str(
                                    BigRGTable[i][j][1]) + " was changed from " + str(
                                    BigRGTable[k][l][3]) + " in application " + str(BigAppList[k][0]) + " to " + str(
                                    BigRGTable[i][j][3]) + " in application " + str(BigAppList[i][0]) + ". ",
                                                                   str(BigRGTable[i][j][1]), str(BigAppList[i][0]),
                                                                   str(CurrAppFormatDict[BigRGTable[i][j][16]])])
                            if BigRGTable[k][l][4] != BigRGTable[i][j][4]:
                                BigAppRGCommentsList[i][j].append(["The monitoring frequency of MPID " + str(
                                    BigRGTable[i][j][1]) + " was changed from " + str(
                                    BigRGTable[k][l][4]) + " in application " + str(BigAppList[k][0]) + " to " + str(
                                    BigRGTable[i][j][4]) + " in application " + str(BigAppList[i][0]) + ". ",
                                                                   str(BigRGTable[i][j][1]), str(BigAppList[i][0]),
                                                                   str(CurrAppFormatDict[BigRGTable[i][j][16]])])
                            if BigRGTable[k][l][5] != BigRGTable[i][j][5]:
                                BigAppRGCommentsList[i][j].append([
                                    "The elevation of MPID " + str(BigRGTable[i][j][1]) + " was changed from " + str(
                                        BigRGTable[k][l][5]) + " in application " + str(
                                        BigAppList[k][0]) + " to " + str(
                                        BigRGTable[i][j][5]) + " in application " + str(BigAppList[i][0]) + ". ",
                                    str(BigRGTable[i][j][1]), str(BigAppList[i][0]),
                                    str(CurrAppFormatDict[BigRGTable[i][j][16]])])
                            if BigRGTable[k][l][6] != BigRGTable[i][j][6]:
                                BigAppRGCommentsList[i][j].append([
                                    "The quadrangle of MPID " + str(BigRGTable[i][j][1]) + " was changed from " + str(
                                        BigRGTable[k][l][6]) + " in application " + str(
                                        BigAppList[k][0]) + " to " + str(
                                        BigRGTable[i][j][6]) + " in application " + str(BigAppList[i][0]) + ". ",
                                    str(BigRGTable[i][j][1]), str(BigAppList[i][0]),
                                    str(CurrAppFormatDict[BigRGTable[i][j][16]])])
                            if BigRGTable[k][l][7] != BigRGTable[i][j][7]:
                                BigAppRGCommentsList[i][j].append(["The northing coordinate of MPID " + str(
                                    BigRGTable[i][j][1]) + " was changed from " + str(
                                    BigRGTable[k][l][7]) + " in application " + str(BigAppList[k][0]) + " to " + str(
                                    BigRGTable[i][j][7]) + " in application " + str(BigAppList[i][0]) + ". ",
                                                                   str(BigRGTable[i][j][1]), str(BigAppList[i][0]),
                                                                   str(CurrAppFormatDict[BigRGTable[i][j][16]])])
                            if BigRGTable[k][l][8] != BigRGTable[i][j][8]:
                                BigAppRGCommentsList[i][j].append(["The easting coordinate of MPID " + str(
                                    BigRGTable[i][j][1]) + " was changed from " + str(
                                    BigRGTable[k][l][8]) + " in application " + str(BigAppList[k][0]) + " to " + str(
                                    BigRGTable[i][j][8]) + " in application " + str(BigAppList[i][0]) + ". ",
                                                                   str(BigRGTable[i][j][1]), str(BigAppList[i][0]),
                                                                   str(CurrAppFormatDict[BigRGTable[i][j][16]])])
                            if BigRGTable[k][l][9] != BigRGTable[i][j][9]:
                                BigAppRGCommentsList[i][j].append([
                                    "The status of MPID " + str(BigRGTable[i][j][1]) + " was changed from " + str(
                                        BigRGTable[k][l][9]) + " in application " + str(
                                        BigAppList[k][0]) + " to " + str(
                                        BigRGTable[i][j][9]) + " in application " + str(BigAppList[i][0]) + ". ",
                                    str(BigRGTable[i][j][1]), str(BigAppList[i][0]),
                                    str(CurrAppFormatDict[BigRGTable[i][j][16]])])
                            if BigRGTable[k][l][10] != BigRGTable[i][j][10]:
                                BigAppRGCommentsList[i][j].append([
                                    "The stream of MPID " + str(BigRGTable[i][j][1]) + " was changed from " + str(
                                        BigRGTable[k][l][10]) + " in application " + str(
                                        BigAppList[k][0]) + " to " + str(
                                        BigRGTable[i][j][10]) + " in application " + str(BigAppList[i][0]) + ". ",
                                    str(BigRGTable[i][j][1]), str(BigAppList[i][0]),
                                    str(CurrAppFormatDict[BigRGTable[i][j][16]])])
                            if BigRGTable[k][l][11] != BigRGTable[i][j][11]:
                                BigAppRGCommentsList[i][j].append(["The watershed acreage of MPID " + str(
                                    BigRGTable[i][j][1]) + " was changed from " + str(
                                    BigRGTable[k][l][11]) + " in application " + str(BigAppList[k][0]) + " to " + str(
                                    BigRGTable[i][j][11]) + " in application " + str(BigAppList[i][0]) + ". ",
                                                                   str(BigRGTable[i][j][1]), str(BigAppList[i][0]),
                                                                   str(CurrAppFormatDict[BigRGTable[i][j][16]])])
                            if BigRGTable[k][l][12] != BigRGTable[i][j][12]:
                                BigAppRGCommentsList[i][j].append(["The disturbed acreage of MPID " + str(
                                    BigRGTable[i][j][1]) + " was changed from " + str(
                                    BigRGTable[k][l][12]) + " in application " + str(BigAppList[k][0]) + " to " + str(
                                    BigRGTable[i][j][12]) + " in application " + str(BigAppList[i][0]) + ". ",
                                                                   str(BigRGTable[i][j][1]), str(BigAppList[i][0]),
                                                                   str(CurrAppFormatDict[BigRGTable[i][j][16]])])
                            Match = True
                        l += 1
                    k -= 1
                j += 1
            i -= 1
        mpHistoryPermitList.append(PermitDataList)
        mpHistoryAppList.append(BigAppList)
        mpHistoryNPDESList.append(BigNPDESTable)
        mpHistoryISList.append(BigISTable)
        mpHistoryGWList.append(BigGWTable)
        mpHistoryRGList.append(BigRGTable)
        mpHistoryNPDESComments.append(BigAppNPDESCommentsList)
        mpHistoryISComments.append(BigAppISCommentsList)
        mpHistoryGWComments.append(BigAppGWCommentsList)
        mpHistoryRGComments.append(BigAppRGCommentsList)
        mpSharedHistoryDict.append(MasterMPIDSharedPermitDict)
        mpPermitExists.append(True)
    else:
        mpHistoryPermitList.append([])
        mpHistoryAppList.append([])
        mpHistoryNPDESList.append([])
        mpHistoryISList.append([])
        mpHistoryGWList.append([])
        mpHistoryRGList.append([])
        mpHistoryNPDESComments.append([])
        mpHistoryISComments.append([])
        mpHistoryGWComments.append([])
        mpHistoryRGComments.append([])
        mpSharedHistoryDict.append([])
        mpPermitExists.append(False)
    WriteFileString('Finished Creating Permit History')
        

