function [aligned_pts] = NonlinearOptimisationFit(pts, placedpts, index)

% Initially just get the data
x_orig = pts(1,:)';
y_orig = pts(2,:)';
p_x = placedpts(1,:)';
p_y = placedpts(2,:)';

% Now we rescale so that the first two of the selected point have length 1
den = sqrt((x_orig(index(1)) - x_orig(index(2)))^2+ (y_orig(index(1)) - y_orig(index(2)))^2);
x = x_orig./den;
x = x - mean(x);
y = y_orig./den;
y = y - mean(y);
for i=1:length(x)
    for j=1:length(x)
        RATIO(i, j) = sqrt((x(j) - x(i))^2+ (y(j) - y(i))^2);
    end
end


% We now need to do the same for the other unplaced points
den2 = sqrt((p_x(1) - p_x(2))^2 + (p_y(1) - p_y(2))^2);
p_x = (p_x)./den2;
p_y = (p_y)./den2;
offset(1) = p_x(1) - x(index(1));
offset(2) = p_y(1) - y(index(1));

p_x = p_x - offset(1);
p_y = p_y - offset(2);

figure; hold on;
plot(x, y, 'bo');
plot(p_x, p_y, 'ro');

axis tight;
RATIO

pause


I.ratio = RATIO;
I.den = den;
pts = zeros(length(x),2);
pts(index,1) = p_x;
pts(index,2) = p_y;
I.pts = pts;
I.index = index;
I.O = [x, y];
%X = [x(length(p_x)+1:end) y(length(p_x)+1:end)];

X = [x(setdiff(1:length(x), index)) y(setdiff(1:length(x), index))];



options = optimset('Display', 'none');
[X,toterr,exitflag,nbite]=fminsearch(@(X) min_ratio(X,  I), X, options);

pts_x = zeros(length(x),1);
pts_x(index) = p_x;
pts_x(setdiff(1:length(pts_x), index)) = X(:,1);
pts_y = zeros(length(x),1);
pts_y(index) = p_y;
pts_y(setdiff(1:length(pts_y), index)) = X(:,2);


% pts_x = [p_x; X(:,1)];
% pts_y = [p_y; X(:,2)];



pts_x = (pts_x + offset(1)).*den2;
pts_y = (pts_y + offset(2)).*den2;
aligned_pts = [transpose(pts_x(:)); transpose(pts_y(:))];
