@name ArmShop V1 EGP
@inputs S:wirelink D:wirelink
# Idle animations
@outputs  
@persist Dir IdleRate FadeGuns AimFadeGuns IdleStatus
# Users
@outputs 
@persist LogOutIdle NearbyGunT:table WaitingNearby Nearby:array NearbyGun:array NI LogOutAlpha CheckNearby SpawnAnyway NGI
# Purchasing
@outputs BuyStage
@persist PurchaseSeconds PurchaseSecDelay MoveUpTheta
# Selecting gun
@outputs 
@persist AttributeText:string Selected Spread
# Click 
@outputs 
@persist IsClick 
# Swiping
@outputs MoveRate
@persist StartPos MovePos  USwipe 
# Scanning shipments
@outputs
@persist ScanRanger:ranger ScanPos:array ScanStrings:array KnownGuns:table ScanNumber ScanStage ShipmentName:string ScanTable:table
# Credit
@outputs 
@persist Credit:table SaveCreditTable:string DSCredit:array CreditStage CreditCount CreditCooldown LimboCredit
# File systems
@outputs
@persist FileStage
# Discount
@outputs
@persist Discount:table Discounted:table NonDiscounted:table
# Sounds
@persist SwipeSound
# Settings
@outputs
@persist User:entity Guns:table SavedUser:entity EnableSounds TempUser:entity SaveCreditType:string UserTakeoverCooldown PriceMultiplier:string FastLoad
# Props
@outputs 
@persist Panel:entity
# DSGroups
@outputs 
@persist GN:string GUNE2:entity

#DONE: User who is going
#DONE: User nearby players spawn gun
#DONE: Flick display to tell players what to do

interval(100)
runOnLast(1)
runOnFile(1)

if(first()) {
    function addKnownGun(RPName:string,Name:string,Cost:number,Slot:string,Count:number,Model:string,Desc:string,Ammo:string,Mag:number,Attach:string,FireMode:string,Coord:vector,HoloCoord:vector,Scale:vector){
        KnownGuns[RPName:upper(),table] = table("Name" = Name,"Cost" = Cost,"Slot" = Slot,"Count" = Count,"Model" = Model,"Desc" = Desc,"Ammo" = Ammo,"Mag" = Mag,"Attach" = Attach,"FireMode" = FireMode,"Coord" = Coord,"HoloCoord"=HoloCoord,"Scale" = Scale)
    }
    function addDiscount(JobName:string,DiscountString:string) {
        local ExistingJobs = table("Citizen"=1,"Civil Protection"=1,"Veteran Civil Protection"=1,"Gangster"=1,"Mob boss"=1,"Gun Dealer"=1,"Medic"=1,"Civil Protection Chief"=1,"Mayor"=1,"Gunshop Owner"=1,"SWAT"=1,"Thief"=1,"Moneyprinter Technician"=1,"Black Market Dealer"=1,"Sewer Ork"=1,"Sewer Ork Boss"=1,"Scholar"=1)
        if(ExistingJobs:exists(JobName)) {
            if((DiscountString:index(1) == "x" | DiscountString:index(1) == "+" | DiscountString:index(1) == "-") & DiscountString:length() > 1 & DiscountString:sub(2):toNumber() > 0) {
                Discount[JobName,string] = DiscountString
            }
            else{print("Error: Discount syntax error at " + JobName + "!")}
        }
        else{print("Error: Discount failed to add ("+JobName+" does not exist)")}
    }
    function vector fixVector(Vector:vector) {
        return vec(Vector:y(),Vector:x(),Vector:z())
    }
    
    
    # Price Multiplier (How the gun prices should be set):
    # Valid entries: "+" or "x" followed by a number. Add or multiply a value, respectively
    PriceMultiplier = "+100"
    
    # Fast Load (If the system should physically scan (for looks) each time:
    # Valid entries: 1 for fast scanning, 0 for visual, slow scanning
    FastLoad = 1
    
    # Save Credit Type (How credit data should be saved):
    # Valid entries: "FILE" for saving with filefunctions, "GUNE2" for saving within the Gunshop Main E2, "nil" for no saving (defaults to no saving)
    SaveCreditType = "FILE"
    
    EnableSounds = 0
    
    # Job discounts (Flexing price according to customer's job):
    # Valid entries: addDiscount("<team name>","<"+", "-", or "x" followed by a number. Add or multiply a value, respectively>")
    #addDiscount("SWAT","x0.75")
    #addDiscount("Civil Protection","x0.75")
    #addDiscount("Mayor","x0.75")
    #addDiscount("Veteran Civil Protection","x0.75")
    #addDiscount("Civil Protection Chief","x0.75")
    #addDiscount("Black Market Dealer","x0.1")
    
    #addDiscount("Gangster","x0.75")
    #addDiscount("Mob boss","x0.75")
    
    #addKnownGun(RPNAME, DISPLAYNAME, COST, SLOT (OBSELETE), COUNT (OBSELETE), MODEL, DESCRIPTION, AMMOTYPE, MAGAZINECOUNT, ATTACHMENTS, FIREMODES, DISPLAYCOORDS, DISPLAYSCALE){
    #           <string>  <string>  <number>   <string>          <number>     <string>  <string>   <string>    <number>      <string>    <string>    <3D vector>    <3D vector>
    
    # Gundealer
    addKnownGun("Raging Bull","Raging Bull",2500/5,"1,b",10,"models/weapons/w_357.mdl","The Brazilian revolver is marketed to hunt large animals, even buffalo",".454 Casull",5,"CompM4,Leupold MK4","Double-action",vec(-6,0,4),vec(-6,0,4),vec(0.5))
    addKnownGun("P226","P226",2500/5,"1,b",10,"models/weapons/w_pist_p228.mdl","The SIG Sauer pistol is used by law-enforcement worldwide",".357 SIG",13,"Suppressor","Semi-auto",vec(-3,0,1),vec(-3,0,1),vec(0.5))
    addKnownGun("OTs-33","OTs-33",2000/5,"1,b",10,"models/weapons/w_smg_tmp.mdl","The Russian machine pistol is used by special police","9x18MM",18,"","Semi-auto,Full-Auto",vec(0,0,0),vec(0,0,0),vec(0.25))
    addKnownGun("M1911","M1911",2000/5,"1,b",10,"models/weapons/w_pistol.mdl","The American pistol has been through WW1, WW2, and is still in use.",".45 ACP",7,"Suppressor","Semi-auto",vec(-4,0,5),vec(-4,0,5),vec(0.5))
    addKnownGun("Desert Eagle","Desert Eagle",3000/5,"1,b",10,"models/weapons/w_pist_deagle.mdl","The US/Israeli pistol is one of the most powerful to exist",".50 AE",7,"Tritium Sights","Semi-auto",vec(-4,0,0),vec(-4,0,0),vec(0.5))
    addKnownGun("Glock 20","Glock-20",1500/5,"1,b",10,"models/weapons/w_pist_glock18.mdl","The Austrian pistol dominates 65% US police armament","10x25MM",15,"Suppressor,Tritium Sights","Semi-auto",vec(-3,0,0),vec(-3,0,0),vec(0.5))
    addKnownGun("M3 Super 90","M3 Super 90",4500/5,"1,b",10,"models/weapons/w_shot_m3super90.mdl","The Italian shotgun is popular among citizens and police","12-gauge",8,"CompM4","Semi-auto",vec(6,0,0),vec(6,0,0),vec(0.25))
    addKnownGun("Remington 870","Remington 870",3500/5,"1,b",10,"models/weapons/w_shot_xm1014.mdl","The pump-action shotgun is widely used for hunting","12-gauge",8,"","Pump-action",vec(6,0,-1),vec(6,0,-1),vec(0.25))
    
    # Gunshop owner/black market dealer
    addKnownGun("SR25","SR-25",8750/5,"1,b",10,"models/weapons/w_snip_sg550.mdl","The American sniper rifle is a versatile weapon used by the US Navy","7.62x51MM",10,"Suppressor","Semi-auto",vec(5,0,0),vec(5,0,0),vec(0.25))
    addKnownGun("M82","M82",9500/5,"2,b",10,"models/weapons/w_snip_awp.mdl","The Barrett rifle can fires .50 cal bullets capable of stopping anything","0.50 BMG",10,"","Semi-auto",vec(6,0,0),vec(6,0,0),vec(0.2))
    addKnownGun("M24","M24",8500/5,"3,b",10,"models/weapons/w_snip_scout.mdl","The Remington rifle is a hunting rifle variant designed for the military","7.62x51MM",5,"Suppressor,Bipod","Bolt-action",vec(6,0,0),vec(6,0,0),vec(0.25))
    addKnownGun("M4A1","M4A1",7500/5,"4,b",10,"models/weapons/w_rif_m4a1.mdl","The American carbine derived from the M16 is used widely by the US army","5.56x45MM",30,"Supressor,ELCAN C79,CompM4,EoTech 553","Semi-auto,Full-auto,3 round Burst",vec(6,0,0),vec(6,0,0),vec(0.25))
    addKnownGun("UZI","UZI",2500/5,"1,m",10,"models/weapons/w_smg_mac10.mdl","The Israeli submachine gun was one of the first, still used, machine-pistols","9x19MM",32,"Suppressor,Uzi Stock","Semi-auto,Full-auto",vec(-2,0,1.5),vec(-2,0,1.5),vec(0.25))
    addKnownGun("G36C","G36C",7500/5,"2,m",10,"models/weapons/w_smg_ump45.mdl","The German assault rifle by Heckler & Koch, meant to replace the heavier G3","5.56x45MM",30,"Suppressor,CompM4","Semi-auto,Full-auto,2 round Burst",vec(0,0,0),vec(0,0,0),vec(0.25))
    addKnownGun("CZ-858","CZ-858",5750/5,"3,m",10,"models/weapons/w_rif_ak47.mdl","The iconic Soviet assault rifle is the most widespread weapon in the world","7.62x39MM",30,"Suppressor,CompM4","Semi-auto,Full-auto",vec(6,0,0),vec(6,0,0),vec(0.25))
    addKnownGun("FAMAS","FAMAS",6750/5,"4,m",10,"models/weapons/w_rif_famas.mdl","The French bullpup assault rifle is a service rifle still in use today","5.56x45MM",25,"Suppressor,CompM4","Semi-auto,Full-auto,3 round Burst",vec(7.5,0,0),vec(7.5,0,0),vec(0.25))
    addKnownGun("G3","G3",7500/5,"1,t",10,"models/weapons/w_snip_g3sg1.mdl","The German assault rifle by Heckler &   Koch is the European M4A1 equivalent","7.62x51MM",20,"Suppressor,CompM4,EoTech 553","Semi-Auto,Full-Auto",vec(6.5,0,0),vec(6.5,0,0),vec(0.25))
    addKnownGun("MP5","MP5",8150/5,"2,t",10,"models/weapons/w_smg_mp5.mdl","The German submachine gun by Heckler &   Koch is used by over 40 nations today","9x19MM",15,"Supressor,30RND Mag","Semi-auto,Full-auto,3 round Burst",vec(0,0,0),vec(0,0,0),vec(0.25))
    addKnownGun("SG550","SG550",8150/5,"3,t",10,"models/weapons/w_rif_sg552.mdl","The Swiss SIG assault rifle is developed for all aspects military personnel","5.56x45MM",20,"Suppressor,EoTech 553,30RND Mag","Semi-auto,Full-auto,3 round Burst",vec(7.5,0,0),vec(7.5,0,0),vec(0.25))
    addKnownGun("SKS","SKS",6750/5,"4,t",10,"models/weapons/w_rif_galil.mdl","The Soviet carbine is the standard semi-automatic rifle worldwide.","7.62x39MM",10,"Suppressor,PSO-1,CompM4,EoTech,20RND Clip,30RND Mag","Semi-auto",vec(6,0,0),vec(6,0,0),vec(0.25))
    addKnownGun("M14","M14",8750/5,"4,t",10,"models/weapons/w_snip_sg550.mdl","The American rifle, prevalent in Vietnam and later replaced by the M16","7.62x51MM",20,"Suppressor,Leupold MK4,CompM4,EoTech 553","Semi-Auto,Full-Auto",vec(6,0,0),vec(6,0,0),vec(0.25))
    addKnownGun("Lockpick","Lockpick",3000,"4,t",10,"models/weapons/w_crowbar.mdl","I swear officer, this isn't a lockpick.","N/A",20,"N/A","N/A",vec(-8,0,6),vec(0,0,2),vec(0.25))

    # TylerB's server
    addKnownGun("9MM PISTOL","9 MM",3000,"4,t",10,"models/weapons/w_pistol.mdl","Weaker than a crowbar!","Pistol Ammo",18,"N/A","Semi-auto",vec(-4,0,6),vec(0,0,2),vec(0.75))
    addKnownGun("KEYPAD CRACKER","Cracker",2000,"4,t",10,"models/weapons/w_c4_planted.mdl","Why not just blow it up with the C4?","N/A",0,"N/A","N/A",vec(-4,0,0),vec(0,0,2),vec(0.4))
    addKnownGun("PUMP SHOTGUN","Shotgun",3500/5,"1,b",10,"models/weapons/w_shot_xm1014.mdl","The pump-action shotgun is widely used for hunting","12-gauge",8,"","Pump-action",vec(6,0,-1),vec(6,0,-1),vec(0.25))

    #CG Server
    addKnownGun("M4","M4",3000,"4,t",10,"models/weapons/w_crowbar.mdl","I swear officer, this isn't a lockpick.","N/A",20,"N/A","N/A",vec(-8,0,6),vec(0,0,2),vec(0.25))
    entity():propFreeze(1)
    
    GN = "CanadiansMunitions"

    timer("StartScanningShipments",1000)
    # -45,-94,-142,-190
    # 15
    # -35,0,35
    ScanPos = array(
        vec(35.059844970703,44.940078735352,15.039823532104),vec(35.059860229492,93.939682006836,15.236180305481),vec(35.059875488281,141.93930053711,15.42852973938),vec(35.05989074707,189.93891906738,15.620879173279),
        vec(0.060126833617687,44.939529418945,15.180086135864),vec(0.060142058879137,93.93913269043,15.376442909241),vec(0.060156971216202,141.9387512207,15.56879234314),vec(0.060171887278557,189.93836975098,15.761141777039),
        vec(-34.939590454102,44.938980102539,15.320348739624),vec(-34.939575195313,93.938583374023,15.516705513),vec(-34.939559936523,141.9382019043,15.709054946899),vec(-34.939544677734,189.93782043457,15.901404380798)
    )
    ScanStrings = array(
        "1,b","2,b","3,b","4,b",
        "1,m","2,m","3,m","4,m",
        "1,t","2,t","3,t","4,t"
    )
    ScanNumber = 1
    ScanStage = 1
}

