   long int id_y = (k     * c_Size.y + j + 1)* c_Size.x + i;
   long int id_z = ((k+1) * c_Size.y + j)    * c_Size.x + i;
 
-  grad_x[id] = in[id_x] - in[id];
-  grad_y[id] = in[id_y] - in[id];
-  grad_z[id] = in[id_z] - in[id];
+  if (i == (c_Size.x - 1)) grad_x[id] = 0;
+  else grad_x[id] = in[id_x] - in[id];
+
+  if (j == (c_Size.y - 1)) grad_y[id] = 0;
+  else grad_y[id] = in[id_y] - in[id];
+
+  if (k == (c_Size.z - 1)) grad_z[id] = 0;
+  else grad_z[id] = in[id_z] - in[id];
 }
 
 __global__

  if (i == (c_Size.x - 1)) A.x = 0;
  else A.x = grad_x[id];

  if (i == 0) B.y = 0;
  else B.y = grad_y[id_y];
  if (i == (c_Size.y - 1)) A.y = 0;
  else A.y = grad_y[id];

  if (i == 0) B.z = 0;
  else B.z = grad_z[id_z];
  if (i == (c_Size.z - 1)) A.z = 0;
  else A.z = grad_z[id];

  out[id] = A.x - B.x + A.y - B.y + A.z - B.z;

  long int id_y = (k     * c_Size.y + j + 1)* c_Size.x + i;
  long int id_z = ((k+1) * c_Size.y + j)    * c_Size.x + i;

  if (i != (c_Size.x - 1)) grad_x[id] -= (in[id_x] - in[id]);
  if (j != (c_Size.y - 1)) grad_y[id] -= (in[id_y] - in[id]);
  if (k != (c_Size.z - 1)) grad_z[id] -= (in[id_z] - in[id]);
}

__global__
