Title: Code Optimization, Structuring, and Refactoring Assistance

Instructions:

Please assist in optimizing, structuring, and refactoring the following code to enhance its performance, readability, and maintainability. Follow these guidelines:

Performance Optimization:
Identify and improve any inefficient code segments.
Optimize algorithms and data structures for better performance.
Reduce computational complexity where possible.
Code Structuring:
Organize the code into logical sections or modules.
Ensure proper use of functions/classes to encapsulate functionality.
Apply appropriate design patterns if beneficial.
Refactoring:
Simplify complex or redundant code.
Improve variable and function names for clarity.
Remove any dead or unused code.
Best Practices and Standards:
Adhere to the coding conventions of the language used.
Ensure the code is clean, well-documented, and easy to understand.
Maintain or improve security and error-handling mechanisms.
Documentation:
Add or update comments and docstrings where necessary.
Provide a brief explanation of significant changes or optimizations made.
Code to Optimize:

```lua
local imgui = require 'mimgui'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8

local new = imgui.new
packet = {}
local renderWindow = new.bool(false)
local selectMenu = new.bool(false)
local count = 1
local speed = new.int(50)
local debug = new.bool(false)
imgui.OnInitialize(function()
    imgui.GetIO().IniFilename = nil
end)
local fuel = new.bool(false)
local gm = new.bool(false)
local alock = new.bool(false)
local colision = new.bool(false)
work = {
    {"jeffersonwork1", 5},
    {"lswork1", 7},
    {"lvwork1", 9},
    {"sfwork1", 13},
}
rout = "None"
button = false
local newFrame = imgui.OnFrame(
    function() return renderWindow[0] end,
    function(player)
        local resX, resY = getScreenResolution()
        local sizeX, sizeY = 300, 150
        imgui.SetNextWindowPos(imgui.ImVec2(resX / 2, resY / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(sizeX, sizeY), imgui.Cond.FirstUseEver)
        imgui.Begin('Main Window', renderWindow, imgui.WindowFlags.NoResize +  imgui.WindowFlags.NoScrollbar)
            imgui.SliderInt('speed', speed, 1, 100)
            imgui.Text("Packet: "..count) imgui.SameLine() 
            imgui.Text("Select route: "..rout)
            imgui.Checkbox('debug', debug) imgui.SameLine()
            if imgui.Button('cheats', imgui.ImVec2(-1, 20)) then
                selectMenu[0] = not selectMenu[0]
            end
            imgui.Text(u8("Работаем в: "..bolka)) imgui.SameLine() if imgui.Button(u8'распознать') then sampSendChat("/stats") end
            if sanfierro then
                if imgui.Button("sfwork1") then
                    count = 1
                    button = false
                    rout = "sfwork1"
                    getRoute("sfwork1")
                end
            end
            if jefferson then
                if imgui.Button("jeffersonwork1") then
                    count = 1
                    button = false
                    rout = "jeffersonwork1"
                    getRoute("jeffersonwork1")
                end
            end
            if lasventuras then
                if imgui.Button("lvwork1") then
                    count = 1
                    button = false
                    rout = "lvwork1"
                    getRoute("lvwork1")
                end
            end
            if lossantos then
                if imgui.Button("lswork1") then
                    count = 1
                    button = false
                    rout = "lswork1"
                    getRoute("lswork1")
                end
            end
            imgui.SameLine()
            if imgui.Button('start', imgui.ImVec2(100, 20)) then
                click = true
                checkInt()
                if button then
                    setCharCoordinates(1,packet[count].x, packet[count].y, packet[count].z)
                    blocksync = false
                else
                    blocksync = true
                end
                if packet[1] ~= nil then
                    button = not button
                    click = true
                    checkInt()
                else
                    sampAddChatMessage('Select Route', -1)
                end
            end
            imgui.SameLine()
            if imgui.Button('STOP', imgui.ImVec2(100, 20)) then
                if button then
                    setCharCoordinates(1,packet[count].x, packet[count].y, packet[count].z)
                    blocksync = false
                    thisScript():reload()
                end
            end
        imgui.End()
    end
)

imgui.OnFrame(
    function() return selectMenu[0] end,
    function(player)
        local resX, resY = getScreenResolution()
        local sizeX, sizeY = 150, 130
        imgui.SetNextWindowPos(imgui.ImVec2(resX / 2, resY / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(sizeX, sizeY), imgui.Cond.FirstUseEver)
        imgui.Begin('cheat', selectMenu, imgui.WindowFlags.NoResize +  imgui.WindowFlags.NoScrollbar )
            imgui.Checkbox(u8"ГМ", gm)
            imgui.Checkbox(u8"авто закрытие", alock)
            imgui.Checkbox(u8"Заправка", fuel)
            imgui.Checkbox(u8"коллизия", colision)
        imgui.End()
    end
)

function main()
    while not isSampAvailable() do wait(0) end
    sampRegisterChatCommand('med', function()
        renderWindow[0] = not renderWindow[0]
    end)
    lua_thread.create(sendSync)
    while true do
        wait(0)
        if isCharInAnyCar(1) then
            if gm[0] then
                setCarProofs(storeCarCharIsInNoSave(1), true, true, true, true, true)
            else
                setCarProofs(storeCarCharIsInNoSave(1), false, false, false, false, false)
            end
        end
        for i, v in ipairs(getAllVehicles()) do
            if isCharInAnyCar(1) then
                if v ~= storeCarCharIsInNoSave(1) then
                    if colision[0] then
                        setCarCollision(v, false)
                    else
                        setCarCollision(v, true)
                    end
                end
            end
        end
    end
end

function sendSync()
    while true do wait(speed[0])
        if button and packet[1] ~= nil then
            local x, y, z = getCharCoordinates(1)
            if getDistanceBetweenCoords3d(packet[count].x, packet[count].y, packet[count].z, x, y, z) > 10 and count ==  1 then
                sampAddChatMessage('Далеко как то...', -1)
                button = false
                goto skip
            end
            if isCharInAnyCar(1) and packet[count].packetId == 200 then -- veh
                local data = samp_create_sync_data("vehicle")
                data.vehicleId = select(2,sampGetVehicleIdByCarHandle(storeCarCharIsInNoSave(PLAYER_PED)))
                data.leftRightKeys = packet[count].lr
                data.upDownKeys = packet[count].ud
                data.keysData = packet[count].keys
                data.quaternion = {packet[count].qw, packet[count].qx, packet[count].qy, packet[count].qz}
                data.position = {packet[count].x, packet[count].y, packet[count].z}
                data.moveSpeed = {packet[count].sx, packet[count].sy, packet[count].sz}
                data.send()
            elseif not isCharInAnyCar(1) and packet[count].packetId == 207 then
                local data = samp_create_sync_data("player")
                data.leftRightKeys = packet[count].lr
                data.upDownKeys = packet[count].ud
                data.keysData = packet[count].keys
                data.quaternion = {packet[count].qw, packet[count].qx, packet[count].qy, packet[count].qz}
                data.position = {packet[count].x, packet[count].y, packet[count].z}
                data.moveSpeed = {packet[count].sx, packet[count].sy, packet[count].sz}
                data.send()
            elseif packet[count].packetId == 203 then
                print("SKIp - "..count.. "PACKET")
            end
            if debug[0] then
                setCharCoordinates(1,packet[count].x, packet[count].y, packet[count].z-1)
                if isCharInAnyCar(1) then
                    setVehicleQuaternion(storeCarCharIsInNoSave(1),packet[count].qx, packet[count].qy, packet[count].qz,-(packet[count].qw))
                else
                    setCharQuaternion(1,-(packet[count].qx), packet[count].qy, packet[count].qz,packet[count].qw)
                end
            end
            if count+2 == #packet then
                
                button = false
                setCharCoordinates(1,packet[count].x, packet[count].y, packet[count].z)
                if isCharInAnyCar(1) then
                    local bx, by = getCharCoordinates(1)
                    local angle = getHeadingFromVector2d((packet[count].x - bx), (packet[count].y - by))
                    setCarHeading(storeCarCharIsInNoSave(1),angle)
                else
                    setCharQuaternion(1,packet[count].qx, packet[count].qy, packet[count].qz,packet[count].qw)
                end
                packet = {}
                count = 1
                print("STOP RACE")
                
                if rout:find("sex") then
                    if not isCharInAnyCar(1) then
                        if getActiveInterior() == 0 then
                            lua_thread.create(function()
                            seatcar = true
                            walk = true
                            wait(100)
                            posadka()
                            end)
                        end
                    end
                end
            else
                DrawCube(packet[count].x, packet[count].y, packet[count].z)
                count = count + 1
            end
        end
        ::skip::
    end
end
function DrawCube(x,y,z)
	if isPointOnScreen(x,y,z) then
		x = x-1
		y = y-1
		local xx,yy = convert3DCoordsToScreen(x,y,z)
		local xxx,yyy = convert3DCoordsToScreen(x+2,y,z)
		renderDrawLine(xx,yy,xxx,yyy,3,-1)
		local xx,yy = convert3DCoordsToScreen(x+2,y,z)
		local xxx,yyy = convert3DCoordsToScreen(x+2,y,z-2)
		renderDrawLine(xx,yy,xxx,yyy,3,-1)
		local xx,yy = convert3DCoordsToScreen(x,y,z)
		local xxx,yyy = convert3DCoordsToScreen(x,y,z-2)
		renderDrawLine(xx,yy,xxx,yyy,3,-1)
		local xx,yy = convert3DCoordsToScreen(x,y,z-2)
		local xxx,yyy = convert3DCoordsToScreen(x+2,y,z-2)
		renderDrawLine(xx,yy,xxx,yyy,3,-1)
		local xx,yy = convert3DCoordsToScreen(x,y,z)
		local xxx,yyy = convert3DCoordsToScreen(x,y+2,z)
		renderDrawLine(xx,yy,xxx,yyy,3,-1)
		local xx,yy = convert3DCoordsToScreen(x,y+2,z)
		local xxx,yyy = convert3DCoordsToScreen(x,y+2,z-2)
		renderDrawLine(xx,yy,xxx,yyy,3,-1)
		local xx,yy = convert3DCoordsToScreen(x,y+2,z-2)
		local xxx,yyy = convert3DCoordsToScreen(x,y,z-2)
		renderDrawLine(xx,yy,xxx,yyy,3,-1)
		local xx,yy = convert3DCoordsToScreen(x+2,y+2,z)
		local xxx,yyy = convert3DCoordsToScreen(x+2,y+2,z-2)
		renderDrawLine(xx,yy,xxx,yyy,3,-1)
		local xx,yy = convert3DCoordsToScreen(x+2,y,z)
		local xxx,yyy = convert3DCoordsToScreen(x+2,y+2,z)
		renderDrawLine(xx,yy,xxx,yyy,3,-1)
		local xx,yy = convert3DCoordsToScreen(x+2,y+2,z-2)
		local xxx,yyy = convert3DCoordsToScreen(x,y+2,z-2)
		renderDrawLine(xx,yy,xxx,yyy,3,-1)
		local xx,yy = convert3DCoordsToScreen(x+2,y+2,z-2)
		local xxx,yyy = convert3DCoordsToScreen(x+2,y,z-2)
		renderDrawLine(xx,yy,xxx,yyy,3,-1)
		local xx,yy = convert3DCoordsToScreen(x+2,y+2,z)
		local xxx,yyy = convert3DCoordsToScreen(x,y+2,z)
		renderDrawLine(xx,yy,xxx,yyy,3,-1)
	end
end
local ev = require('lib.samp.events')
sanfierro = false
lossantos = false
lasventuras = false
jefferson = false
function ev.onSendVehicleSync(data)
    if button or blocksync then return false end
end
function ev.onSendPlayerSync(data)
    if button or blocksync then return false end
end
nick = function()
    return sampGetPlayerNickname(select(2, sampGetPlayerIdByCharHandle(1)))
end

function ev.onShowTextDraw(id, data)
	local posx, posy = math.floor(data.position.x), math.floor(data.position.y)
	if posx == 320 and posy == 199 then
		lua_thread.create(function()
			wait(500)
			sampSendClickTextdraw(id)
        end)
    end  
	if data.text == "FILL" then
		lua_thread.create(function()
			wait(1200)
			sampSendClickTextdraw(id)
		end)
	end
end

function ev.onDisplayGameText(style, time, text)
	if text:find("~w~~n~~n~~n~~n~~n~~n~~n~~n~~n~~n~CAR~r~ LOCK~n~/olock") then
		if not isCharInAnyCar(1) then
			lua_thread.create(function()
				wait(500)
                if alock[0] then
				    sampSendChat("/lock")
                end
			end)
		end
	end
	if text:find("UNLOCK") then
		if isCharInAnyCar(1) then
			lua_thread.create(function()
			wait(1500)
                if alock[0] then
                    sampSendChat("/lock")
                end
			end)
		end
	end
	if text:find("hungry") then
		if settings.autoeat then
			lua_thread.create(function()
				wait(math.random(300, 1500))
				sampSendChat("/cheeps")
			end)
		end
	end
end
function angleToQuaternion(angle)
    local a = (math.rad(angle) / 2) 
    local qz = -(math.sin(a))
    local qw = math.cos(a)    
    return qz, qw 
end

function runToPoint(tox, toy)
    local x, y, z = getCharCoordinates(PLAYER_PED)
    local angle = getHeadingFromVector2d(tox - x, toy - y)
    local xAngle = math.random(-50, 50)/100
    setCameraPositionUnfixed(xAngle, math.rad(angle - 90))
    stopRun = false
    while getDistanceBetweenCoords2d(x, y, tox, toy) > 2.5 do
        setGameKeyState(1, -255)
        --setGameKeyState(16, 1)
        wait(1)
        x, y, z = getCharCoordinates(PLAYER_PED)
        angle = getHeadingFromVector2d(tox - x, toy - y)
        setCameraPositionUnfixed(xAngle, math.rad(angle - 90))
        if stopRun then
            stopRun = false
            break
        end
    end
end

function posadka()
	lua_thread.create(function()
        while true do wait(1000)
            if getActiveInterior() == 0 then
                for q, w in pairs(getAllVehicles()) do
                    res, q = sampGetVehicleIdByCarHandle(w)
                    if getCarModel(w) == 416 and res then
                        if seatcar then
                            local x, y, z = getCharCoordinates(1)
                            local xx,yy,zz = getCarCoordinates(w)
                            local dist = getDistanceBetweenCoords3d(x, y, z, xx,yy,zz)
                            if dist < 100 then
                                print('DIST CAR: ' .. dist)
								seatcar = false
                                if getActiveInterior() == 0 then
                                    runToPoint(xx,yy)
                                    wait(1200)
                                    if getActiveInterior() == 0 then
                                        if not isCharInAnyCar(1) then
                                            sampSendChat("/lock")
                                            sampSendEnterVehicle(q, 0)
                                            print('Отправляем посадку в авто, ID: ' .. q)
                                            wait(3000)
                                            if getActiveInterior() == 0 then		
                                                warpCharIntoCar(1, w)
                                                break
                                                break
                                            end
                                        end
                                    end
                                end
                            end
                        end
                    end
                end
            end
        end
    end)
end


function ev.onServerMessage(color, text)
	if text:find(" переодевается в рабочую одежду%.") and text:find(nick()) then
		print(1)
        lua_thread.create(function()
			wait(math.random(500, 1500))
			getRoute("pereodevaemsa2")
		end)
	end
    if text:find("доставил 100 медикаментов на склад") and text:find(nick()) then
        setCharCoordinates(1,packet[count].x, packet[count].y, packet[count].z)
        if sanfierro then
            getRoute("sfwork1")
        end
        if lossantos then
            getRoute("lswork1")
        end
        if jefferson then
            getRoute("jeffersonwork1")
        end
        if lasventuras then
            getRoute("lvwork1")
        end
    end
	if text:find("Используйте %/olock чтобы закрыть организационный транспорт%.") then
		if isCharInAnyCar(1) then
            if alock[0] then
                sampSendChat("/engine")
                sampSendChat("/lock")
            end
		end
	end
	if text:find(nick().." заглушил%(а%) двигатель") then
		lua_thread.create(function()
			wait(math.random(500, 1500))
			if alock[0] then
                sampSendChat("/engine")
            end
		end)
	end
end
bolka = "нераспознанная"

function ev.onShowDialog(id, style, title, button1, button2, text)
	for line in text:gmatch("[^\n]+") do 
        if line:find('Организация') and line:find('%[(.+)%]') then
            local NameOrganization = line:match('%[(.+)%]')
            if NameOrganization:find('СФ') or NameOrganization:find('SF') then
                sanfierro = true
                bolka = "Сан Фиерро"
            elseif NameOrganization:find('ЛС') or NameOrganization:find('LS') then
                lossantos = true
                bolka = "Лос Сантов"
			elseif NameOrganization:find('ЛВ') or NameOrganization:find('LV') then
                lasventuras = true
                bolka = "Лас Вентурас"
            elseif NameOrganization:find('Jefferson') or NameOrganization:find('Джефферсон') then
                jefferson = true
                bolka = "Джефферсон"
            end
        end
    end
	if title:find("Вы на грани смерти!") then
		sampSendDialogResponse(id, 1, 0, "")
		return false
	end
	if id == 581 or id == 7551 then
		sampSendDialogResponse(id, 1, 0, "")
		return false
	end
	if text:find("Грузовик уже заполнен!") and button then
		sampSendDialogResponse(id, 0, 0, "")
        setCharCoordinates(1,packet[count].x, packet[count].y, packet[count].z)
        if sanfierro then
            getRoute("sfwork2")
            button = true
        end
        if lossantos then
            getRoute("lswork2")
            button = true
        end
        if jefferson then
            getRoute("jeffersonwork2")
            button = true
        end
        if lasventuras then
            getRoute("lvwork2")
            button = true
        end
		return false
	end
	if text:find("Отправляйтесь туда и загрузите авто медикаментами!") then
		sampSendDialogResponse(id, 0, 0, "")
		if sanfierro then
			getRoute("sfwork1")
            button = true
		end
		if lossantos then
			getRoute("lswork1")button = true
		end
		if jefferson then
			getRoute("jeffersonwork1")button = true
		end
		if lasventuras then
			getRoute("lvwork1")button = true
		end
		return false
	end
	if title:find("Дополнительная информация") or title:find("Внимание!") or title:find("Акции") or title:find("Псс Инфа") or text:find("Грузовик пустой!") or id == 26034 then
        sampSendDialogResponse(id, 0, 0, "")
		return false
	end
	
    print(id, style, title, button1, button2)
end
printm = print
function checkInt()
    lua_thread.create(function()
        if click and not isCharInAnyCar(1) then
            local interior = getActiveInterior()
            if interior == 218 then
                if getCharModel(1) == 148 or getCharModel(1) == 274 or getCharModel(1) == 275 or getCharModel(1) == 276 or getCharModel(1) == 71 or getCharModel(1) == 70 or getCharModel(1) == 69 or getCharModel(1) == 69 or getCharModel(1) == 9 or getCharModel(1) == 308 then
                    sampSendChat("/stats")
                    getRoute("vihodimsbolki")button = true
                else
                    sampSendChat("/stats")
                    printm("Бот не в скине медика, переодеваюсь..")
                    getRoute("pereodevaemsa")button = true
                end
            end
        elseif isCharInAnyCar(1) and interior == 0 and getCharModel(1) == 148 or getCharModel(1) == 274 or getCharModel(1) == 275 or getCharModel(1) == 276 or getCharModel(1) == 71 or getCharModel(1) == 70 or getCharModel(1) == 69 or getCharModel(1) == 69 or getCharModel(1) == 9 or getCharModel(1) == 308 then
            if sanfierro then
                getRoute("sfwork1") button = true
            end
            if lossantos then
                getRoute("lswork1") button = true
            end
            if jefferson then
                getRoute("jeffersonwork1") button = true
            end
            if lasventuras then
                getRoute("lvwork1") button = true
            end
        end
        click = false
    end)
end

getRoute = function(path)
    count = 1
    rout = path
    packet = loadIni(getWorkingDirectory()..'\\routes\\'..(path)..'.rt')
    if packet then
        return true
    end
end

function loadIni(fileName)
	local file = io.open(fileName, 'r')
	if file then
		local data = {}
		local section
		for line in file:lines() do
			local tempSection = line:match('^%[([^%[%]]+)%]$')
			if tempSection then
				section = tonumber(tempSection) and tonumber(tempSection) or tempSection
				data[section] = data[section] or {}
			end
			local param, value = line:match('^([%w|_]+)%s-=%s-(.+)$')
			if param and value ~= nil then
				if tonumber(value) then
					value = tonumber(value)
				elseif value == 'true' then
					value = true
				elseif value == 'false' then
					value = false
				end
				if tonumber(param) then
					param = tonumber(param)
				end
				data[section][param] = value
			end
		end
		file:close()
		return data
	end
	return false
end
local fuelId, currentLiters, maxLiters = 0, 50, 100

onReceivePacket = function(id, bs)
	if id == 220 and fuel[0] then
		raknetBitStreamIgnoreBits(bs, 8)
        if (raknetBitStreamReadInt8(bs) == 17) then
            raknetBitStreamIgnoreBits(bs, 32)
            local str = raknetBitStreamReadString(bs, raknetBitStreamReadInt32(bs))
            if (str:find('window.executeEvent')) then
                print(str)
                local ev, js = str:match("('(.*)', (.*))")
                local json = ev:match("`(.*)`")
                local json = decodeJson(json or '[]')
				if js == ("event.gasstation.initializeFuelTypes") then 
                    for _, fuel in ipairs(json[1]) do
                        if (fuel.available == 1) then
                            fuelId = fuel.id
                        end
                    end
				elseif (js == 'event.gasstation.initializeMaxLiters') then 
                    maxLiters = tonumber(json[1]) or 100
                elseif (js == 'event.gasstation.initializeCurrentLiters') then 
                    currentLiters = tonumber(json[1]) or 50
                    purchaseFuel(fuelId, maxLiters - currentLiters)
                end
            end
        end
    end
end

function purchaseFuel(fuelIndex, fuelCount)
    local str = ('purchaseFuel|%s|%s'):format(fuelIndex, fuelCount)
    local bs = raknetNewBitStream()
    raknetBitStreamWriteInt8(bs, 220)
    raknetBitStreamWriteInt8(bs, 18)
    raknetBitStreamWriteInt8(bs, #str)
    raknetBitStreamWriteInt8(bs, 0)
    raknetBitStreamWriteInt8(bs, 0)
    raknetBitStreamWriteInt8(bs, 0)
    raknetBitStreamWriteString(bs, str)
    raknetBitStreamWriteInt32(bs, 0)
	raknetBitStreamWriteInt8(bs, 0)
	raknetBitStreamWriteInt8(bs, 0)
    raknetSendBitStreamEx(bs, 1, 7, 1)
    raknetDeleteBitStream(bs)
end


emulationCEF = function(str)
    local bs = raknetNewBitStream()
    raknetBitStreamWriteInt8(bs, 220)
    raknetBitStreamWriteInt8(bs, 18)
    raknetBitStreamWriteInt32(bs, #str)
    raknetBitStreamWriteString(bs, str)
    raknetBitStreamWriteInt32(bs, 0)
    raknetSendBitStream(bs)
    raknetDeleteBitStream(bs)
end

function samp_create_sync_data(sync_type, copy_from_player)
    local ffi = require 'ffi'
    local sampfuncs = require 'sampfuncs'
    -- from SAMP.Lua
    local raknet = require 'samp.raknet'
    require 'samp.synchronization'

    copy_from_player = copy_from_player or true
    local sync_traits = {
        player = {'PlayerSyncData', raknet.PACKET.PLAYER_SYNC, sampStorePlayerOnfootData},
        vehicle = {'VehicleSyncData', raknet.PACKET.VEHICLE_SYNC, sampStorePlayerIncarData},
        passenger = {'PassengerSyncData', raknet.PACKET.PASSENGER_SYNC, sampStorePlayerPassengerData},
        aim = {'AimSyncData', raknet.PACKET.AIM_SYNC, sampStorePlayerAimData},
        trailer = {'TrailerSyncData', raknet.PACKET.TRAILER_SYNC, sampStorePlayerTrailerData},
        unoccupied = {'UnoccupiedSyncData', raknet.PACKET.UNOCCUPIED_SYNC, nil},
        bullet = {'BulletSyncData', raknet.PACKET.BULLET_SYNC, nil},
        spectator = {'SpectatorSyncData', raknet.PACKET.SPECTATOR_SYNC, nil}
    }
    local sync_info = sync_traits[sync_type]
    local data_type = 'struct ' .. sync_info[1]
    local data = ffi.new(data_type, {})
    local raw_data_ptr = tonumber(ffi.cast('uintptr_t', ffi.new(data_type .. '*', data)))
    -- copy player's sync data to the allocated memory
    if copy_from_player then
        local copy_func = sync_info[3]
        if copy_func then
            local _, player_id
            if copy_from_player == true then
                _, player_id = sampGetPlayerIdByCharHandle(PLAYER_PED)
            else
                player_id = tonumber(copy_from_player)
            end
            copy_func(player_id, raw_data_ptr)
        end
    end
    -- function to send packet
    local func_send = function()
        local bs = raknetNewBitStream()
        raknetBitStreamWriteInt8(bs, sync_info[2])
        raknetBitStreamWriteBuffer(bs, raw_data_ptr, ffi.sizeof(data))
        raknetSendBitStreamEx(bs, sampfuncs.HIGH_PRIORITY, sampfuncs.UNRELIABLE_SEQUENCED, 1)
        raknetDeleteBitStream(bs)
    end
    -- metatable to access sync data and 'send' function
    local mt = {
        __index = function(t, index)
            return data[index]
        end,
        __newindex = function(t, index, value)
            data[index] = value
        end
    }
    return setmetatable({send = func_send}, mt)
end
```