##
# Copyright (c) 2021 Xilinx, Inc.
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and 
# associated documentation files (the "Software"), to deal in the Software without restriction, including 
# without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
# copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to 
# the following conditions: 
# 
# The above copyright notice and this permission notice shall be included in all copies or substantial 
# portions of the Software. 
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT 
# LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# 
#
#
##
#!/usr/bin/env python

import os, sys, inspect, importlib,string,re
from backend import ysocket
from backend import header
import json
import time
import threading
from api import settings
from pymongo import MongoClient
from multiprocessing import Process
import datetime
from backend import *
# from backend import sender
# from backend import receiver
from backend import rabbitmq_config
from backend import performanceview

currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
apidir = os.path.join(parentdir, "api")
backdir = os.path.join(parentdir, "backend")
client = ysocket.SocketClient('', '', '')
performancethread = []  # threading.Thread(target = getperformance, args=())
dbdump = []
configarr = []

def isHex(val):
    if (val.startswith("0x") or val.startswith("0X")) and set(val[2:]).issubset(string.hexdigits):
        return True
    else:
        return False

def connecttoserver(hostname, port, active_user):
    global performancethread, dbdump
    client = ysocket.SocketClient(hostname, port, active_user)
    if (client):
        if (not client.connect()):
            ysocket.boardname = hostname
            ysocket.xsdbport = port
            # dbdumpthread = threading.Thread(target=receiver.recvData, args=(active_user,))
            # dbdumpthread.deamon = True
            # dbdumpthread.start()
            return client
        else:
            return 0


def disconnectserver(client):
    global performancethread, dbdump
    # sender.closeconnection()
    client.connectionstatus = 0
    ysocket.numberofnps = 0
    time.sleep(1)
    client.disconnect()
    print("socket disconnected")
    ysocket.boardname = ""
    ysocket.xsdbport = ""
    return 1

def configaws(client):
    configFile = open(os.path.join(apidir, "%s" % header.ConfigAWS), "r")
    for line in configFile:
        if ((line[0] != "#") and (len(line) > 2)):
            resp = client.send_msg(line, "ConfigAWS")
            print("resp",resp)
    configFile.close()

def getvoltage(dataarr,resp,key_name):
    print(dataarr,"\n")
    print("resp",resp)
    exponent_mask = int("0x60000",16)
    format_mask = int("0x10000",16)
    mantissa_mask = int("0xFFFF",16)
    for i in range(len(dataarr)):
        temp = dataarr[i].split(":")
        if len(temp) == 2:
            my_addr_h = "0x"+temp[0].strip()
            my_number = int(temp[1].strip(),16)
            exponent = ((my_number & exponent_mask) >> 17) - 16
            format_m = (my_number & format_mask)   >> 16
            mantissa = my_number & mantissa_mask
            if format_m & ((mantissa) >> 15):
                my_decimal = (mantissa * pow(2,exponent)) - 1
            else:
                my_decimal = mantissa * pow(2,exponent)
            my_decimal_5f = float("{0:.5f}".format(my_decimal))
            status = True
            if len(resp)<14:
                for j in range(len(resp)):
                    if resp[j]["name"] == header.AWS_lookup[my_addr_h]:
                        resp[j][key_name] = my_decimal_5f
                        status = False
                        break
                    else:
                        status = True
                if status:
                    obj = {}
                    obj["name"] = header.AWS_lookup[my_addr_h]
                    obj[key_name] = my_decimal_5f
                    resp.append(obj)
            else:
                resp[i][key_name] = my_decimal_5f
                if key_name not in ["min", "max"]:
                    resp[i][key_name+"_per"] = my_decimal_5f*100
    # print("resp",resp)
    return resp
def readaws(client):
    resp = []
    temp = runcommandfromui("mrd 0xF1271040 10","ReadAWS",client)
    resp = getvoltage(temp,resp,"value")
    temp = runcommandfromui("mrd 0xF1271340 10","ReadAWS",client)
    resp = getvoltage(temp,resp,"min")
    temp = runcommandfromui("mrd 0xF1271640 10","ReadAWS",client)
    resp = getvoltage(temp,resp,"max")
    # print(resp)
    for i in range(len(resp)):
        resp[i]["value_per"] = str(resp[i]["value"]/(resp[i]["min"]+resp[i]["max"])*100) + "%"
        resp[i]["threshold"] = 0
        resp[i]["threshold_per"] = str(0)+"%"
    return resp
    
