#@name egp_tetris_test
@inputs 
@outputs [SpawnIndex SpawnRow SpawnCol MaxRow MaxCol]
@persist [SpawnIndex SpawnRow SpawnCol MaxRow MaxCol] EGP:wirelink [NextRow NextCol NextIndex NextStep]
@trigger none

if (first()) {
    
    MaxRow = 22
    MaxCol = 10
    
    EGP = entity():isWeldedTo():wirelink()
    EGP:egpClear()    
    EGP:entity():setMaterial("effects/ar2_altfire1b")
    
    NextStep = curtime()
    
    function number getID( R, C ) {
        return (R - 0)*10 + C + 1
    }
}

interval(15)

if (SpawnRow < MaxRow & egpCanSendUmsg()) {
    if (SpawnCol < MaxCol) {
        SpawnCol++

        SpawnIndex++
        
        local Pos = vec2(SpawnCol*22 + 256 - MaxRow*22/4, (SpawnRow + 1)*22 + 2)
        local Size = vec2(21, 21)

        EGP:egpBox(SpawnIndex, Pos, Size)
        EGP:egpColor(SpawnIndex, vec(100))
    }
    else {
        SpawnCol = 0    
        SpawnRow++
    }
}
else {
    local L = owner():keyPressed("right") - owner():keyPressed("left")
    if (egpCanSendUmsg() & changed(L) & L) {
        
        EGP:egpColor(NextIndex, vec(100))
        
        NextCol = clamp(NextCol + L, 0, MaxCol - 1)
        NextIndex = getID(NextRow, NextCol)
        
        EGP:egpColor(NextIndex, vec(255, 255, 0))
    }

    if (egpCanSendUmsg() & curtime() - NextStep > 0.1) {
        NextStep = curtime()

        NextRow = (NextRow + 1) % MaxRow
        if (NextRow == 0) {
            NextCol = 0    
        }
        else {
            EGP:egpColor(NextIndex, vec(100))
        }

        NextIndex = getID(NextRow, NextCol)
        
        EGP:egpColor(NextIndex, vec(255, 255, 0))
    }
}
