main_folder = pwd;
read_prefix = 'mov3__ ';
matlab_prefix = read_prefix;
red_offset = 1;
top_bottom_clip = 3;


last_stack = 158;
last_position = 2;
last_color = 1;
last_slice = 99;
last_scan = 0;


if last_color == 0
start_slice = top_bottom_clip;
elseif last_color ==1
start_slice = top_bottom_clip + red_offset;
end

end_slice = last_slice - top_bottom_clip;

image_width = 500;
image_height = 500;


mkdir('Stacks')
cd('Stacks');

for i = 0:last_position;
    mkdir(['Position ' num2str(i)]);
end

% Could replace most of this with utilities TiffStackWrite and
% TiffStackImport

for i = 0:last_stack
    for j = 0:last_position
        cd(main_folder);cd(['./Stacks/Position ' num2str(j)]);
        % Grabs files which are saved in many foldes to avoid Windows
        % Explorer issues, and reconstitutes into stacks.
         folder_number = floor( (i*(last_position +1) + j)/5);
        for k = 0:last_color
            
            tiff_obj = Tiff([matlab_prefix 'Stack ' num2str(i) ' Position ' num2str(j) ' Color ' num2str(k) '.tiff'],'w');
            for l = start_slice : end_slice
                if k == 1
                    slice_index = l - red_offset;
                else
                    slice_index = l;
                end
                    
                for m = 0:last_scan
                    filename = [read_prefix 'Stack ' num2str(i) ' Position ' num2str(j) ' Color ' num2str(k) ' Slice ' num2str(slice_index) ' Scan ' num2str(m) '.tif'];
                    im = imread(['../../Folder ' num2str(folder_number) '/' filename]);
                                        
                    if (((l-start_slice)*(last_scan+1)) + m) ==0
                        
                        tiff_obj.setTag('Photometric',Tiff.Photometric.MinIsBlack);
                        tiff_obj.setTag('BitsPerSample',16);
                        tiff_obj.setTag('PlanarConfiguration',Tiff.PlanarConfiguration.Chunky);
                        tiff_obj.setTag('ImageWidth',image_width);
                        tiff_obj.setTag('ImageLength',image_height);
                        tiff_obj.write(im);
                                                
                    else
                        
                        tiff_obj.writeDirectory;
                        tiff_obj.setTag('Photometric',Tiff.Photometric.MinIsBlack);
                        tiff_obj.setTag('BitsPerSample',16);
                        tiff_obj.setTag('PlanarConfiguration',Tiff.PlanarConfiguration.Chunky);
                        tiff_obj.setTag('ImageWidth',image_width);
                        tiff_obj.setTag('ImageLength',image_height);                        
                        tiff_obj.write(im);
                        
                    end
                end
            end
            
            tiff_obj.close;
            clear('tiff_obj')
                        
        end
    end
end