if(dsGetString() == "scanshipments" & ScanStage == 0) {
    timer("StartScanningShipments",100)
}
if(clk("StartScanningShipments")) {
    local HoloDelI = 0
    for(HoloDelI=1,12) {
        holoDelete(HoloDelI)
    }    S:egpClear()
    D:egpClear()
    if(FastLoad == 0) {
        dsSendDirect(GN,GUNE2,"scanningshipments")
    }
    Guns:clear()
    ScanStage = 1
    ScanNumber = 1
    timer("ScanNextShipment",1000)
}
if(clk("ScanNextShipment") & ScanNumber <= 12) {
    ScanRanger = rangerOffset(50,GUNE2:toWorld(ScanPos[ScanNumber,vector]),-GUNE2:up())
    timer("ScanShipment",100)
}
if(clk("ScanNextShipment") & ScanNumber > 12) {
    if(FastLoad == 1) {ScanStage = 2}
    elseif(FastLoad == 0) {ScanStage = ScanStage+0.5}
}
if(dsGetString() == "finishedscanning") {ScanStage = ScanStage+0.5}

if(ScanStage == 2) {
    timer("FinishScan",200)
    timer("DrawScreens",100)
}

if(clk("FinishScan")) {
    ScanStage = 0
    ScanNumber = 0
}

elseif(clk("ScanShipment")) {
    if(ScanRanger:entity():type() == "spawned_shipment") {
        if(ScanRanger:entity():shipmentName():sub(ScanRanger:entity():shipmentName():length()-10,ScanRanger:entity():shipmentName():length()):lower():trim() == "(smuggled)" | ScanRanger:entity():shipmentName():sub(ScanRanger:entity():shipmentName():length()-10,ScanRanger:entity():shipmentName():length()):lower():trim() == "(discount)") {
            ShipmentName = ScanRanger:entity():shipmentName():sub(1,ScanRanger:entity():shipmentName():length()-11):trim()
        } else{
            ShipmentName = ScanRanger:entity():shipmentName()
        }
        
        if(KnownGuns:exists(ShipmentName:upper())) {
            ScanTable = KnownGuns[ShipmentName:upper(),table]:clone()
            if(PriceMultiplier:index(1) == "+" & PriceMultiplier:sub(2):toNumber() >= 1) {
                ScanTable["Cost",number] = round(PriceMultiplier:sub(2):toNumber()+(ScanRanger:entity():shipmentPrice()/10))
            }elseif(PriceMultiplier:index(1) == "x" & PriceMultiplier:sub(2):toNumber() >= 0) {
                ScanTable["Cost",number] = round(PriceMultiplier:sub(2):toNumber()*(ScanRanger:entity():shipmentPrice()/10))
            }
            ScanTable["Count",number] = ScanRanger:entity():shipmentAmount()
            ScanTable["Slot",string] = ScanStrings[ScanNumber,string]
            Guns[(Guns:count()+1):toString(),table] = ScanTable:clone()
        }
        else{
            print("Error: Gun \""+ShipmentName+"\" was not found in the known guns list!")
        }
    }
    else{"no shipment found go to next"}
    timer("NextScanNumber",100)
}
elseif(clk("NextScanNumber")) {
    ScanNumber = (ScanNumber+1)
    ShipmentName = ""
    ScanTable:clear()
    timer("ScanNextShipment",100)
}

