/*
 * File: koch.c
 * ---------------
 * Este programa desenha o  fractal de Koch.
 */

#include <stdio.h>
#include <math.h>
#include "genlib.h"
#include "simpio.h"
#include "graphics.h"

#define PI 3.1415926535897932384626433832795

/*
 * Function: DrawLineDirection
 * Usage: DrawLine(length, direction);
 * -----------------------------------
 * This procedure draws a line extending from the current
 * point by moving the pen length inches in the direction
 * given by the parameter direction, which is an angle.  
 * The final position becomes the new current point.
 */

void DrawLineDirection(double length, double direction);

/*
 * Function: koch
 * Usage: koch(length, direction, depth);
 * --------------------------------------
 * This procedure draws a Koch fractal.  The parameter 
 * length defines the distance between the initial and
 * final points, and direction is the angle determined
 * by the line between these points and the x-axis.
 * The parameter depth gives the depth of the recursion
 * that is to be used.
 */

void koch(double length, double direction, int depth);

/* Main program */

main()
{
    double length;
    int depth;

    printf("Comprimento? ");
    length = GetReal();
    printf("Profundidade? ");
    depth = GetInteger();
    
    InitGraphics();

    MovePen(GetWindowWidth()/2, 2*GetWindowHeight()/3);

    koch(length, -PI/3, depth);
    koch(length, -PI, depth);
    koch(length,  PI/3, depth);
}

void DrawLineDirection(double length, double direction)
{
  double dx, dy;

  dx = length * cos(direction);
  dy = length * sin(direction);

  DrawLine(dx, dy);
}

void koch(double length, double direction, int depth)
{
  if (depth == 0) 
    DrawLineDirection(length, direction);
  else {
    double l = length/3;
    koch(l, direction, depth - 1);
    koch(l, direction + PI/3, depth -1);
    koch(l, direction - PI/3, depth -1);
    koch(l, direction, depth - 1);
  }
}

  

  
