     const long int min_out_x = offset_x + last_x*shift_x;
     const long int min_out_y = offset_y + last_y*shift_y;
 
-    for(long int out_x = 0; out_x < length_x; out_x++)
-    {
-        if((out_x + min_out_x < 0) || (out_x + min_out_x >= output_size_x))
-        {
-            continue;
-        }
-
-        for(long int out_y = 0; out_y < length_y; out_y++)
-        {
-            if((out_y + min_out_y < 0) || (out_y + min_out_y >= output_size_y))
-            {
-                continue;
-            }
-
+    const long int min_x = (min_out_x < 0) ? -min_out_x : 0;
+    const long int min_y = (min_out_y < 0) ? -min_out_y : 0;
+
+    const long int max_x = (length_x + min_out_x > output_size_x) ? output_size_x - min_out_x : length_x;
+    const long int max_y = (length_y + min_out_y > output_size_y) ? output_size_y - min_out_y : length_y;
+
+    for(long int out_x = min_x; out_x < max_x; out_x++)
+    {
+        for(long int out_y = min_y; out_y < max_y; out_y++)
+        {
             for(size_t out_z = 0; out_z < output_size_z; out_z++)
             {
                 size_t i = (out_x + min_out_x)*output_size_y*output_size_z + (out_y + min_out_y)*output_size_z + out_z;


    const size_t local_n = last_x*gridDim.y*gridDim.z + last_y*gridDim.z + last_z;
    const size_t global_n = last_x*gridDim.y*num_chunks*gridDim.z + last_y*num_chunks*gridDim.z + chunk_counter*gridDim.z + last_z;
    const long int min_out_x = offset_x + last_x*shift_x;
    const long int min_out_y = offset_y + last_y*shift_y;

    float_type res_sup = sup_cst[local_n];

    float_type tmp1, tmp2;

    for(long int out_x = 0; out_x < length_x; out_x++)
    {
        if((out_x + min_out_x < 0) || (out_x + min_out_x >= output_size_x))
        {
            continue;
        }

        for(long int out_y = 0; out_y < length_y; out_y++)
        {
            if((out_y + min_out_y < 0) || (out_y + min_out_y >= output_size_y))
            {
                continue;
            }

            for(size_t out_z = 0; out_z < output_size_z; out_z++)
            {
                size_t i = (out_x + min_out_x)*output_size_y*output_size_z + (out_y + min_out_y)*output_size_z + out_z;

    const long int min_out_x = offset_x + last_x*shift_x;
    const long int min_out_y = offset_y + last_y*shift_y;

    const long int min_x = (min_out_x < 0) ? -min_out_x : 0;
    const long int min_y = (min_out_y < 0) ? -min_out_y : 0;

    const long int max_x = (length_x + min_out_x > output_size_x) ? output_size_x - min_out_x : length_x;
    const long int max_y = (length_y + min_out_y > output_size_y) ? output_size_y - min_out_y : length_y;

    for(long int out_x = min_x; out_x < max_x; out_x++)
    {
        for(long int out_y = min_y; out_y < max_y; out_y++)
        {
            for(size_t out_z = 0; out_z < output_size_z; out_z++)
            {
                size_t i = (out_x + min_out_x)*output_size_y*output_size_z + (out_y + min_out_y)*output_size_z + out_z;