def readaws_old(client):
    resp = []
    temp = runcommandfromui("mrd 0xF1271040 14","ReadAWS",client)
    resp = getvoltage(temp,resp,"value")
    temp = runcommandfromui("mrd 0xF1271340 14","ReadAWS",client)
    resp = getvoltage(temp,resp,"min")
    temp = runcommandfromui("mrd 0xF1271640 14","ReadAWS",client)
    resp = getvoltage(temp,resp,"max")
    # print(resp)
    for i in range(len(resp)):
        resp[i]["value_per"] = str(resp[i]["value"]/(resp[i]["min"]+resp[i]["max"])*100) + "%"
        resp[i]["threshold"] = 0
        resp[i]["threshold_per"] = str(0)+"%"
    return resp


def configureapmmonitors(client):
    # global client
    configFile = open(os.path.join(apidir, "%s" % header.CONF_APM), "r")
    for line in configFile:
        if ((line[0] != "#") and (len(line) > 2)):
            resp = client.send_msg(line, "APM_PERF")
    configFile.close()
    print("APM perfmon config done")


def configuredcmonitors(client):
    # global client
    print("dc perfmon config start")
    configFile = open(os.path.join(apidir, "%s" % header.CONF_DC_PERF), "r")
    for line in configFile:
        if ((line[0] != "#") and (len(line) > 2)):
            resp = client.send_msg(line, "DC_PERF")
    configFile.close()
    print("dc perfmon config done")

def configuremonitors0(client):
    print("counter config 0 start")
    configFile = open(os.path.join(apidir, "%s" % header.CONF_DDR_NOC_0), "r")
    for line in configFile:
        if ((line[0] != "#") and (len(line) > 2)):
            resp = client.send_msg(line, "DDR_NOC_0_PERF")
    configFile.close()
    print("counter config 0 done")

def configuremonitors1(client):
    print("counter config 1 start")
    configFile = open(os.path.join(apidir, "%s" % header.CONF_DDR_NOC_1), "r")
    for line in configFile:
        if ((line[0] != "#") and (len(line) > 2)):
            resp = client.send_msg(line, "DDR_NOC_1_PERF")
    configFile.close()
    print("counter config 1 done")

def configuremonitors2(client):
    print("counter config 2 start")
    configFile = open(os.path.join(apidir, "%s" % header.CONF_DDR_NOC_2), "r")
    for line in configFile:
        if ((line[0] != "#") and (len(line) > 2)):
            resp = client.send_msg(line, "DDR_NOC_2_PERF")
    configFile.close()
    print("counter config 2 done")

def configuremonitors3(client):
    print("counter config 3 start")
    configFile = open(os.path.join(apidir, "%s" % header.CONF_DDR_NOC_3), "r")
    for line in configFile:
        if ((line[0] != "#") and (len(line) > 2)):
            resp = client.send_msg(line, "DDR_NOC_3_PERF")
    configFile.close()
    print("counter config 3 done")

def resetLpdCounters(client):
    configFile = open(os.path.join(apidir, "%s" % header.RESET_LPD_COUNTERS), "r")
    for line in configFile:
        if ((line[0] != "#") and (len(line) > 2)):
            resp = client.send_msg(line, "LPD_PERF")
    configFile.close()

