function inverted = NE_inversion_experiment2(max_count)
% NE_inversion_experiment2 - tile PD with 45-degree triangles
%     put triangles in center of PD and invert through sides recursively
% On input:
%     max_count (int): number of unique triangles to generate
% On output:
%     inverted (nx6 array): linearized list of existing triangles
% Call:
%     invT = NE_inversion_experiment2(16);
% Author:
%     T. Henderson
%     UU
%     Summer 2023
%

ZERO_THRESH = 0.00001;

corners_PD = NE_equi45;

% boundaries of square
sq_pts1 = NE_PD_seg_pts([-sqrt(2)/2,sqrt(2)/2],[sqrt(2)/2,sqrt(2)/2]);
sq_pts2 = NE_PD_seg_pts([sqrt(2)/2,sqrt(2)/2],[sqrt(2)/2,-sqrt(2)/2]);
sq_pts3 = NE_PD_seg_pts([sqrt(2)/2,-sqrt(2)/2],[-sqrt(2)/2,-sqrt(2)/2]);
sq_pts4 = sq_pts2;
sq_pts4(:,1) = -sq_pts4(:,1);
t = [0:0.1:2*pi,2*pi];
x = cos(t);
y = sin(t);

clf
plot(x,y,'k');
hold on
plot(sq_pts1(:,1),sq_pts1(:,2),'b.');
plot(sq_pts2(:,1),sq_pts2(:,2),'b.');
plot(sq_pts3(:,1),sq_pts3(:,2),'b.');
plot(sq_pts4(:,1),sq_pts4(:,2),'b.');
axis equal
xx = 0.4143*cos(t);
yy = 0.4143*sin(t);
plot(xx,yy,'k');
plot(xx,yy,'k.');

inverted = [];
queue(1).corners = corners_PD;

done = 0;
count = 0;
total = 0;
while done==0
    count = count + 1;
    [total,count]
    T = queue(1).corners;
    queue(1) = [];
    len_queue = length(queue);
    new_T = 1;
    if NE_already_inverted_tri(T,inverted)
        new_T = 0;
    else
        inverted = [inverted;T(:)'];
    end
    
    if new_T==1
        % draw current triangle
        total = total + 1;
        p_pts1 = NE_PD_seg_pts(T(1,:),T(2,:));
        p_pts2 = NE_PD_seg_pts(T(2,:),T(3,:));
        p_pts3 = NE_PD_seg_pts(T(3,:),T(1,:));
        plot(p_pts1(:,1),p_pts1(:,2),'r');
        plot(p_pts2(:,1),p_pts2(:,2),'r');
        plot(p_pts3(:,1),p_pts3(:,2),'r');
        drawnow;
        
        % inversion through face 1
        circle1 = NE_orthog_circle(T(1,:),T(2,:));
        p1i = NE_inversion_all(T(1,:),T(2,:),circle1,T);
        queue = NE_insert_priority_queue(p1i,queue);
        
        % inversion through face 2
        circle2 = NE_orthog_circle(T(2,:),T(3,:));
        p2i = NE_inversion_all(T(2,:),T(3,:),circle2,T);
        queue = NE_insert_priority_queue(p2i,queue);
        
        % inversion through face 3
        circle3 = NE_orthog_circle(T(3,:),T(1,:));
        p3i = NE_inversion_all(T(3,:),T(1,:),circle3,T);
        queue = NE_insert_priority_queue(p3i,queue);
        
        tch = 0;
    end
    if total>=max_count|isempty(queue)
        done = 1;
    end
end

tch = 0;
