%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% coord_cell = IV_saveCellTrajectory_new('file directory',1,1);
% figure; plot(coord_cell(1,:), coord_cell(2,:));
% figure; plot(coord_cell(1,:), coord_cell(2,:)); hold on; plot(coord_cell(1,1), coord_cell(2,1), 'rx');

% figure; plot(cell_centroid_imgRef(1,:), cell_centroid_imgRef(2,:)); hold on; plot(cell_centroid_imgRef(1,1), cell_centroid_imgRef(2,1), 'rx');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


function coord_cell = IV_saveCellTrajectory_new(cell_mat_file,firstpoint,pt_interval) 
    [PathName,filename,~] = fileparts(cell_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; % 1/0.3; or 1/0.18
    trX = X*scale_param_pos; % carefull there seems to be more positions than the number of images
    trY = Y*scale_param_pos;

    %read cell centroid file
    data_cell = load(cell_mat_file);
    if( isfield(data_cell,'cell_centroid') ) % to work with both old and new version
        cell_centroid = data_cell.cell_centroid;
    else
        cell_centroid = data_cell.cell_centroid_imgRef;
    end

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

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

% figure; plot(coord_cell(1,:),coord_cell(2,:)); hold on; plot(coord_cell(1,1), coord_cell(2,1), 'rx');