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

scriptname = mfilename;

scriptpath = which(scriptname);
tokens = regexp(scriptpath, filesep);

cd(scriptpath(1:tokens(end)));

param.targetDirectory = scriptname;



load('helamodel.mat')

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

positions = model.cellShapeModel.positions(cellinds,:);

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

numperdim = 5;


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

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

%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)];
    
    simplex_idx = tsearchn(model.cellShapeModel.positions,model.cellShapeModel.tessellation,point);
    if ~isnan(simplex_idx)

        points(c,:) = point;
        param.position = point;
        
        savedir = [scriptpath '_img' num2str(i)];
        if ~exist(savedir, 'dir')
            mkdir(savedir)
        end
        cd(savedir);

        param.targetDirectory = savedir;
        
        imgs{c} = model2img({model}, param);
        c = c+1
    end
    
end
