clearvars
clc
%%
output_dir=fullfile('stitched');
mkdir(output_dir)
%%
fnames=dir('Max*.tif');
fnames={fnames.name}; 
%% get x y pos 
pos=zeros(numel(fnames),1);
x=pos;y=pos;
translations=zeros(numel(fnames),2);

for i=1:numel(fnames)
    idx1=regexp(fnames{i},'_|_Pos|\.');
    pos(i)=str2double(fnames{i}((idx1(1)+4):(idx1(2)-1)));
    x(i)=str2double(fnames{i}((idx1(2)+1):(idx1(3)-1)));
    y(i)=str2double(fnames{i}((idx1(3)+1):(idx1(4)-1)));
    translations(i,:)=[-x(i)*2463.5-6*y(i),2471*y(i)+5*x(i)];
end
uniq_pos=unique(pos);
for i=1:numel(uniq_pos)
    translations(pos==uniq_pos(i),:)=translations(pos==uniq_pos(i),:)-min(translations(pos==uniq_pos(i),:));
end
tforms={};
for i=1:numel(fnames)
    tforms{i}=affine2d([1 0 0;0 1 0;translations(i,:),1]);
end


save('tforms.mat','tforms','pos','x','y')
% change all transformations to positives

%% 
trim=300;
all_ch=[4];

parfor mm=1:numel(all_ch)
    ch=all_ch(mm);
    for i=1:numel(uniq_pos)
        in_slice=find(pos==uniq_pos(i));
        max_tform=max(translations(in_slice,:));

        stitched_img=zeros([round(max_tform(2)+3300),round(max_tform(1)+3300)],'uint16');
        RA=imref2d(size(stitched_img));
        for n=1:numel(in_slice)
            im=imread(fnames{in_slice(n)},ch);
            im([1:trim,end-trim:end],:)=0;
            im(:,[1:trim,end-trim:end])=0;
            
            stitched_img=max(stitched_img,imwarp(im,tforms{in_slice(n)},'OutputView',RA));
        end
        imwrite(stitched_img,fullfile(output_dir,['Pos',num2str(uniq_pos(i)),'ch',num2str(ch),'.tif']));

    end
end
%


%%