def configurelpdCounters(client):
    # global client
    print("lpd counter config start")
    resetLpdCounters(client)
    configFile = open(os.path.join(apidir, "%s" % header.PS_PMC_RPU_AXI0), "r")
    for line in configFile:
        if ((line[0] != "#") and (len(line) > 2)):
            resp = client.send_msg(line, "LPD_PERF")
    configFile.close()
    configFile = open(os.path.join(apidir, "%s" % header.INTLPD_AFIFSLPD_AXI), "r")
    for line in configFile:
        if ((line[0] != "#") and (len(line) > 2)):
            resp = client.send_msg(line, "LPD_PERF")
    configFile.close()
    configFile = open(os.path.join(apidir, "%s" % header.INTLPD_OCM_AXI), "r")
    for line in configFile:
        if ((line[0] != "#") and (len(line) > 2)):
            resp = client.send_msg(line, "LPD_PERF")
    configFile.close()
    configFile = open(os.path.join(apidir, "%s" % header.INTLPD_INTFPD_AXI), "r")
    for line in configFile:
        if ((line[0] != "#") and (len(line) > 2)):
            resp = client.send_msg(line, "LPD_PERF")
    configFile.close()
    configFile = open(os.path.join(apidir, "%s" % header.XPPU), "r")
    for line in configFile:
        if ((line[0] != "#") and (len(line) > 2)):
            resp = client.send_msg(line, "LPD_PERF")
    configFile.close()
    print("lpd counter config done")
    return 0

def resetFpdCounters(client):
    configFile = open(os.path.join(apidir, "%s" % header.RESET_FPD_COUNTERS), "r")
    for line in configFile:
        if ((line[0] != "#") and (len(line) > 2)):
            resp = client.send_msg(line, "FPD_PERF")
    configFile.close()

def configurefpdCounters(client):
    # global client
    print("fpd counter config start")
    resetFpdCounters(client)
    configFile = open(os.path.join(apidir, "%s" % header.FPD_SLAVE), "r")
    for line in configFile:
        if ((line[0] != "#") and (len(line) > 2)):
            resp = client.send_msg(line, "FPD_PERF")
    configFile.close()
    configFile = open(os.path.join(apidir, "%s" % header.INTFLD_INTLPD_OCM), "r")
    for line in configFile:
        if ((line[0] != "#") and (len(line) > 2)):
            resp = client.send_msg(line, "FPD_PERF")
    configFile.close()
    configFile = open(os.path.join(apidir, "%s" % header.INTFPD_INTLPD_LPD_SLAVE), "r")
    for line in configFile:
        if ((line[0] != "#") and (len(line) > 2)):
            resp = client.send_msg(line, "FPD_PERF")
    configFile.close()
    configFile = open(os.path.join(apidir, "%s" % header.INTFPD_INTLPD_PCIE), "r")
    for line in configFile:
        if ((line[0] != "#") and (len(line) > 2)):
            resp = client.send_msg(line, "FPD_PERF")
    configFile.close()
    configFile = open(os.path.join(apidir, "%s" % header.PS_FPD_APM), "r")
    for line in configFile:
        if ((line[0] != "#") and (len(line) > 2)):
            resp = client.send_msg(line, "FPD_PERF")
    configFile.close()
    configFile = open(os.path.join(apidir, "%s" % header.PS_NOC_NCI_AXI0), "r")
    for line in configFile:
        if ((line[0] != "#") and (len(line) > 2)):
            resp = client.send_msg(line, "FPD_PERF")
    configFile.close()
    configFile = open(os.path.join(apidir, "%s" % header.PS_NOC_NCI_AXI1), "r")
    for line in configFile:
        if ((line[0] != "#") and (len(line) > 2)):
            resp = client.send_msg(line, "FPD_PERF")
    configFile.close()
    print("fpd counter config done")


def configurecpmcounters(client):
    # global client
    print("cpm counter config start")
    configFile = open(os.path.join(apidir, "%s" % header.CPM_AXI0), "r")
    for line in configFile:
        if ((line[0] != "#") and (len(line) > 2)):
            resp = client.send_msg(line, "CPM_PERF")
    configFile.close()
    configFile = open(os.path.join(apidir, "%s" % header.CPM_AXI1), "r")
    for line in configFile:
        if ((line[0] != "#") and (len(line) > 2)):
            resp = client.send_msg(line, "CPM_PERF")
    configFile.close()
    configFile = open(os.path.join(apidir, "%s" % header.CPM_PCIe), "r")
    for line in configFile:
        if ((line[0] != "#") and (len(line) > 2)):
            resp = client.send_msg(line, "CPM_PERF")
    configFile.close()
    print("cpm counter config done")

