level = 4;
basename = 'medical';
dirname = sprintf('%s_%d', basename, level);
filename = sprintf('%s.jpg', dirname);
fprintf('Chopping %s\n', filename);
[rs, gs, bs] = jpgread(filename);

height = size(rs, 1);
width = size(rs, 2);
step_size = 100;

for i = 1:step_size:height % rows
  for j = 1:step_size:width % columns
    end_i = (min(i+step_size-1, height));
    end_j = (min(j+step_size-1, width));
    chunk_rs = rs(i:end_i, j:end_j);
    chunk_gs = gs(i:end_i, j:end_j);
    chunk_bs = bs(i:end_i, j:end_j);
    
    filename = sprintf('%s/%s_%d_%d.jpg', dirname, dirname, ...
                       round(i/step_size)+1, round(j/step_size)+1);
    fprintf('size: width = %d, height = %d\n', end_i-i+1, end_j-j+1);
    fprintf('%s\n', filename);
    jpgwrite(filename, chunk_rs, chunk_gs, chunk_bs);
  end

end

