% function LinkNods2Roots6
%To link nodules to roots

%Load dataset lists
if ~exist('mpd')
    mpd=uigetdir(pwd,['Select the main project folder']);
end
load([mpd '\dataset.mat']);

for s=1:size(imgpth,1);
    c_data=dataset(s,:);
    c_imgpth=[mpd imgpth(s,end-35:end)];
    c_resfol=[mpd resfol(s,end-19:end)];
    if str2num(c_data(end))>0
        
        disp(['Processing ' c_data '...']);
        load([c_resfol '/primary.mat'],'prix','priy');
        load([c_resfol '/individroots.mat'],'attg','xyg');
         load([c_resfol '/nodules_auto.mat'],'nx','ny');
         
         %Remove nodules outside of the nodulation zone
         K=convhull(xyg(:,1), xyg(:,2));
         in=inpolygon(nx,ny,xyg(K,1), xyg(K,2));
         nx(in==0)=[];
         ny(in==0)=[];
         
        %% Add primary root       
        xyg=[xyg;prix priy zeros(size(prix))];
        
        %% Match nodules to roots
        %         if ~exist([c_resfol '/noduleattachments.mat'])
        nID=[]; natt=[]; latD=[];
        for jn=1:length(nx) %For each nodule
            
            %Calculate distance of each nodule to each root
            d=distance(xyg(:,1:2),[nx(jn) ny(jn)]);
            [mindist ind]=min(d);
            
            if mindist<100%If not too far
                %Record which root it is attached to
                nID(jn,:)=xyg(ind,3);
                %Record xy attachment point
                natt(jn,:)=xyg(ind,1:2);
            else
                nID(jn,:)=NaN;
                natt(jn,:)=[NaN NaN];
            end
            
%             imshow(imread(c_imgpth)); hold on
%             rtInd=find(xyg(:,3)==xyg(ind,3));
%             rtp=plot(xyg(rtInd,1),xyg(rtInd,2),'.g','MarkerSize',2);
%             np=plot(nx(jn),ny(jn),'om');
%             set(rtp,'Visible','off')
%             set(np,'Visible','off')
            %Record lateral root position
            %                 latD(jn,1)=attg(xyg(ind,3));
            
            %                     %Make list of all nodules attached to this root;
            %                     nod{xyg(ind,3)}=[nod{xyg(ind,3)}; natt(jn)];
        end
        save([c_resfol '/nodAttchmts.mat'],'nID','natt','nx','ny');
    end
end