def resetPmcCounters(client):
    configFile = open(os.path.join(apidir, "%s" % header.RESET_PMC_COUNTERS), "r")
    for line in configFile:
        if ((line[0] != "#") and (len(line) > 2)):
            resp = client.send_msg(line, "PMC_PERF")
    configFile.close()

def configurepmccounters(client):
    # global client
    print("pmc counter config start")
    resetPmcCounters(client)
    configFile = open(os.path.join(apidir, "%s" % header.PMC_NOC_AXI), "r")
    for line in configFile:
        if ((line[0] != "#") and (len(line) > 2)):
            resp = client.send_msg(line, "PMC_PERF")
    configFile.close()
    print("pmc counter config done")


def getperformance(client="", active_user="", conf=""):
    for j in range(len(conf)):
        conf_found_status = False
        for i in range(len(rabbitmq_config.queues)):
            if rabbitmq_config.queues[i]["config"]["tabname"].lower() == conf[j]["displayname"].lower():
                conf_found_status = True
                delay = conf[j].get("delay",0.1)
                if conf[j]["permission"]:
                    activethreadstatus = False
                    threadname = rabbitmq_config.queues[i]["config"]["tabname"] + "_" + active_user
                    for threads in performancethread:
                        if threadname == threads["threadname"]:
                            activethreadstatus = True
                            conf[j]["threadname"] = threadname
                            # threads["dependency"].append("performance")
                            break
                        else:
                            activethreadstatus = False
                    if not activethreadstatus:
                        # eval(rabbitmq_config.queues[i]["config"]["configuration"])(client)
                        if "configuration" in rabbitmq_config.queues[i]["config"]:
                            print("configuration found", rabbitmq_config.queues[i]["config"]["configuration"])
                            eval(rabbitmq_config.queues[i]["config"]["configuration"])(client)

                            configarr.append({"configuration":rabbitmq_config.queues[i]["config"]["configuration"],"board":client.host, "port":client.port,"uid":active_user,"threadname":rabbitmq_config.queues[i]["config"]["tabname"] + "_" + active_user})

                        try:
                            newthread = performanceview.PikaClient(threadname, client, active_user,
                                                               rabbitmq_config.queues[i]["config"]["tabname"],
                                                               rabbitmq_config.queues[i]["config"]["method"],
                                                               delay, conf[j]["status"],
                                                               rabbitmq_config.queues[i]["config"]["logfile"])
                            # performancethread.append({"threadname": newthread.threadname, "thread": newthread,"dependency":["performance"]})
                            performancethread.append({"threadname": newthread.threadname, "thread": newthread})
                            newthread.createthread()
                            conf[j]["threadname"] = newthread.threadname
                        except Exception as e:
                            print("error---------->>>", str(e))
                            conf[j]["error"] = "Thread not created"
        if not conf_found_status:
            conf[j]["error"] = "Performance not found"
    # dbdumpthread = threading.Thread(target=receiver.recvData, args=(active_user,))
    # dbdumpthread.deamon = True
    # dbdumpthread.start()
    return conf

