local param2_rotate90 = { [0]=3, [1]=0, [2]=1, [3]=2 };

local function offset_vector(pos, offset, side_dir, front_dir)
    local new_pos = vector.new(pos);
    
    if (offset ~= vector.new(0, 0, 0)) then
        if (offset.x < 0) then
            new_pos = vector.add(new_pos, vector.round(side_dir)*math.abs(offset.x));
        elseif (offset.x > 0) then
            new_pos = vector.subtract(new_pos, vector.round(side_dir)*offset.x);
        end;
            
        if (offset.z > 0) then
            new_pos = vector.add(new_pos, vector.round(front_dir)*math.abs(offset.z));
        elseif (offset.z < 0) then
            new_pos = vector.subtract(new_pos, vector.round(front_dir)*offset.z);
        end;
            
        new_pos.y = pos.y + offset.y;
    end;
    
    return new_pos;
end;

-- GET NODE MAP
function warp_portal.get_node_map(pos, map)
    local node = core.get_node(pos);
    local front_dir = core.facedir_to_dir(node.param2%4);
    local side_dir = core.facedir_to_dir(param2_rotate90[node.param2%4]);
    
    local result = {};
    
    for i, offset in pairs(map) do
        local new_pos = offset_vector(pos, offset, side_dir, front_dir);
        local node = core.get_node(new_pos);
        table.insert(result, {name=node.name, node=node, pos=new_pos, param2=node.param2});
    end;
    
    return result;
end;

-- SET NODE MAP
function warp_portal.set_node_map(pos, name, map, swap)
    local node = core.get_node(pos);
    local front_dir = core.facedir_to_dir(node.param2%4);
    local side_dir = core.facedir_to_dir(param2_rotate90[node.param2%4]);
    
    for i, offset in pairs(map) do
        if swap then
            core.swap_node(offset_vector(pos, offset, side_dir, front_dir), {name=name});
        else
            core.set_node(offset_vector(pos, offset, side_dir, front_dir), {name=name});
        end;
    end;
    
end;