function mitosis1(which_cells::Array{CartesianIndex{2},1})
    
    cell_size = size(which_cells)[1]
    
    centre_of_mass = (Tuple(sum(which_cells)) ./ cell_size)

    xx = 0.
    xy = 0.
    yx = 0.
    yy = 0. 
    
    for i in Tuple.(which_cells)
        
        xx += (i[1] - centre_of_mass[1])^2
        xy += (i[1] - centre_of_mass[1])*(i[2] - centre_of_mass[2])
        yx += (i[2] - centre_of_mass[2])*(i[1] - centre_of_mass[1])
        yy += (i[2] - centre_of_mass[2])^2
    end

    T = (xx + yy)/cell_size
    D = (xx*yy - xy*yx)/(cell_size^2)
    
    L1 = 0.5*(T + sqrt(T^2 - 4*D +  1e-10))
    L2 = 0.5*(T - sqrt(T^2 - 4*D + 1e-10))
    
    if yx != 0
        normal_dir= (-yx/cell_size,max(L1,L2) - yy/cell_size)
        
    else 
        normal_dir = (0,-1)        
    end  
    
    hyp_const = -sum(normal_dir .* centre_of_mass)

    left::Array{CartesianIndex{2},1} = []
    right::Array{CartesianIndex{2},1} = []

    for i in which_cells
        if sum(Tuple(i) .* normal_dir) + hyp_const >= 0
            push!(left,i)
        else
            push!(right,i)
        end
    end
    
    return left,right
end

function cell_mitosis_and_apoptosis!(environment::Array{Float64,3},all_cells::Array{Float64,1},n_div::Dict{Float64,Integer},
    cell_config::CellularConfig)

    new_cells::Array{Float64,1} = []
    counter = 1

    @inbounds for cell in all_cells
        
        cell_size = 0.
        which_cells::Array{CartesianIndex{2},1} = []
        
        @inbounds for j in 1:size(environment,2)
            @inbounds for i in 1:size(environment,1)
                if environment[i,j,1] == cell
                    cell_size += 1.
                    push!(which_cells,CartesianIndex(i, j))
                end
            end
        end  

        if cell_size >= cell_config.cell_size_upper_limit
            left,right = mitosis1(which_cells)
            new_id = maximum(all_cells) + counter
            environment[left,1] .= new_id
            push!(new_cells,new_id)
            counter += 1
            n_div[cell] += 1
        end
    end    

    append!(all_cells,new_cells)

    for cell in new_cells
        n_div[cell] = 0
    end

end





