function data = adjustForOutOfBoundary(pos, outDir, update)
% pos: Data
% outDir: Dir in which the adjusted images will be written.
% update: if true, then create updated images and refer to them in data.
%   else throw and error.
imrows = pos(1).size.nrows;
imcols = pos(1).size.ncols;
minx = min([pos.x1]);
miny = min([pos.y1]);
maxx = max([pos.x2]);
maxy = max([pos.y2]);

lPad = 0;
rPad = 0;
tPad = 0;
bPad = 0;

if minx < 1
  lPad = -minx + 1;
end
if miny < 1
  tPad = -miny + 1;
end
if maxx > imcols
  rPad = maxx - imcols;
end
if maxy > imrows
  bPad = maxy - imrows;
end

data = pos;
if update
  data = updateData(pos, lPad, rPad, tPad, bPad, outDir);
elseif lPad > 0 || tPad > 0 || rPad > 0 || bPad > 0
  error('Padding required, but disallowed.');
end
end

function pos = updateData(pos, lPad, rPad, tPad, bPad, outDir)
% Update the name of the image in the cell data and also writes out the
% new image to the destination location.
I = imread(pos(1).im);
[rows cols chan] = size(I);
newI = uint8(ones(rows + tPad + bPad, cols + lPad + rPad, chan));
newI(tPad+1 : tPad+rows , lPad+1:lPad+cols, :) = I;
[fileName, ext] = getFileNameParts(pos(1).im);
newName = sprintf('%s/%s_%d.%s', outDir, fileName, ...
  floor(intmax()*rand(1,1)), ext);
while exist(newName, 'dir')
  newName = sprintf('%s/%s_%d.%s', outDir, fileName, ...
    floor(intmax()*rand(1,1)), ext);
end
for i = 1 : length(pos)
  pos(i).x1 = pos(i).x1 + lPad;
  pos(i).x2 = pos(i).x2 + lPad;
  pos(i).y1 = pos(i).y1 + tPad;
  pos(i).y2 = pos(i).y2 + tPad;
  pos(i).im = newName;
end
imwrite(newI, newName);
end