if(ScanStage > 0) {
    local LoadI = 0
    local LoadText = array("g","n","i","d","a","o","L")

    for(LoadI=1,7) {
        if(S:egpHasObject(100+LoadI) == 0 & (S:egpPos(100+LoadI-1):y() > 160 | (LoadI == 1 & S:egpHasObject(107) == 0))) {
            S:egpTextLayout(100+LoadI,LoadText[LoadI,string],vec2(256-16,0),vec2(512/14,512/14))
            S:egpSize(100+LoadI,32)
            S:egpAlign(100+LoadI,1,1)
        }
        if(S:egpHasObject(100+LoadI) == 1) {
            if(S:egpPos(100+LoadI):y() < 160) {S:egpPos(100+LoadI,S:egpPos(100+LoadI)+vec2(0,20))}
            elseif(S:egpPos(100+LoadI):y() >= 160 & S:egpPos(100+LoadI):y() < 400) {S:egpPos(100+LoadI,S:egpPos(100+LoadI)+vec2(0,2.5))}
            elseif(S:egpPos(100+LoadI):y() >= 400 & S:egpPos(100+LoadI):y() < 600) {S:egpPos(100+LoadI,S:egpPos(100+LoadI)+vec2(0,40))}
            elseif(S:egpPos(100+LoadI):y() >= 600) {S:egpRemove(100+LoadI)}
        }
    }
}elseif(S:egpHasObject(101) | S:egpHasObject(107)) {
    local DelLoadI=0
    for(DelLoadI=100,107) {
        S:egpRemove(DelLoadI)
    }
}

if(dsGetEntity():owner() == owner() & GUNE2:model() == "") {
    GUNE2 = dsGetEntity()
    dsSendDirect(GN,GUNE2,entity())
}
if(dsGetString():sub(1,3) == "del") {
    GUNE2 = noentity()
    if(ScanStage > 0) {
        ShipmentName = ""
        ScanTable:clear()
        ScanStage = 0
        ScanNumber = 1
        ScanStage = 1
        timer("StartScanningShipments",100)
    }
}
if(last()) {
    if(Credit:count() < 1 | SaveCreditType != "GUNE2") {
        dsSendDirect(GN,GUNE2,"del")
    }else{
        dsSendDirect(GN,GUNE2,"del "+vonEncode(Credit:clone()))
    }
}


if(dsGetString() == "antidupe") {
    entity():propNotSolid(1)
}

if(dsGetString() == "unantidupe") {
    entity():propNotSolid(0)
}

if(first()) {
    entity():setMaterial("models/effects/vol_light001")
    entity():setAlpha(0)
    
    S:entity():setMaterial("models/effects/vol_light001")
    S:entity():setAlpha(255)
    S:entity():propFreeze(1)
    D:entity():setMaterial("models/effects/vol_light001")
    D:entity():setAlpha(255)
    D:entity():propFreeze(1)
    
    Spread = 1
    Panel = entity():isWeldedTo()
    FadeGuns = 255
    AimFadeGuns = 255
    
    dsJoinGroup(GN)
    dsSetScope(0)
    dsSend(GN,GN,entity())
    S:egpClear()
    D:egpClear()
}

if(clk("DrawScreens")) {
    S:egpClear()
    D:egpClear()
    
    S:egpBox(13,vec2(256,266.8),vec2(45,20))
    S:egpMaterial(13,"VGUI/gradient_down")
    S:egpColor(13,vec(255,220,150))
    S:egpAlpha(13,0)
    S:egpBox(14,vec2(256,256),vec2(45,4))
    S:egpColor(14,vec(255,220,150))
    S:egpAlpha(14,0)
    S:egpBox(15,vec2(256,245.2),vec2(45,20))
    S:egpMaterial(15,"VGUI/gradient_up")
    S:egpColor(15,vec(255,220,150))
    S:egpAlpha(15,0)
    
    for(I=1,12) {
        #S:egpBox(I,vec2(256,256),vec2(512/14,512/14))
        if(Guns:exists(I:toString())) {
            S:egpTextLayout(I,Guns[I:toString(),table]["Name",string],vec2(256,256),vec2(512/14,512/14))
            S:egpSize(I,10)
            S:egpAlign(I,1,1)
            holoCreate(I,S:egpToWorld(vec2(256,256)),fixVector(Guns[I:toString(),table]["Scale",vector]-vec(clamp(Guns[I:toString(),table]["Scale",vector]:x()-(Guns[I:toString(),table]["Scale",vector]:x()-0.1),0.01,100),0,0)),entity():toWorld(ang(0,-90,90)))
            holoModel(I,Guns[I:toString(),table]["Model",string])
        }else{
            #S:egpTextLayout(I,"NO STOCK",vec2(256,256),vec2(512/14,512/14))
            S:egpTextLayout(I," ",vec2(256,256),vec2(512/14,512/14))
            S:egpSize(I,10)
            S:egpAlign(I,1,1)
            S:egpColor(I,vec(150))
        }
    }
    
    S:egpTextLayout(20,"Press USE to begin",vec2(236,224),vec2(512/12,128))
    S:egpSize(20,16)
    S:egpAlign(20,1,0)
    S:egpAlpha(20,0)
    

    
    S:egpCircle(22,vec2(256,320),vec2(5,5))
    S:egpColor(22,vec(255))
    S:egpSize(22,2)
    S:egpMaterial(22,"vgui/minixhair.vtf")
    S:egpAlpha(22,0)
    
    S:egpCircle(21,vec2(256.5,320+20),vec2(10,10))
    S:egpColor(21,vec(255,255,255))
    S:egpSize(21,2)
    S:egpMaterial(21,"gui/arrow.vtf")
    S:egpAlpha(21,0)
    
    S:egpLine(23,vec2(256.5,350+20),vec2(256.5,S:egpPos(21):y()))
    S:egpSize(23,4)
    S:egpColor(23,vec(255,220,150))
    S:egpAlpha(23,0)
        
    # Gun name shadow
    D:egpTextLayout(2,"",vec2(160-5,256+64)+vec2(2),vec2(96,64))
    D:egpSize(2,30)
    D:egpAlign(2,2,1)
    D:egpColor(2,vec())
    D:egpAlpha(2,0)
    # Gun name
    D:egpTextLayout(1,"",vec2(160-5,256+64),vec2(96,64))
    D:egpSize(1,30)
    D:egpAlign(1,2,1)
    D:egpAlpha(1,0)
    # Price shadow
    D:egpTextLayout(4,"",vec2(160-5,256+84)+vec2(2),vec2(96,64))
    D:egpSize(4,16)
    D:egpAlign(4,2,1)
    D:egpColor(4,vec())
    D:egpAlpha(4,0)
    # Price
    D:egpTextLayout(3,"",vec2(160-5,256+84),vec2(96,64))
    D:egpSize(3,16)
    D:egpAlign(3,2,1)
    D:egpAlpha(3,0)
    # Description shadow
    D:egpTextLayout(6,"",vec2(161,417),vec2(192,128))
    D:egpSize(6,10)
    D:egpAlign(6,1,1)
    D:egpColor(6,vec())
    D:egpAlpha(6,0)
    # Description
    D:egpTextLayout(5,"",vec2(160,416),vec2(192,128))
    D:egpSize(5,10)
    D:egpAlign(5,1,1)
    D:egpAlpha(5,0)
    
    # Attribute shadow
    D:egpTextLayout(8,"",vec2(256+5,256+80)+vec2(2),vec2(96,50))
    D:egpSize(8,12)
    D:egpAlign(8,0,1)
    D:egpColor(8,vec())
    # Attribute
    D:egpTextLayout(7,"",vec2(256+5,256+80),vec2(96,50))
    D:egpSize(7,12)
    D:egpAlign(7,0,1)
    D:egpAlpha(7,0)
        
    # Desc box
    D:egpBox(9,vec2(256,504+5),vec2(192,12))
    D:egpAlpha(9,0)
    D:egpBox(10,vec2(256,497+5),vec2(192,2))
    D:egpColor(10,vec())
    D:egpAlpha(10,0)
    D:egpBox(11,vec2(256,511+5),vec2(192,2))
    D:egpColor(11,vec())
    D:egpAlpha(11,0)
    
    # Purchase button shadow
    D:egpTextLayout(13,"",vec2(160,476)+vec2(1),vec2(192,64))
    D:egpSize(13,12)
    D:egpAlign(13,1,1)
    D:egpColor(13,vec())
    D:egpAlpha(13,0)
    # Purchase button 
    D:egpTextLayout(12,"",vec2(160,476),vec2(192,64))
    D:egpSize(12,12)
    D:egpAlign(12,1,1)
    D:egpAlpha(12,0)
    
    D:egpTextLayout(14,"Pending Purchase...",vec2(160,256+96)+vec2(1),vec2(192,128))
    D:egpSize(14,16)
    D:egpAlign(14,1,1)
    D:egpColor(14,vec())
    D:egpAlpha(14,0)
    
    D:egpTextLayout(15,"Pending Purchase...",vec2(160,256+96),vec2(192,128))
    D:egpSize(15,16)
    D:egpAlign(15,1,1)
    D:egpAlpha(15,0)
    
    D:egpTextLayout(16,"20 sec",vec2(160,256+96+32)+vec2(1),vec2(192,128))
    D:egpSize(16,48)
    D:egpAlign(16,1,1)
    D:egpColor(16,vec())
    D:egpAlpha(16,0)
    
    D:egpTextLayout(17,"20 sec",vec2(160,256+96+32),vec2(192,128))
    D:egpSize(17,48)
    D:egpAlign(17,1,1)
    D:egpAlpha(17,0)
    
    D:egpTextLayout(18,"Purchase cancelled,\nreturning to menu in X...",vec2(160,256+128)+vec2(1),vec2(192,128))
    D:egpSize(18,16)
    D:egpAlign(18,1,1)
    D:egpColor(18,vec())
    D:egpAlpha(18,0)
    
    D:egpTextLayout(19,"Purchase cancelled,\nreturning to menu in X...",vec2(160,256+128),vec2(192,128))
    D:egpSize(19,16)
    D:egpAlign(19,1,1)
    D:egpAlpha(19,0)
    
    D:egpTextLayout(20,"",vec2(160,256+128+16)+vec2(1),vec2(192,128))
    D:egpSize(20,16)
    D:egpAlign(20,1,1)
    D:egpColor(20,vec())
    D:egpAlpha(20,0)
    
    D:egpTextLayout(21,"",vec2(160,256+128+16),vec2(192,128))
    D:egpSize(21,16)
    D:egpAlign(21,1,1)
    D:egpAlpha(21,0)
    
    D:egpTextLayout(22,"You have been logged out for idling/taking too long.",vec2(160,256+128)+vec2(1),vec2(192,128))
    D:egpSize(22,16)
    D:egpAlign(22,1,1)
    D:egpAlpha(22,0)
    
    D:egpTextLayout(23,"Warning: other players are nearby, in order to prevent theft, gun will not spawn until they leave.",vec2(160,256+112)+vec2(1),vec2(192,128))
    D:egpColor(23,vec())
    D:egpSize(23,16)
    D:egpAlign(23,1,1)
    D:egpAlpha(23,0)
    
    D:egpTextLayout(24,"Warning: other players are nearby, in order to prevent theft, gun will not spawn until they leave.",vec2(160,256+112),vec2(192,128))
    D:egpSize(24,16)
    D:egpAlign(24,1,1)
    D:egpAlpha(24,0)
    
    holoCreate(13,entity():pos(),vec(0.01),ang())
    holoAlpha(13,0)
}




