%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% coord_nucleus = VII_saveCellTrajectory_new_nucleus('file directory',1,10);
% figure; plot(coord_nucleus(1,:), coord_nucleus(2,:));
% figure; plot(coord_nucleus(1,:), coord_nucleus(2,:)); hold on; plot(coord_nucleus(1,1), coord_nucleus(2,1), 'rx');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


function coord_nucleus = VII_saveCellTrajectory_new_nucleus(nucleus_mat_file,firstpoint,pt_interval) % creates the movie marking the DIC image with the contours and centroid (rounded to the closest pixel)
    [PathName,filename,~] = fileparts(nucleus_mat_file);
    tmp = strsplit(filename,'_');
    acquisition_name = [tmp{1} '_' tmp{2} '_']; % to find the prefix of the acquisition ex: c012_pos4

    if( exist( [PathName, '\' , acquisition_name, 'wTIRF_642.tif'] ) )  % look for the size image automatically if the file exists
        info = imfinfo([PathName, '\' , acquisition_name, 'wTIRF_642.tif'] );
        sizeImgY = info(1).Height;
    else % ask for the user otherwise
        sizeImgY = str2num(input('Size of your image? (Height, in Y direction)\n','s'));
    end
    
    %read position file
    pos_file = dir([PathName '\' acquisition_name '*Positions.mat']);
    if ( ~isempty(pos_file) )
        load(fullfile(PathName,pos_file.name));
    else
        warning = 'No positions file found, impossible to compute the translations';
    end
    % keep only some positions
    p = p(1:2,firstpoint:pt_interval:end); % taking on point every pt_interval, starting with firstpoint
    X = p(1,:)-p(1,1);
    Y = p(2,:)-p(2,1);
    % computes the corresponding translations
    scale_param_pos = 1/0.2167;
    trX = X*scale_param_pos; % carefull there seems to be more positions than the number of images
    trY = Y*scale_param_pos;

    %read nucleus centroid file
    data_cell = load(nucleus_mat_file);
    if( isfield(data_cell,'nucleus_centroid') ) % to work with both old and new version
        nucleus_centroid = data_cell.nucleus_centroid;
    else
        nucleus_centroid = data_cell.nucl_centroid_imgRef;
    end

    Nf = size(nucleus_centroid,2); % number of images
    coord_nucleus = [nucleus_centroid(2,:)+trX(1:Nf); sizeImgY-nucleus_centroid(1,:)+trY(1:Nf)];

    save(fullfile(PathName,[acquisition_name '_coord_centroid_nucleus.mat']),'coord_nucleus');
    
    figure; plot(coord_nucleus(1,:),coord_nucleus(2,:)); hold on; plot(coord_nucleus(1,1), coord_nucleus(2,1), 'rx');
end

%figure; plot(coord_cell(1,:),coord_cell(2,:));