def getoverlay(client="", active_user="", conf=""):
    print("client ", client, "active_user", active_user, "conf", conf)
    for length in range(len(conf)):
        overlay = {"name": "overlay",
                   "config": {
                       "method": "",
                       "dbname": "overlaydb",
                       "tabname": "overlay",
                       "logfile": "overlay",
                   }
                   }
        #[{"tab":"overlay","performance":[{"subtab":"PMC","plot":["PMC_0","PMC_1"]},{"subtab":"DDRMC_0","plot":["NSU_1","NSU_2"]}],"uid":"pranayd","threadname":"overlay_1_pranayd"}]
        if "performance" in conf[length] and len(conf[length]["performance"])>0:
            for k in range(len(conf[length]["performance"])):
                for i in range(len(rabbitmq_config.queues)):
                    if rabbitmq_config.queues[i]["name"].lower() == conf[length]["performance"][k]["subtab"].lower():
                        # subthreadname = rabbitmq_config.queues[i]["config"]["tabname"] + "_" + active_user
                        activethreadstatus= False
                        for configure in configarr:
                            if (configure["configuration"] == rabbitmq_config.queues[i]["config"]["configuration"]) and (configure["board"] == client.host) and (configure["port"] == client.port) and (configure.uid == active_user):
                                print("thread found----", threads)
                                activethreadstatus = True
                                # threads["dependency"].append("overlay")
                                break
                            else:
                                activethreadstatus = False
                        if not activethreadstatus:
                            eval(rabbitmq_config.queues[i]["config"]["configuration"])(client) #writing configuration
                            configarr.append({"configuration":rabbitmq_config.queues[i]["config"]["configuration"],"board":client.host, "port":client.port,"uid":active_user})
                        overlay["config"]["method"] += rabbitmq_config.queues[i]["config"]["method"]+"/" #all read method
        threadname = conf[length]["threadname"]
        try:
            newthread = performanceview.PikaClient(threadname, client, active_user,
                                                   overlay["config"]["tabname"],
                                                   overlay["config"]["method"],
                                                   0.1, True,
                                                   overlay["config"]["logfile"],tempobj=conf[length])
            performancethread.append({"threadname": newthread.threadname, "thread": newthread})
            newthread.createthread()
            conf[length]["threadname"] = newthread.threadname
            conf[length]["thread_createtime"] = newthread.thread_createtime
        except Exception as e:
            print("error---------->>>", str(e))
            conf[length]["error"] = "Thread not created"
        print("conf------>>>",conf)
    return conf


def getperf(num, client):
    mrdNoc = open(os.path.join(apidir, str("perf_ddr_noc_" + str(num) + ".tcl")), "r")
    perfArr = []
    timenow = datetime.datetime.now()
    for line in mrdNoc:
        line = line.replace("\n", "")
        keys = line.split(",")
        perfmonData = {}
        perfmonData["accumulatedlatency"] = getcommandresponse(
            ("mrd 0x%s\n" % str("%x" % (int(keys[5], 16) + int("0", 16)))), "perf_ddr_noc", client)
        perfmonData["burstcount"] = getcommandresponse(
            ("mrd 0x%s\n" % str("%x" % (int(keys[5], 16) + int("4", 16)))), "perf_ddr_noc", client)
        perfmonData["transactioncount"] = getcommandresponse(
            ("mrd 0x%s\n" % str("%x" % (int(keys[5], 16) + int("8", 16)))), "perf_ddr_noc", client)
        perfmonData["module"] = keys[0]
        perfmonData["submodule"] = keys[1]
        perfmonData["monitor"] = keys[2]
        perfmonData["time"] = timenow
        perfArr.append(perfmonData)
    mongoClient = MongoClient(settings.MONGO_URI)
    db = mongoClient.xregv
    db.perfmon_1.insert_one(perfArr)
    mrdNoc.close()


def getlpdcounters(client):
    readcounters = open(os.path.join(apidir, "%s" % header.READ_LPD_COUNTERS), "r")
    counterArr = []
    timenow = datetime.datetime.now()
    for line in readcounters:
        line = line.replace("\n", "")
        keys = line.split(" ")
        counterData = {}
        counterData["time"] = timenow
        if ((len(keys) >= 3) and (line[0] != '#')):
            counterData["requesttype"] = str(keys[0])
            counterData["value"] = getcommandresponse(("mrd %s\n" % str(keys[1])), "perf_LPD", client)
            counterData["displayname"] = str(keys[2])
            counterArr.append(counterData)
    mongoClient = MongoClient(settings.MONGO_URI)
    db = mongoClient.xregv
    db.lpdcounters.insert_one(counterArr)
    readcounters.close()


def getfpdcounters(client):
    readcounters = open(os.path.join(apidir, "%s" % header.READ_FPD_COUNTERS), "r")
    counterArr = []
    timenow = datetime.datetime.now()
    for line in readcounters:
        line = line.replace("\n", "")
        keys = line.split(" ")
        counterData = {}
        counterData["time"] = timenow
        if ((len(keys) >= 3) and (line[0] != '#')):
            counterData["requesttype"] = str(keys[0])
            counterData["value"] = getcommandresponse(("mrd %s\n" % str(keys[1])), "perf_FPD", client)
            counterData["displayname"] = str(keys[2])
            counterArr.append(counterData)
    mongoClient = MongoClient(settings.MONGO_URI)
    db = mongoClient.xregv
    db.fpdcounters.insert_one(counterArr)
    readcounters.close()