# Idle
if(User:isPlayer() == 0 & BuyStage == 0) {
    if(randint(1,200) == 1 & ((Dir == 1 & IdleRate == 2) | (Dir == 0))) {Dir = -1}
    if(randint(1,200) == 1 & ((Dir == -1 & IdleRate == -2) | (Dir == 0))) {Dir = 1}
    if(IdleRate < 2 & Dir == 1) {IdleRate = (IdleRate+0.05)}
    if(IdleRate > -2 & Dir == -1) {IdleRate = (IdleRate-0.05)}
}else{IdleRate = 0}










if(User:isPlayer() == 0 & findCanQuery()) {
    findClearBlackList()
    findByClass("player")
    findSortByDistance(entity():toWorld(vec(0,50,0)))
    Nearby = findToArray()
}

#if(first()) {print("toLocal: " + entity():toLocal(entity():pos()+vec(5,-3,-8)))
#    print("edit: " + shiftR(vec(5,-3,-8)*vec(-1,1,-1)))
#    }
#shiftR(vec(5,-3,-8)*vec(-1,1,-1))

if(User:isPlayer() == 0 & Nearby:count() > 0 & BuyStage == 0 & ScanStage == 0) {
    for(NI=1,clamp(Nearby:count(),1,3)) {
        if(Nearby[1,entity]:pos():distance(entity():pos()) < 100 & User:isPlayer() == 0) {
            if(IdleStatus == 0) {IdleStatus = 1}
        } else{IdleStatus = 0}

        if(Nearby[NI,entity]:aimEntity() == Panel & (Nearby[NI,entity]:keyUse() | Nearby[NI,entity]:keyAttack1() | Nearby[NI,entity]:keyAttack2())) {
            IdleStatus = 0
            User = Nearby[NI,entity]
            Dir = 0
            timer("LongTimeout",1000*120)
            LogOutAlpha = 0
            # Discount
                if(NonDiscounted:count() == 0 & Guns:count() > 0) {NonDiscounted = Guns:clone()}
                if(Discount:exists(Nearby[NI,entity]:team():teamName()) & Guns:count() > 0) {
                    local DiscountI=0
                    for(DiscountI=1,clamp(NonDiscounted:count(),1,12)) {
                        local DiscountTeam = Discount[Nearby[NI,entity]:team():teamName(),string]
                        local DiscountNewCost = Guns[DiscountI:toString(),table]["Cost",number]
                        local DiscountGunTable = Guns[DiscountI:toString(),table]:clone()
                        if(DiscountTeam:index(1) == "-")     {DiscountNewCost = round(clamp(Guns[DiscountI:toString(),table]["Cost",number]-(DiscountTeam:sub(2)):toNumber(),0,100^100))}
                        elseif(DiscountTeam:index(1) == "+") {DiscountNewCost = round(clamp(Guns[DiscountI:toString(),table]["Cost",number]+(DiscountTeam:sub(2)):toNumber(),0,100^100))}
                        elseif(DiscountTeam:index(1) == "x") {DiscountNewCost = round(clamp(Guns[DiscountI:toString(),table]["Cost",number]*(DiscountTeam:sub(2)):toNumber(),0,100^100))}
                        DiscountGunTable["Cost",number] = DiscountNewCost
                        Discounted[(Discounted:count()+1):toString(),table] = DiscountGunTable:clone()
                    }
                }
                if(Discount:exists(Nearby[NI,entity]:team():teamName())) {
                    Guns = Discounted:clone()
                }else{
                    Guns = NonDiscounted:clone()
                }
        }
    }
}

if(User:isPlayer()) {
    if(changed(User:aimPos()) == 0 & LogOutIdle == 0 & BuyStage < 2) {LogOutIdle = 1 timer("LogoutIdle",20*1000)}
    if(clk("LogoutIdle") & BuyStage < 2) {LogOutIdle = 0 stoptimer("LongTimeout") timer("LogOutIdle",100)}
    if(changed(User:aimPos()) & LogOutIdle == 1) {LogOutIdle = 0 stoptimer("LogoutIdle")}
}
if(( (User:isPlayer() & User:pos():distance(entity():toWorld(vec(0,50,0))) > 200) | clk("LogOutIdle") | clk("LongTimeout")) & BuyStage < 2) {
    User = noentity()
    Selected = 0
    LogOutAlpha = 255
    LogOutIdle = 0
    stoptimer("LogoutIdle")
    stoptimer("LongTimeout")
}

if(clk("LogOutIdle") | clk("LongTimeout") & CreditStage > 0) {
    local DelCreditI=1
    for(DelCreditI=50,79) {D:egpRemove(DelCreditI)}
    CreditStage = 0 CreditCount = 0 LimboCredit = 0
    BuyStage = 0
    SavedUser = noentity()
    
    User = noentity()
    Selected = 0
    LogOutAlpha = 255
    LogOutIdle = 0
    stoptimer("LogoutIdle")
    stoptimer("LongTimeout")
}

if(owner():keyUse() & owner():keyReload() & owner():aimEntity() == Panel) {
    if(User != owner() & UserTakeoverCooldown == 0) {
        TempUser = User
        if(SavedUser:isPlayer()) {SavedUser = owner()}
        User = owner()
        print("Owner has been set as user (taken from: " +TempUser:name()+ ")!")
        UserTakeoverCooldown = 1
        timer("UnownerCooldown",500)
    }
    if(User == owner() & UserTakeoverCooldown == 0) {
        User = TempUser
        if(SavedUser:isPlayer()) {SavedUser = TempUser}
        TempUser = noentity()
        print("Owner has been removed from user (given to:" +User:name()+")!")
        UserTakeoverCooldown = 1
        timer("UnownerCooldown",500)
    }
}
if(clk("UnownerCooldown")) {UserTakeoverCooldown = 0}   
if(User:isPlayer() == 0 & TempUser:isPlayer() == 1) {TempUser = noentity()}


# Clicking
if((User:keyUse() == 1 | User:keyAttack1() == 1 | User:keyAttack2() == 1) & IsClick == 0) {IsClick = 1 timer("IsClick",1000)}
if(clk("IsClick") | abs($USwipe) > 0.5) {IsClick = -1}
if(IsClick == 1 & (User:keyUse() == 0 & User:keyAttack1() == 0 & User:keyAttack2() == 0)) {stoptimer("IsClick") timer("Click",10) IsClick = 2}
if(clk("Click")) {IsClick = 0}
if((IsClick == 1 | IsClick == -1) & (User:keyUse() == 0 & User:keyAttack1() == 0 & User:keyAttack2() == 0)) {IsClick = 0}

if(User:isPlayer() & User:aimEntity() == Panel) {
    # Draggin
    USwipe = Panel:toLocal(User:aimPos()):y()
    if((User:keyUse() == 1 | User:keyAttack1() == 1 | User:keyAttack2() == 1) & User:aimEntity() == Panel & BuyStage == 0) {
        StartPos = Panel:toLocal(User:aimPos()):y()
    }
    if((User:keyUse() == 1 | User:keyAttack1() == 1 | User:keyAttack2() == 1) & User:aimEntity() == Panel & abs($USwipe) > 0.5 & BuyStage == 0) {
        MoveRate = MoveRate+($USwipe)*-1
        Selected = 0
    }
}

if(EnableSounds == 1) {
    if(abs(MoveRate) > 1 & User:isAlive() & SwipeSound == 0 & (User:keyUse() == 1 | User:keyAttack1() == 1 | User:keyAttack2() == 1)) {
        soundPlay("swipe",0,"ambient/levels/citadel/field_loop1.wav")
        SwipeSound = 1
    }
    if(SwipeSound == 1) {
        soundPitch("swipe",clamp(abs(MoveRate*5)+50,0,255))
    }
    if(SwipeSound == 1 & abs(MoveRate) <= 1 & ((User:keyUse() == 0 & User:keyAttack2() == 0 & User:keyAttack1() == 0) | User:isAlive() == 0)) {soundStop("swipe") SwipeSound = 0}
}

