%Random Tree!
%try r=5/6, theta=pi/10 and 1000 iterations

%----------------------------MAIN----FUNCTION-----------------------------

function[]=random_tree(r,theta,iterations)
%function random_tree
%r = 5/6;
%theta = pi/10;
%iterations = 1000;
%here is the original branch in the form of 2 points (x1,y1,x2,y2)
l=[0,0,0,1];
x=l;
h(1) = plot(l(1:2),l(3:4),'Color',[0.58 0.39 0.39],'Linewidth',1);
hold on
count = 2;
for i=1:iterations
    n=ceil(rand(1)*size(x,1));
    l=x(n,:);
    [L1,L2]=expand(l,r,theta); %this will send the segment for expansion
    %replace the plotted line with two new lines
    x(n,:)=[];
    x(end+1,:)=L1;
    x(end+1,:)=L2;
    %plot here
    if (i>.9*iterations) 
        %add fruit (see help linespec)
    end
    h(count)=plot([L1(1),L1(3)],[L1(2),L1(4)],'Color',[0.58 0.39 0.39],'Linewidth',1);
    count = count+1;
    h(count)=plot([L2(1),L2(3)],[L2(2),L2(4)],'Color',[0.58 0.39 0.39],'Linewidth',1);
    count = count+1;
end;
hold off

%----------------------------Calculation----FUNCTION-----------------------------

function [L1,L2]=expand(l,r,theta)

t=[l(3);l(4)];
v=[l(1),l(3);l(2),l(4)]; 
%here are the two transformations
A1=r*[cos(theta) , -sin(theta) ; sin(theta) , cos(theta)];
A2=r*[cos(theta) , sin(theta) ; -sin(theta) , cos(theta)];
%% Calculate the two new lines
L1=A1*(v(:,2)-v(:,1))+t; 
L2=A2*(v(:,2)-v(:,1))+t;
L1=[t(1),t(2),L1(1),L1(2)];
L2=[t(1),t(2),L2(1),L2(2)];
