using Plots
using LaTeXStrings

function mandelbrot(x,y,iteration)
    z = 0 + 0*im
    c = x + y*im
    @fastmath for i in 1:iteration
        z = z*z + c
        val = abs2(z) # absolute without taking the root because it is slow so we compare with the square of 2
        cond = val > 4
        if cond
            return i
        end
    end
    return 0
end

function show_mandelbrot()

    #### Initialization

#     x_min=-2.0;
#     x_max=0.75;
#     y_min=-1.25;
#     y_max=1.25;
#     n_max=100;
#     grid_size = 800;

    #A nice zoomed in part of it
    x_min=-0.75075;
    x_max=-0.73852;
    y_min=0.09898;
    y_max=0.10816;
    n_max=1000;
    grid_size = 1080;

    X=LinRange(x_min,x_max,grid_size); # grid points in x-direction
    Y=LinRange(y_min,y_max,grid_size); # grid points in y-direction
    Z = Array{Int}(undef,grid_size,grid_size); ### This is just a different way to define a matrix

    ### Processing
    for i in eachindex(X)
        for j in eachindex(Y)
            Z[i,j] = mandelbrot(X[i],Y[j],n_max)
        end
    end

    ###############################################

    #Postprocessing
    ylabel = latexstring("y \\in [$y_min,$y_max]")
    xlabel = latexstring("x \\in [$x_min,$x_max]")

    p = heatmap(X,Y,Z', c=:thermal, ylabel=ylabel, xlabel=xlabel, title="Mandelbrot Set") #you can choose between different colormaps
    return p
end

show_mandelbrot()