if(S:egpPos(Selected):y() > 256+20 & Selected != 0) {MoveRate = -4}
if(S:egpPos(Selected):y() < 256-20 & Selected != 0) {MoveRate = 4}

elseif(MoveRate > 0.1 | MoveRate < -0.1) {MoveRate = (MoveRate/1.15)}
else{MoveRate = 0}
MovePos = MovePos+MoveRate+IdleRate

# Movement
for(I=1,12) {
    local EGPiPOS = vec2(256,(Spread*MovePos + ((I-1)*(Spread*512)/12)) + -(Spread*512)*floor((Spread*MovePos + ((I-1)*(Spread*512)/12))/(Spread*512)))

    S:egpPos(I, vec2(-(512/14)/2,-(512/14)/2) + EGPiPOS)
    #holoPos(-1, Guns[I:toString(),table]["Coord",vector] + vec(0,0.75,-2) + vec(0,0,10)*(Spread-1) + S:egpToWorld(vec2(-(512/14)/2,-(512/14)/2) + vec2(1) + vec2(256,(Spread*MovePos + ((I)*(Spread*512)/12)) + -(Spread*512)*floor((Spread*MovePos + ((I)*(Spread*512)/12))/(Spread*512))) ))

    holoPos(I, entity():toWorld(
        shiftR(Guns[I:toString(),table]["Coord",vector]*vec(-1,1,-1))
        + shiftR(vec(0,0.75,-2)*vec(-1,1,-1))
        + shiftR(vec(0,0,10)*vec(-1,1,-1))*(Spread-1)
        + entity():toLocal(S:egpToWorld(vec2(-(512/14)/2,-(512/14)/2)
            + vec2(1)
            + vec2(256,(Spread*MovePos + ((I)*(Spread*512)/12)) + -(Spread*512)*floor((Spread*MovePos + ((I)*(Spread*512)/12))/(Spread*512))) )
            )
        )
    )
    
    if(Selected == I) {S:egpColor(I,vec(255,150,0))}
    elseif(inrange(User:aimPos(),entity():toWorld(entity():toLocal(S:egpToWorld(EGPiPOS)+vec(-4,-2,-6))),entity():toWorld(entity():toLocal(S:egpToWorld(EGPiPOS)+vec(4,2,2))))) {
        if(S:egpColor(I) != vec(180,100,0) & EnableSounds == 1) {Panel:soundPlay("rollover",0.5,"ui/buttonrollover.wav")}
        S:egpColor(I,vec(180,100,0))
        if(clk("Click") & BuyStage == 0 & Guns:exists(I:toString()) & Guns[I:toString(),table]["Count",number] > 0) {Selected = I timer("SelectedGun",50)}
    }
    else{
        if(Guns:exists(I:toString()) & Guns[I:toString(),table]["Count",number] > 0) {
            S:egpColor(I,vec(255))
        }
        else{
            S:egpColor(I,vec(150))
        }
    }
}

