## Program that calculates the fractal dimensionality of an arbitrary
## curve (could also be smooth)
## Usage : df=fractal_dimension(x,y,Nlevels)
##         df : fractal dimension
##         x,y : coordinates of the fractal
function df=fractal_dimension(x,y,Nlevels)

  ## Calculate the distance between the initial and final point of the
  ## curve.
  l=length(x);  ## Gets used several times, so assign to variable
  d = sqrt( (x(l)-x(1))^2+(y(l)-y(1))^2 );
  Lsf=[]; Nsf=[];  ## Initialize arrays
  
  for n = 1:Nlevels
    n          ## For display, no semicolons
    Ls  = d/2^n;   Lsf = [Lsf;Ls];
    Ns  = 0;   ## Counter for number of steps
    c1  = 1;   ## Counter for the reference point
    di_to_end = d+eps;  ## Distance of c1 to the end

    while ( di_to_end>Ls ) 

      c2 = c1+1;   ## Consecutive point
      di = 0;  ## Initialize the distance between c1 and c2
    
      while ( di < Ls )
        di = sqrt( (x(c2)-x(c1))^2 + (y(c2)-y(c1))^2 );
        c2++;
      endwhile

      c1=c2;
      di_to_end = sqrt( (x(c1)-x(l))^2 + (y(c1)-y(l))^2 );
      Ns++;   ## Increment the number of steps
 
    endwhile
    
    Nsf=[Nsf;Ns];

  endfor

  p=fit(log(Lsf),log(Nsf),1);
  df=-p(1);
    
endfunction