def getcpmcounters(client):
    readcounters = open(os.path.join(apidir, "%s" % header.READ_CPM_COUNTERS), "r")
    counterArr = []
    timenow = datetime.datetime.now()
    for line in readcounters:
        line = line.replace("\n", "")
        keys = line.split(" ")
        counterData = {}
        counterData["time"] = timenow
        if ((len(keys) >= 3) and (line[0] != '#')):
            counterData["requesttype"] = str(keys[0])
            counterData["value"] = getcommandresponse(("mrd %s\n" % str(keys[1])), "perf_CPM", client)
            counterData["displayname"] = str(keys[2])
            counterArr.append(counterData)
    mongoClient = MongoClient(settings.MONGO_URI)
    db = mongoClient.xregv
    db.cpmcounters.insert_one(counterArr)
    readcounters.close()


def getpmccounters(client):
    readcounters = open(os.path.join(apidir, "%s" % header.READ_PMC_COUNTERS), "r")
    counterArr = []
    timenow = datetime.datetime.now()
    for line in readcounters:
        line = line.replace("\n", "")
        keys = line.split(" ")
        counterData = {}
        counterData["time"] = timenow
        if ((len(keys) >= 3) and (line[0] != '#')):
            counterData["requesttype"] = str(keys[0])
            counterData["value"] = getcommandresponse(("mrd %s\n" % str(keys[1])), "perf_PMC", client)
            counterData["displayname"] = str(keys[2])
            counterArr.append(counterData)
    mongoClient = MongoClient(settings.MONGO_URI)
    db = mongoClient.xregv
    db.pmccounters.insert_one(counterArr)
    readcounters.close()


def getcommandresponse(command, cmdsrc, client, target="",beam_target=""):
    resp = str(client.send_msg(command, cmdsrc, target,beam_target))
    if ((resp.find("error") == -1) and ("error" != resp) and (len(resp) > 1)):
        # data = resp.replace("okay ", "").split(':')
        data = re.sub('^["error","okay"]*', '', resp)
        data = data.split(':')
        if len(data) >= 2:
            return " ".join(((data[1]).replace("\\r", "").replace("\\n", "").replace("\\", "").replace("\'", "")).split())
    resp = re.sub('^["error","okay"]*', '', resp)
    return " ".join((resp.replace("\\r", "").replace("\\n", "").replace("\\", "").replace("\'", "")).split())


def runcommandfromui(command, cmdsrc, client, target="",beam_target=""):
    # global client
    resp = str(client.send_msg(command + "\n", cmdsrc, target,beam_target))
    if (("error" != resp) and (len(resp) > 1)):
        data = re.sub('^["error","okay"]*', '', resp)
        data = (" ".join((data.replace("\\r", "").replace("\'", "")).split())).split("\\n")
        for x in range(0, len(data)):
            data[x] = re.sub('^["error","okay"]*', '', data[x])
            data[x] = " ".join((data[x].replace("\\", "").replace("\"", "")).split())
        return data
    else:
        return 0


def getregistervalue(address, client, target="",beam_target=""):
    return getcommandresponse(("mrd %s\n" % address), "getRegister", client, target,beam_target)


def rundicommands(command, cmdsrc, client, target="",beam_target="", is_tcl_script=False):
    # global client
    resp = str(client.di_send_msg(command + "\n", cmdsrc, is_tcl_script, target,beam_target))
    if (("error" != resp) and (len(resp) > 1)):
        data = re.sub('^["error","okay"]*', '', resp)
        data = (" ".join((data.replace("\\r", "").replace("\'", "")).split())).split("\\n")
        for x in range(0, len(data)):
            data[x] = re.sub('^["error","okay"]*', '', data[x])
            data[x] = " ".join((data[x].replace("\\", "").replace("\"", "")).split())
        return data
    else:
        return 0