if(Selected != 0 & BuyStage == 0) {
        S:egpPos(13,ceil(vec2(0,11.9),1) + ceil(vec2(256,(Spread*MovePos + ((Selected-1)*(Spread*512)/12)) + -(Spread*512)*floor((Spread*MovePos + ((Selected-1)*(Spread*512)/12))/(Spread*512))),1))
        S:egpPos(14,round(vec2(0,0),1) + round(vec2(256,(Spread*MovePos + ((Selected-1)*(Spread*512)/12)) + -(Spread*512)*floor((Spread*MovePos + ((Selected-1)*(Spread*512)/12))/(Spread*512))),1))
        S:egpPos(15,floor(vec2(0,-11.9),1) + floor(vec2(256,(Spread*MovePos + ((Selected-1)*(Spread*512)/12)) + -(Spread*512)*floor((Spread*MovePos + ((Selected-1)*(Spread*512)/12))/(Spread*512))),1))

        local Vec = User:shootPos()+((D:entity():right():dot(D:entity():pos()-User:shootPos()))/(D:entity():right():dot(User:aimPos()-User:shootPos())))*(User:aimPos()-User:shootPos())
        local LB = entity():toLocal(D:entity():pos()+vec(-24,-2,6))
        local UB = entity():toLocal(D:entity():pos()+vec(24,2,10))

        if(inrange(entity():toLocal(Vec),vec(min(LB:x(),UB:x()),min(LB:y(),UB:y()),min(LB:z(),UB:z())),vec(max(LB:x(),UB:x()),max(LB:y(),UB:y()),max(LB:z(),UB:z()))) & BuyStage == 0) {
            D:egpColor(12,vec(255,225,180))
            if((User:keyUse() == 1 | User:keyAttack1() == 1 | User:keyAttack2() == 1)) {
                if(EnableSounds == 1) {D:entity():soundPlay("presspurchase",2,"buttons/button14.wav")}
                if(Guns[Selected:toString(),table]["Cost",number] > 0) {
                        if(Credit:exists(User:steamID()) == 0 | (Credit[User:steamID(),table]["G",number] == 0 & Credit[User:steamID(),table]["$",number] == 0)) {
                            moneyRequest(User,Guns[Selected:toString(),table]["Cost",number],"Canadian's Munitions " + Guns[Selected:toString(),table]["Name",string]+" purchase",20)
                            timer("MoneyTimeoutJIC",21000)
                            PurchaseSeconds = 19
                        }
                        elseif(Credit:exists(User:steamID()) == 1 & (Credit[User:steamID(),table]["G",number] > 0 | Credit[User:steamID(),table]["$",number] > 0)) {
                            CreditCooldown = 1
                            timer("Uncreditcooldown",500)
                            CreditCount = 1
                            CreditStage = 1
                            if(Credit[User:steamID(),table]["$",number] > 0) {CreditCount=(CreditCount+1)}
                            if(Credit[User:steamID(),table]["G",number] > 0) {CreditCount=(CreditCount+1)}
                        }
                }elseif(Guns[Selected:toString(),table]["Cost",number] == 0) {
                    timer("PseudoMoneyClk()",1000)
                }
                BuyStage = 1
                SavedUser = User
                timer("PurchaseEGP",100)
            }
        }else{
            D:egpColor(12,vec(255))
        }
        holoPos(13,entity():toWorld(vec(-59.130402,35.452133,-42.165962)+vec(2*sin(curtime()*25),2*sin(curtime()*50),0)+shiftR(Guns[Selected:toString(),table]["HoloCoord",vector])))
        holoAng(13,entity():toWorld(ang(0,90+4*sin(curtime()*100),-90)))
        if(clk("SelectedGun")) {
            soundStop("select")
            if(EnableSounds == 1) {Panel:soundPlay("select",1,"ui/buttonclick.wav")}
            S:egpAlpha(13,50)
            S:egpAlpha(14,50)
            S:egpAlpha(15,50)
            
            D:egpAlpha(1,255)
            D:egpAlpha(2,255)
            D:egpAlpha(3,255)
            D:egpAlpha(4,255)
            D:egpAlpha(5,255)
            D:egpAlpha(6,255)
            D:egpAlpha(7,255)
            D:egpAlpha(8,255)
            D:egpAlpha(12,255)
            D:egpAlpha(13,255)
            D:egpAlpha(9,50)
            D:egpAlpha(10,100)
            D:egpAlpha(11,100)
            
            AttributeText = Guns[Selected:toString(),table]["Ammo",string]
            for(FIREMODEI=1,Guns[Selected:toString(),table]["FireMode",string]:explode(","):count()) {
                AttributeText = AttributeText+"\n"+Guns[Selected:toString(),table]["FireMode",string]:explode(",")[FIREMODEI,string]
            }
            D:egpSetText(1,Guns[Selected:toString(),table]["Name",string])
            D:egpSetText(2,Guns[Selected:toString(),table]["Name",string])
            D:egpSize(1,30-(clamp(Guns[Selected:toString(),table]["Name",string]:length(),5,100)-5)*4)
            D:egpSize(2,30-(clamp(Guns[Selected:toString(),table]["Name",string]:length(),5,100)-5)*4)
            D:egpSetText(3,"$"+Guns[Selected:toString(),table]["Cost",number]:toString())
            D:egpSetText(4,"$"+Guns[Selected:toString(),table]["Cost",number]:toString())
            D:egpSetText(5,Guns[Selected:toString(),table]["Desc",string])
            D:egpSetText(6,Guns[Selected:toString(),table]["Desc",string])
            D:egpSetText(7,AttributeText)
            D:egpSetText(8,AttributeText)
            D:egpSetText(12,"Purchase " + Guns[Selected:toString(),table]["Name",string] + " for $" + Guns[Selected:toString(),table]["Cost",number]:toString())
            D:egpSetText(13,"Purchase " + Guns[Selected:toString(),table]["Name",string] + " for $" + Guns[Selected:toString(),table]["Cost",number]:toString())
            holoModel(13,Guns[Selected:toString(),table]["Model",string])
            holoAlpha(13,255)
            holoScale(13,fixVector(Guns[Selected:toString(),table]["Scale",vector]*4))
        }
        
}
elseif(holoEntity(13):getAlpha() != 0) {
    S:egpAlpha(13,0)
    S:egpAlpha(14,0)
    S:egpAlpha(15,0)
    D:egpAlpha(1,0)
    D:egpAlpha(2,0)
    D:egpAlpha(3,0)
    D:egpAlpha(4,0)
    D:egpAlpha(5,0)
    D:egpAlpha(6,0)
    D:egpAlpha(7,0)
    D:egpAlpha(8,0)

    if(BuyStage != 5) {
    D:egpAlpha(9,0)
    D:egpAlpha(10,0)
    D:egpAlpha(11,0)
    D:egpAlpha(12,0)
    D:egpAlpha(13,0)
    }
    
    holoAlpha(13,0)
}


        
if(BuyStage > 0) {
    if(PurchaseSeconds > 0 & PurchaseSecDelay == 0) {timer("PurchaseSecMinusOne",900) PurchaseSecDelay = 1}
    if(clk("PurchaseSecMinusOne")) {
        D:egpSetText(16,PurchaseSeconds:toString() + " sec")
        D:egpSetText(17,PurchaseSeconds:toString() + " sec")
        PurchaseSeconds = (PurchaseSeconds-1)
        PurchaseSecDelay = 0
    }
    
    if(clk("PurchaseEGP") & Credit:exists(User:steamID()) == 0) {
        D:egpAlpha(14,255)
        D:egpAlpha(15,255)
        D:egpAlpha(16,255)
        D:egpAlpha(17,255)
    }
    if(clk("PurchaseEGP") & Credit:exists(User:steamID()) == 1) {
        local CBI=1
        for(CBI=1,CreditCount) {
            D:egpBox(40+(10*CBI)+1,vec2(256,504+5-(32*(CBI-1))),vec2(192,24))
            D:egpAlpha(40+(10*CBI)+1,50)
            D:egpBox(40+(10*CBI)+2,vec2(256,491+5-(32*(CBI-1))),vec2(192,2))
            D:egpColor(40+(10*CBI)+2,vec())
            D:egpAlpha(40+(10*CBI)+2,100)
            D:egpBox(40+(10*CBI)+3,vec2(256,517+5-(32*(CBI-1))),vec2(192,2))
            D:egpColor(40+(10*CBI)+3,vec())
            D:egpAlpha(40+(10*CBI)+3,100)
            D:egpTextLayout(40+(10*CBI)+5,"",vec2(160,476-(32*(CBI-1)))+vec2(1),vec2(192,64))
            D:egpSize(40+(10*CBI)+5,12)
            D:egpAlign(40+(10*CBI)+5,1,1)
            D:egpColor(40+(10*CBI)+5,vec())
            D:egpAlpha(40+(10*CBI)+5,255)
            D:egpTextLayout(40+(10*CBI)+4,"",vec2(160,476-(32*(CBI-1))),vec2(192,64))
            D:egpSize(40+(10*CBI)+4,12)
            D:egpAlign(40+(10*CBI)+4,1,1)
            D:egpAlpha(40+(10*CBI)+4,255)
        }
        D:egpSetText(55,"Purchase normally\n(with your own wallet money)")
        D:egpSetText(54,"Purchase normally\n(with your own wallet money)")
        if(CreditCount == 2) {
            if(Credit[User:steamID(),table]["$",number] > 0) {
                D:egpSetText(65,"Purchase with monetary credit\n($" + Credit[User:steamID(),table]["$",number]:toString() + " available)")
                D:egpSetText(64,"Purchase with monetary credit\n($" + Credit[User:steamID(),table]["$",number]:toString() + " available)")
            }
            else{
                D:egpSetText(65,"Purchase with free gun credit\n(" + Credit[User:steamID(),table]["G",number]:toString() + " available)")
                D:egpSetText(64,"Purchase with free gun credit\n(" + Credit[User:steamID(),table]["G",number]:toString() + " available)")
            }
        }
        else{
            D:egpSetText(65,"Purchase with monetary credit\n($" + Credit[User:steamID(),table]["$",number]:toString() + " available)")
            D:egpSetText(64,"Purchase with monetary credit\n($" + Credit[User:steamID(),table]["$",number]:toString() + " available)")
            D:egpSetText(75,"Purchase with free gun credit\n(" + Credit[User:steamID(),table]["G",number]:toString() + " available)")
            D:egpSetText(74,"Purchase with free gun credit\n(" + Credit[User:steamID(),table]["G",number]:toString() + " available)")
        }
    }
    
    if(BuyStage == 1 & CreditStage == 1) {
        local CAI=1
        local Vec = User:shootPos()+((D:entity():right():dot(D:entity():pos()-User:shootPos()))/(D:entity():right():dot(User:aimPos()-User:shootPos())))*(User:aimPos()-User:shootPos())

        for(CAI=1,CreditCount) {
            local LB = entity():toLocal(D:entity():pos()+vec(-24,-2,5+((CAI-1)*8)))
            local UB = entity():toLocal(D:entity():pos()+vec(24,2,11+((CAI-1)*8)))
            if(inrange(entity():toLocal(Vec),vec(min(LB:x(),UB:x()),min(LB:y(),UB:y()),min(LB:z(),UB:z())),vec(max(LB:x(),UB:x()),max(LB:y(),UB:y()),max(LB:z(),UB:z())))) {
                D:egpColor(40+(10*CAI)+4,vec(255,225,180))
                if(CreditCooldown == 0 & (User:keyUse() == 1 | User:keyAttack1() == 1 | User:keyAttack2() == 1)) {
                    local DelCreditI=1
                    for(DelCreditI=50,79) {D:egpRemove(DelCreditI)}
                    if(CAI==1) {
                        # Normal wallet cash
                        moneyRequest(User,Guns[Selected:toString(),table]["Cost",number],"Canadian's Munitions " + Guns[Selected:toString(),table]["Name",string]+" purchase",20)
                        timer("MoneyTimeoutJIC",21000)
                        PurchaseSeconds = 19
                    }
                    elseif(CAI == 2 & CreditCount == 2 & Credit[User:steamID(),table]["$",number] > 0) {
                        # Monetary credit
                        if(Guns[Selected:toString(),table]["Cost",number] > Credit[User:steamID(),table]["$",number]) {
                            moneyRequest(User,Guns[Selected:toString(),table]["Cost",number]-Credit[User:steamID(),table]["$",number],"Canadian's Munitions " + Guns[Selected:toString(),table]["Name",string]+" purchase",20)
                            LimboCredit = 1
                            timer("MoneyTimeoutJIC",21000)
                            PurchaseSeconds = 19
                        }
                        else{
                            timer("PseudoMoneyClk()",1000)
                            Credit[User:steamID(),table] = table("G"=clamp(Credit[User:steamID(),table]:clone()["G",number],0,1000000000),"$"=clamp(Credit[User:steamID(),table]:clone()["$",number]-Guns[Selected:toString(),table]["Cost",number],0,1000000000))
                        }
                    }
                    elseif(CAI == 2 & CreditCount == 2 & Credit[User:steamID(),table]["G",number] > 0) {
                        #Gun credit
                        timer("PseudoMoneyClk()",1000)
                        Credit[User:steamID(),table] = table("G"=clamp(Credit[User:steamID(),table]:clone()["G",number]-1,0,1000000000),"$"=clamp(Credit[User:steamID(),table]:clone()["$",number],0,1000000000))
                    }
                    elseif(CreditCount == 3) {
                        if(CAI == 2) {
                            # Monetary credit:
                            if(Guns[Selected:toString(),table]["Cost",number] > Credit[User:steamID(),table]["$",number]) {
                                moneyRequest(User,Guns[Selected:toString(),table]["Cost",number]-Credit[User:steamID(),table]["$",number],"Canadian's Munitions " + Guns[Selected:toString(),table]["Name",string]+" purchase",20)
                                LimboCredit = 1
                                timer("MoneyTimeoutJIC",21000)
                                PurchaseSeconds = 19
                            }
                            else{
                                timer("PseudoMoneyClk()",1000)
                                Credit[User:steamID(),table] = table("G"=clamp(Credit[User:steamID(),table]:clone()["G",number],0,1000000000),"$"=clamp(Credit[User:steamID(),table]:clone()["$",number]-Guns[Selected:toString(),table]["Cost",number],0,1000000000))
                            }
                        }
                        if(CAI == 3) {
                            # Gun credit
                            timer("PseudoMoneyClk()",1000)
                            Credit[User:steamID(),table] = table("G"=clamp(Credit[User:steamID(),table]:clone()["G",number]-1,0,1000000000),"$"=clamp(Credit[User:steamID(),table]:clone()["$",number],0,1000000000))
                        }
                    }
                    
                }
            }
            else{D:egpColor(40+(10*CAI)+4,vec(255,255,255))}
        }
    }
    
    if(moneyNoClk()
     | moneyTimeout()
     | (User:isPlayer() == 0 & BuyStage != 2)
     | (CreditStage == 1 & (
         (User:isPlayer() & User:pos():distance(entity():toWorld(vec(0,50,0))) > 200)
         | User:isPlayer() == 0))
     | clk("MoneyTimeoutJIC")) {
        local DelCreditI=1
        for(DelCreditI=50,79) {D:egpRemove(DelCreditI)}
        BuyStage = 2
        PurchaseSeconds = 5
        PurchaseSecDelay = 0
        CreditStage = 0 CreditCount = 0 LimboCredit = 0
        stoptimer("MoneyTimeoutJIC")
        D:egpAlpha(14,0)
        D:egpAlpha(15,0)
        D:egpAlpha(16,0)
        D:egpAlpha(17,0)
        D:egpAlpha(18,255)
        D:egpAlpha(19,255)
    }
        
    if(BuyStage == 2) {
        D:egpSetText(18,"Purchase cancelled,\nreturning to menu in " + (PurchaseSeconds):toString() + "...")
        D:egpSetText(19,"Purchase cancelled,\nreturning to menu in " + (PurchaseSeconds):toString() + "...")
    }
    
    if(BuyStage == 2 & PurchaseSeconds == 0) {
        User = noentity()
        SavedUser = noentity()
        stoptimer("LongTimeout")
        Selected = 0
        BuyStage = 0
        PurchaseSeconds = 19
        PurchaseSecDelay = 0
        D:egpAlpha(18,0)
        D:egpAlpha(19,0)
    }
    
    if(moneyClk() | clk("PseudoMoneyClk()")) {
        CreditStage = 0
        if(LimboCredit == 1) {
            Credit[User:steamID(),table] = table("G"=clamp(Credit[User:steamID(),table]:clone()["G",number],0,1000000000),"$"=clamp(Credit[User:steamID(),table]:clone()["$",number]-Guns[Selected:toString(),table]["Cost",number],0,1000000000))
        }
        timer("UpdateFile",100)
        print(User:name() + " has purchased a " + Guns[Selected:toString(),table]["Name",string] + "!")
        dsSendDirect(GN,GUNE2,Guns[Selected:toString(),table]["Slot",string])
        stoptimer("MoneyTimeoutJIC")
        PurchaseSeconds = 0
        PurchaseSecDelay = 0
        stoptimer("LongTimeout")
        BuyStage = 3
        D:egpAlpha(14,0)
        D:egpAlpha(15,0)
        D:egpAlpha(16,0)
        D:egpAlpha(17,0)
        D:egpAlpha(18,255)
        D:egpAlpha(19,255)
        D:egpAlpha(20,255)
        D:egpAlpha(21,255)
        D:egpSetText(18,"Purchase successful!")
        D:egpSetText(19,"Purchase successful!")
        D:egpSetText(20,"Delivering " + Guns[Selected:toString(),table]["Name",string]+ " now!")
        D:egpSetText(21,"Delivering " + Guns[Selected:toString(),table]["Name",string]+ " now!")
        timer("FadePurchaseSuccess",3000)
    }
    
    if(clk("FadePurchaseSuccess")) {
        BuyStage = 4
    }
    if(BuyStage == 4 & D:egpAlpha(18) > 0) {
        D:egpAlpha(18,clamp(D:egpAlpha(18)-15,0,255))
        D:egpAlpha(19,clamp(D:egpAlpha(18)-15,0,255))
    }
    if(BuyStage == 4 & D:egpAlpha(18) == 0) {
        BuyStage = 5
    }
    if((BuyStage == 5 & MoveUpTheta < pi()) | (MoveUpTheta > 0 & BuyStage == 6)) {
        if(BuyStage == 5) {
            MoveUpTheta = clamp(MoveUpTheta+0.1,0,pi())
        }
        if(BuyStage == 6) {
            MoveUpTheta = clamp(MoveUpTheta-0.1,0,pi())
        }
        D:egpPos(20,vec2(160,256+128+16)+vec2(1)+vec2(0,-72*(-sinr(MoveUpTheta+pi()/2)+1)/2))
        D:egpPos(21,vec2(160,256+128+16)+vec2(0)+vec2(0,-72*(-sinr(MoveUpTheta+pi()/2)+1)/2))
    }
    
    
    
    if(dsGetString() == "abouttospawngun") {
        CheckNearby = 1
    }
    
    if(CheckNearby == 1 & findCanQuery()) {
        findClearBlackList()
        findByClass("player")
        findSortByDistance(entity():toWorld(vec(0,50,0)))
        NearbyGun = findToArray()
    }
    
    if(CheckNearby == 1) {
        for(NGI=1,clamp(NearbyGun:count(),1,8)) {
            
            if(NearbyGun[NGI,entity]:pos():distance(entity():pos()) < 250 & NearbyGun[NGI,entity] != owner() & NearbyGun[NGI,entity] != User & SpawnAnyway == 0) {
                if(NearbyGunT:exists(NearbyGun[NGI,entity]:steamID()) == 0) {
                    NearbyGunT[NearbyGun[NGI,entity]:steamID(),entity] = NearbyGun[NGI,entity]
                }
            }
            else{
                if(NearbyGunT:exists(NearbyGun[NGI,entity]:steamID()) == 1) {
                    NearbyGunT:remove(NearbyGun[NGI,entity]:steamID())
                }
            }
            
            if(NearbyGunT:count() > 0 & WaitingNearby == 0) {
                dsSendDirect(GN,GUNE2,"waitnearby")
                D:egpAlpha(23,255)
                D:egpAlpha(24,255)
                D:egpSetText(12,"Spawn anyway")
                D:egpSetText(13,"Spawn anyway")
                D:egpAlpha(12,255)
                D:egpAlpha(13,255)
                D:egpAlpha(9,50)
                D:egpAlpha(10,100)
                D:egpAlpha(11,100)
                WaitingNearby = 1
            }
            if(NearbyGunT:count() == 0 & WaitingNearby == 1) {
                WaitingNearby = 0
                D:egpAlpha(12,0)
                D:egpAlpha(13,0)
                D:egpAlpha(9,0)
                D:egpAlpha(10,0)
                D:egpAlpha(11,0)
                D:egpAlpha(23,0)
                D:egpAlpha(24,0)
                dsSendDirect(GN,GUNE2,"unwaitnearby")
            }
        }
        
        local Vec = User:shootPos()+((D:entity():right():dot(D:entity():pos()-User:shootPos()))/(D:entity():right():dot(User:aimPos()-User:shootPos())))*(User:aimPos()-User:shootPos())
        local LB = entity():toLocal(D:entity():pos()+vec(-24,-2,6))
        local UB = entity():toLocal(D:entity():pos()+vec(24,2,10))

        if((User:isPlayer() == 0 | (inrange(entity():toLocal(Vec),vec(min(LB:x(),UB:x()),min(LB:y(),UB:y()),min(LB:z(),UB:z())),vec(max(LB:x(),UB:x()),max(LB:y(),UB:y()),max(LB:z(),UB:z()))))) & SpawnAnyway == 0) {
            D:egpColor(12,vec(255,225,180))
            if((User:keyUse() == 1 | User:keyAttack1() == 1 | User:keyAttack2() == 1) | User:isPlayer() == 0) {
                SpawnAnyway = 1
                NearbyGunT:clear()
            }
        }else{
            D:egpColor(12,vec(255))
        }
    }

    if(BuyStage == 5 & dsGetString() == "spawnedgun") {
        D:egpAlpha(12,0)
        D:egpAlpha(13,0)
        D:egpAlpha(9,0)
        D:egpAlpha(10,0)
        D:egpAlpha(11,0)
        D:egpAlpha(23,0)
        D:egpAlpha(24,0)
        CheckNearby = 0
        NearbyGunT:clear()
        Guns[Selected:toString(),table]["Count",number] = (Guns[Selected:toString(),table]["Count",number]-1)
        D:egpSetText(20,"Thank you for shopping at Canadian's Munitions, have a great day!")
        D:egpSetText(21,"Thank you for shopping at Canadian's Munitions, have a great day!")
        BuyStage = 6
        timer("CheckStock",100)
    }
    
    if(clk("CheckStock")) {
        if(Guns[Selected:toString(),table]["Count",number] < 1) {
            S:egpSetText(Selected,"NO STOCK")
            S:egpColor(Selected,vec(150))
            holoDelete(Selected)
            timer("sendnostock",3000)
        }
        #else{timer("YesStockRestart",100)}
    }
    
    if(clk("sendnostock")) {
        dsSendDirect(GN,GUNE2,"nostock")
    }
    
    
    if(BuyStage == 6 & (dsGetString() == "readynextgun" | clk("YesStockRestart"))) {
        CreditStage = 0 CreditCount = 0 LimboCredit = 0
        SpawnAnyway = 0
        CheckNearby = 0
        User = noentity()
        SavedUser = noentity()
        NearbyGunT:clear()
        Selected = 0
        BuyStage = 0
        PurchaseSeconds = 19
        PurchaseSecDelay = 0
        MoveUpTheta = 0
        D:egpAlpha(18,0)
        D:egpAlpha(19,0)
        D:egpAlpha(20,0)
        D:egpAlpha(21,0)
    }
    
}

