tiles_layer2={
    surf = nil,
    tiles = {},
}

function tiles_layer2.new(_hab, _x, _y, _tx, _ty, _tw, _th, _anim, _draw)
    local world_x, world_y = coords.room_to_world(_hab,_x,_y)

    table.insert( 
        tiles_layer2.tiles,
        { hab = _hab,
            x = world_x,
            y = world_y,
            w = _tw,
            h = _th,
            tx = _tx,
            ty = _ty,
            tw = _tw,
            th = _th,
            off_x = 0,
            off_y = 0,
            draw = _draw,
            anim = _anim,
            anim_started = false,
        }
    )
end

function tiles_layer2.draw_tile( tile )
    local curr_surf = surf.source() 
    if tiles_layer2.surf ~= nil then
        surf.source(tiles_layer2.surf)
    end
    local scr_x, scr_y = viewp:screen_coords( tile.x, tile.y )
    draw.surf(tile.tx, tile.ty, tile.tw, tile.th,
              scr_x, scr_y, tile.tw, tile.th)
    surf.source(curr_surf)
end

function tiles_layer2.draw()
    for i, tile in ipairs(tiles_layer2.tiles) do
        if viewp:inside(tile.x, tile.y, tile.w, tile.h) then
            if tile.draw == nil then
                tiles_layer2.draw_tile(tile)
            else
                tile.draw(tile)
            end
        end
    end
end

function tiles_layer2.update()
    for i, tile in ipairs(tiles_layer2.tiles) do
        if viewp:inside(tile.x, tile.y, tile.w, tile.h) then
            if tile.anim ~= nil then
                tile.anim(tile)
            end
        end
    end
end

function tiles_layer2.draw_aranya(tile)
    local curr_surf = surf.source() 
    if tiles_layer2.surf ~= nil then
        surf.source(tiles_layer2.surf)
    end
    local scr_x, scr_y = viewp:screen_coords( tile.x, tile.y )
    draw.line(scr_x+11, scr_y, scr_x+11+tile.off_x, scr_y+tile.off_y, 2)
    draw.surf(tile.tx, tile.ty, tile.tw, tile.th,
              scr_x+tile.off_x, scr_y+tile.off_y, tile.tw, tile.th)
    surf.source(curr_surf)
end

function tiles_layer2.update_aranya(tile)
    if not tile.anim_started then
        tile.wait = 6
        tile.step = 0
        tile.off_x= 0
        tile.off_y= 0
        tile.next_move = 16
        tile.vy = 1
        tile.anim_started = true
    end
    
    tile.wait = tile.wait + 1
    if tile.wait>=6 then
        tile.wait = 0
        if tile.off_y==0 or tile.off_y==8 then
            tile.next_move = tile.next_move - 1
            if tile.next_move<=0 then
                tile.next_move = 16+math.random(64)
                if tile.off_y==0 then
                    tile.vy = 1
                else
                    tile.vy = -1
                end
                tile.off_y = tile.off_y + tile.vy
            end
        else
            tile.off_y = tile.off_y + tile.vy 
        end
    end
end