
function pos=stitch_10x_images(ch_count,reg_ch,overlap,x,trim,rescale_factor,mock)
% stitch images using ImageJ and save tforms. Requires imageJ installation 
% If mock, will try to piece together image using an approximation of the
% stitched positions based on 25% overlap. Only works with Kinetix
% (3200x3200).

    if ~exist('mock','var')
        mock=0;
    end
    xinterval=1233;
    yinterval=1236;

    cam_x=3200;
    cam_y=3200;
    fprintf('Stitching whole-slice image.\n');
    if mock~=1
        niestitchgenessingleplane(ch_count,reg_ch,overlap,x,trim); % This doesn't work reliably with DIC channel, adjust imaging settings.


        fprintf('Making 10x equivalent stitched images.\n')

        % make fake 10x images.
        mkdir 10x
        cd(fullfile(['stitchchannel',num2str(x)],'ch1stitched'));
        f=dir('*.tif');
        f=sort_nat({f.name});
        for i=1:length(f)
            im=imread(f{i});
            for n=2:5
                im(:,:,n)=imread(['../ch',num2str(n),'stitched/',f{i}]);
            end
            %im=imresize(imrotate(im,180),0.5);
            im=imresize(im,rescale_factor);
            imwrite(im(:,:,1),['../../10x/',f{i}]);
            for n=2:5
                imwrite(im(:,:,n),['../../10x/',f{i}],'WriteMode','Append');
            end
        end

        cd ../..
        fprintf('Parse tileconfig for each position.\n');
       
        [folders,pos,xxx,yyy]=get_folders();

        fname_all=dir(fullfile(['stitchchannel',num2str(x)],['ch',num2str(reg_ch)],'Pos*.registered.txt'));
        fname_all=sort_nat({fname_all.name})';
        fname_all=cellfun(@(y) fullfile(['stitchchannel',num2str(x)],['ch',num2str(reg_ch)],y),fname_all,'UniformOutput',0);



        %stitchedfname=dir(fullfile('10x','*.tif'));
        %stitchedfname=sort_nat({stitchedfname.name})';
        %stitchedfname=cellfun(@(y) fullfile('10x',y),stitchedfname,'UniformOutput',0);
        %folders=get_folders();
        %
        tforms_converted={};

        for i=1:numel(fname_all)
            fname=fname_all{i};
            fid=fopen(fname);
            c=textscan(fid,'%s %*s %s','Delimiter',';');
            fclose(fid);
            tifnames=c{1};
            tforms=c{2};
            I=contains(tifnames,'tif');
            tifnames=tifnames(I);
            tifnames=cellfun(@(x) x(1:end-4),tifnames,'UniformOutput',0);%truncate filenames to get folder names
            tforms=tforms(I);
            tform_xy=cellfun(@(x)textscan(x,'%*f %f %f %*f','Delimiter',',()'),tforms,'UniformOutput',0);
            tform_xy=cell2mat(cellfun(@cell2mat,tform_xy,'UniformOutput',0))/2;
            min_values = min(tform_xy);
            tform_xy = tform_xy+abs(min_values);

            %stitchedfileinfo=imfinfo(stitchedfname{i});
            %stitched_width=stitchedfileinfo(1).Width;
            tform_xy(:,1)=max(tform_xy(:,1))-tform_xy(:,1);
    		tform_xy(:,2)=tform_xy(:,2)-min(tform_xy(:,2));
            tform_xy(:,1)=tform_xy(:,1)-cam_x*trim/2; %add back the trimed portion
            tform_xy(:,2)=tform_xy(:,2)-cam_y*trim/2; %add back the trimed portion

            [~,I1]=ismember(tifnames,folders); %match up files


            for n=1:numel(I1)
                T=[0.5,0,0;0,0.5,0;tform_xy(n,:),1];
                tforms_converted{I1(n)}=affine2d(T);
            end

        end
        tform40xto10x=tforms_converted;
    else
        tform40xto10x={};
        [folders,pos,xxx,yyy]=get_folders();
        for n=1:numel(folders)
            xt=(max(xxx)-xxx(n))*xinterval;
            yt=yyy(n)*yinterval;
            T=[0.5,0,0;0,0.5,0;xt,yt,1];
            tform40xto10x{n}=affine2d(T);
        end
        uniqpos=unique(pos);
        [~,posidx]=ismember(pos,uniqpos);
        im={};
        for i=1:numel(uniqpos)
            %get image size
            %%
            img10xfilename=['10x/',uniqpos{i},'.tif'];
            subfolders=find(posidx==i);
            imgfiles=dir([folders{subfolders(1)},'/original/*.tif']);
            imgfiles={imgfiles.name};
            imginfo=imfinfo(fullfile(folders{subfolders(1)},'original',imgfiles{1}));
            im{i}=zeros((max(yyy)-1)*yinterval+cam_y,(max(xxx)-1)*xinterval+cam_x,numel(imginfo),'uint16');

            %%
            for n=1:numel(subfolders)
                imgfiles=dir([folders{subfolders(n)},'/original/*.tif']);
                imgfiles={imgfiles.name};
                for m=1
                    imginfo=imfinfo(fullfile(folders{subfolders(n)},'original',imgfiles{m}));
                    for nn=1:numel(imginfo)
                        im1=imread([folders{subfolders(n)},'/original/',imgfiles{m}],nn);
                        im1=imwarp(im1,tform40xto10x{subfolders(n)},'OutputView',imref2d([size(im{i},1),size(im{i},2)]));
                        %im1(1:10,1:10,:)=150;%add a border so that it's easy to count
                        im{i}(:,:,nn)=max(im{i}(:,:,nn),im1);
                    end
                end
            end


        end
        %%
        mkdir('10x')
        % for m=1:numel(im)
        %     imwrite(uint16(im{i}(:,:,1)),['10x/',uniqpos{i},'.tif']);
        %     for n=2:size(im{i},3)
        %         imwrite(uint16(im{i}(:,:,n)),['10x/',uniqpos{i},'.tif'],'WriteMode','Append');
        %     end
        % end
       for m=1:numel(im)
           imwrite_big(uint16(im{i}(:,:,1)),['10x/',uniqpos{i},'.tif']);
           for n=2:size(im{i},3)
               imwrite_big(uint16(im{i}(:,:,n)),['10x/',uniqpos{i},'.tif'],1);
           end
        end
    end

    save('40xto10x.mat','tform40xto10x');
    fprintf('All done. Saved transformations to 40xto10x.mat.\n')
end


function imwrite_big(img,filepath,append_tag)
%write BigTiff files
if ~exist('append_tag','var')
    append_tag=0;
end
if append_tag==0
    tiff_obj=Tiff(filepath,'w8');
    tagstruct.ImageLength=size(img,1);
    tagstruct.ImageWidth=size(img,2);
    tagstruct.Photometric=Tiff.Photometric.MinIsBlack;
    tagstruct.BitsPerSample=16;
    tagstruct.SamplesPerPixel=1;
    tagstruct.PlanarConfiguration=Tiff.PlanarConfiguration.Chunky;
    setTag(tiff_obj,tagstruct);
    write(tiff_obj,img);
    close(tiff_obj)
else
    tiff_obj=Tiff(filepath,'a');
    tagstruct.ImageLength=size(img,1);
    tagstruct.ImageWidth=size(img,2);
    tagstruct.Photometric=Tiff.Photometric.MinIsBlack;
    tagstruct.BitsPerSample=16;
    tagstruct.SamplesPerPixel=1;
    tagstruct.PlanarConfiguration=Tiff.PlanarConfiguration.Chunky;
    setTag(tiff_obj,tagstruct);
    write(tiff_obj,img);
    close(tiff_obj);
end


%%
close(tiff_obj)
end