D:egpAlpha(22,LogOutAlpha)
if(LogOutAlpha > 0) {LogOutAlpha = clamp(LogOutAlpha-5,0,255)}

if(IdleStatus != 0) {
    if(IdleStatus == 1) {AimFadeGuns = 25 S:egpSetText(20,"Hold E and Swipe to scroll") S:egpSize(20,12)}
    if(IdleStatus == 1 & FadeGuns == 25) {
        IdleStatus = 2
        timer("HoldEMessage",6000)
        S:egpSetText(20,"Hold E and Swipe to scroll")
        S:egpSize(20,12)
        S:egpAlpha(21,255)
        S:egpAlpha(22,255)
        S:egpAlpha(23,20)
        }
    if(IdleStatus == 2) {
        if(S:egpPos(22):y() < 295) {
            S:egpPos(22,vec2(256,350))
            S:egpPos(21,vec2(256.5,350+20))
        }
        else{
            S:egpPos(22,vec2(256,S:egpPos(22):y()-4))
            S:egpPos(21,vec2(256.5,S:egpPos(21):y()-4))
        }
        if(ScanStage == 0) {S:egpLine(23,vec2(256,350+20),vec2(256,S:egpPos(21):y()+8))}
    }
    if(clk("HoldEMessage")) {
        IdleStatus = 3
        S:egpSetText(20,"Press USE to begin")
        S:egpSize(20,16)
        S:egpAlpha(21,0) S:egpAlpha(22,0) S:egpAlpha(23,0)
        timer("SwipeMessage",3000)
    }
    if(clk("SwipeMessage")) {IdleStatus = 1}
    
    
#[    if(IdleStatus == 1) {AimFadeGuns = 25}
    if(IdleStatus == 1 & FadeGuns == 25) {IdleStatus = 2 S:egpSetText(20,"Press USE to begin") timer("SwipeIdleText",2000) timer("IdleShowCursor",500)}
    if(clk("IdleShowCursor")) {S:egpAlpha(22,255)}
    if(clk("SwipeIdleText")) {S:egpSetText(20,"Hold and Swipe to scroll") S:egpSize(20,12) timer("SwipeArrowIdle",1000)}
    if(clk("SwipeArrowIdle")) {S:egpAlpha(21,255) S:egpAlpha(23,20) IdleStatus = 3 timer("BackToIdle1",6000)}
    if(IdleStatus == 1) {
        if(S:egpPos(22):y() < 295) {
            S:egpPos(22,vec2(256,350))
            S:egpPos(21,vec2(256.5,350+20))
        }
        else{
            S:egpPos(22,vec2(256,S:egpPos(22):y()-4))
            S:egpPos(21,vec2(256.5,S:egpPos(21):y()-4))
        }
        S:egpLine(23,vec2(256,350+20),vec2(256,S:egpPos(21):y()+8))
    }
    if(clk("BackToIdle1")) {
        IdleStatus = 1
        S:egpSetText(20,"Press USE to begin")
        S:egpSize(20,16)
        S:egpAlpha(21,0) S:egpAlpha(22,0) S:egpAlpha(23,0)
    }]#
}
elseif(AimFadeGuns != 255) {
    S:egpSetText(20,"Press USE to begin")
    stoptimer("BackToIdle1")
    stoptimer("IdleShowCursor")
    stoptimer("SwipeArrowIdle")
    AimFadeGuns = 255
    S:egpAlpha(20,0)
    S:egpAlpha(21,0)
    S:egpAlpha(22,0)
    S:egpAlpha(23,0)
}

