% function [ output_args ] = demo3DDiffeoSynth( input_args )
%This demo illustrates how to grid sample from a diffeomorphic model
clearvars 

scriptname = mfilename;
scriptpath = which(scriptname);
tokens = regexp(scriptpath, filesep);
cd(scriptpath(1:tokens(end)));

param.targetDirectory = mfilename;

load('helamodel.mat')

ndims = 2;
cellinds = find(all(~isnan(model.cellShapeModel.positions),2));

positions = model.cellShapeModel.positions(:,1:ndims);

tri = delaunay(positions(cellinds,:));
tri = cellinds(tri);

model.cellShapeModel.tessellation = tri; 
model.nuclearShapeModel.tessellation = tri;
model.cellShapeModel.positions = positions;
model.nuclearShapeModel.positions = positions;

minpos = min(positions,[], 1);
maxpos = max(positions,[], 1);

numperdim = 6;


for i = 1:length(minpos)
    linsp(i,:) = linspace(minpos(i), maxpos(i), numperdim);
end

%grid search over the first two dimensions
[y,x] = ndgrid(linsp(1,:), linsp(2,:));

%due to the matrix construction, the mean of the dimensions is asymptotically zero.

c = 1;
for i = 1:length(x(:))
    %sample from uniform distribution ANDed to the convex hull of the triangulation
    
%     point = [x(i), y(i), z(i), zeros(1, length(minpos)-3)];
    point = [x(i), y(i)];
    
    simplex_idx = tsearchn(positions,tri,point);
    if ~isnan(simplex_idx)
        param.position(c,:) = point;
        c = c+1
    end
    
end

%show the currently selected points
figure
triplot(model.cellShapeModel.tessellation, model.cellShapeModel.positions(:,1), model.cellShapeModel.positions(:,2))
hold on
scatter(positions(:,1),positions(:,2),40,'.b');
scatter(param.position(:,1),param.position(:,2),40,'.r');


manual = 1;
if manual==1
    prompt = 'Showing currently selected points. How many point would you like to select manually? \n';
    nummanimgs = input(prompt);
    manpoints = demo3DDiffeoPick(nummanimgs);
    simplex_idx = tsearchn(model.cellShapeModel.positions,model.cellShapeModel.tessellation,manpoints);
    simplex_idx(isnan(simplex_idx)) = [];
    param.position = [param.position;manpoints];
end

% prerun = 1;
% if prerun==1
%     load('selectedPositions.mat','positions');
% end
% save('./selectedPositions.mat');





synthpos = param.position;

for i = 1:size(synthpos,1)
    savedir = [scriptpath '_img' num2str(i)];
    if ~exist(savedir, 'dir')
        mkdir(savedir)
    end
    cd(savedir);
    
    param.position = synthpos(i,:);
    imgs = model2img({model}, param);
end