if(FadeGuns > AimFadeGuns) {FadeGuns = clamp(FadeGuns-10,25,255)}
if(FadeGuns < AimFadeGuns) {FadeGuns = clamp(FadeGuns+20,25,255)}

if(holoEntity(1):getAlpha() != FadeGuns) {
    for(IFI=1,12) {
        S:egpAlpha(IFI,FadeGuns)
        holoAlpha(IFI,clamp(FadeGuns,50,255))
    }
    S:egpAlpha(20,255-clamp(FadeGuns*1.5,0,255))
}


#@outputs Credit:table
#@persist DSCredit:string

if(dsGetString():explode(" ")[1,string] == "credit") {
    DSCredit = dsGetString():explode(" ")
    print("Successfully added " + (DSCredit[3,string]:index(1) == "$" ? DSCredit[3,string] : DSCredit[3,string]+" guns") + " of credit to " + DSCredit[2,string] + "'s account.")
    if(Credit:exists(DSCredit[2,string]) == 0) {
        if(DSCredit[3,string]:index(1) == "$") {
            Credit[DSCredit[2,string],table] = table("$"=DSCredit[3,string]:sub(2):toNumber(),"G"=0)
        }else{
            Credit[DSCredit[2,string],table] = table("G"=DSCredit[3,string]:toNumber(),"$"=0)
        }
    }
    else{
        if(DSCredit[3,string]:index(1) == "$") {
            Credit[DSCredit[2,string],table] = table("G"=clamp(Credit[DSCredit[2,string],table]:clone()["G",number],0,1000000000),"$"=clamp(Credit[DSCredit[2,string],table]:clone()["$",number]+DSCredit[3,string]:sub(2):toNumber(),0,1000000000))
        }else{
            Credit[DSCredit[2,string],table] = table("G"=clamp(Credit[DSCredit[2,string],table]:clone()["G",number]+DSCredit[3,string]:toNumber(),0,1000000000),"$"=clamp(Credit[DSCredit[2,string],table]:clone()["$",number],0,1000000000))
        }
    }
    timer("UpdateFile",100)
}
elseif(dsGetString() == "creditall") {
    if(Credit:count() < 1) {
        print("All existing credit:\n       No accounts exist.")
    }
    else{
        local K=0
        print("All existing credit:")
        for(K=1,Credit:count()) {
            print("     " + Credit:keys()[K,string]+": $"+Credit[Credit:keys()[K,string],table]["$",number]:toString() + ", " + Credit[Credit:keys()[K,string],table]["G",number]:toString() + " free gun"+(Credit[Credit:keys()[K,string],table]["G",number] == 1 ? "" : "s") +".")
        }
    }
}
elseif(dsGetString():explode(" ")[1,string] == "creditcheck") {
    DSCredit = dsGetString():explode(" ")
    print(DSCredit[3,string] + "'s current credit standings:")
    if(Credit:exists(DSCredit[2,string]) == 0) {
        print("     -Player has not been associated with any credit.")
    }else{
        print("     -Monetary credit: $" + Credit[DSCredit[2,string],table]["$",number]:toString())
        print("     -Free guns credit: " + Credit[DSCredit[2,string],table]["G",number]:toString())
    }
}
elseif(dsGetString() == "creditreset") {
    print("All " + Credit:count() + " account" + (Credit:count() != 1 ? "s" : "") + " of credit has successfully been cleared.")
    Credit:clear()
    timer("UpdateFile",100)
}
elseif(dsGetString():sub(1,12) == "creditremove") {
    if(Credit:exists(dsGetString():explode(" ")[2,string])) {
        Credit:remove(dsGetString():explode(" ")[2,string])
        print("Credit account \"" + dsGetString():explode(" ")[2,string] + "\" was removed/cleared successfully.")
        timer("UpdateFile",100)
    }
    else{
        print("Error: Credit account \"" + dsGetString():explode(" ")[2,string] + "\" not found!")
    }
}
elseif(dsGetString() == "creditclean") {
    local L=0
    local DelCount=0
    for(L=1,Credit:keys():count()) {
        if(Credit:keys()[L,string]:sub(1,5) == "STEAM" & Credit[Credit:keys()[L,string],table]["$",number] == 0 & Credit[Credit:keys()[L,string],table]["G",number] == 0) {
            Credit:remove(Credit:keys()[L,string])
            DelCount=(DelCount+1)
        }
    }
    timer("UpdateFile",100)
    print(DelCount:toString() + " credit account" + (DelCount!=1 ? "s" : "") +" with $0 and 0 free guns have been deleted successfully.")
}
if(SaveCreditType == "GUNE2" & dsGetString():sub(1,11) == "savedcredit") {
    print("Credit data has successfully been transfered from GUNE2.")
    Credit = vonDecodeTable(dsGetString():sub(13)):clone()
}

if(SaveCreditType == "FILE") {
    if(first()) {
        fileLoad("armshopcredit.txt")
        timer("FileTimeout",10000)
        FileStage = 1
    }
    if(FileStage == 1 & (fileStatus() == 2 | fileStatus() == 3 | fileStatus() == 4 | clk("FileTimeout"))) {
        print("Error: Credit data file failed to load.")
        stoptimer("FileTimeout")
        if(fileStatus() == 3) {
            print("     -New file will be created.")
            FileStage = 4
        }else{
            print("     -Please investigate. New file will not created/data will not save.")
            FileStage = 2
        }
    }
    if(FileStage == 1 & fileLoaded()) {
        stoptimer("FileTimeout")
        if(Credit:count() > 0) {
            print("Error: Credit data loaded from file, but data already exists.\n               (Local data has been overriden.)")
            FileStage = 3
        }elseif(vonDecodeTable(fileRead()):clone():count() == 0) {
            print("Warning: Credit data loaded from file, but was empty.\n                (File should work regardless)")
            FileStage = 4
        }
        else{
            Credit = vonDecodeTable(fileRead()):clone()
            if(Credit:count() != 1) {
                print(Credit:count():toString() + " entries of credit data loaded successfully from disk!") 
            }else{
                print(Credit:count():toString() + " entry of credit data loaded successfully from disk!") 
            }
            FileStage = 4
        }
    }
    if(clk("UpdateFile") & (fileCanWrite() == 0 | FileStage != 4)) {print("Warning: Credit data was unable to be saved to file with the last try.")}
    if(clk("UpdateFile") & fileCanWrite() == 1 & FileStage == 4) {
        fileWrite("armshopcredit.txt",vonEncode(Credit:clone()))
        print("Credit data saved successfully to file.")
    }
}
if(clk("Uncreditcooldown")) {CreditCooldown = 0}

#[
    # Before Spread
    S:egpPos(I,vec2(-(512/14)/2,-(512/14)/2) + vec2(256,(MovePos + ((I-1)*512/12)) + -512*floor((MovePos + ((I-1)*512/12))/512)))
    holoPos(I, Guns[I:toString(),table]["Coord",vector] + vec(0,-1,-2) + S:egpToWorld(vec2(-(512/14)/2,-(512/14)/2) + vec2(1) + vec2(256,(MovePos + ((I)*512/12)) + -512*floor((MovePos + ((I)*512/12))/512))) )

