/* this program generates psuedo-fractal mountains using a
 * random midpoint displacement algorithim (sounds fancy eh :)
 *
 * It is taken from Pokorny & Gerald, _Computer Graphics_ (the chapter
 * on fractals)
 *
 * D.B.G. August 90.
 */
#include <ezlib.h>
#include <math.h>

#define MAX 640

/* NOTE:  It is **very** important to declare functions that return doubles
 *	  as double.  If not, Manx gleefully fucks up your code by converting
 *	  everything to int.
 */
double ran();

double line[MAX];
double rug = 0.3;
struct Screen *screen = NULL;

main()
{
 struct RastPort *rp;
 int i, j;
 double temp1;

 srand(time(0L));    /* I think this may be wrong here.... */

 line[0] = line[MAX-1] = (double) ((rand() % 50)+100);  /* seed it */

 fracline(0, MAX-1);   /* generate the "mountain" */

 screen = makescreen(HIRES, 2);    /* get a custom screen */
 if (screen == NULL)
   { closelibs(); MSG("Opening Screen failed.\n"); exit(10); }

 rp = &screen->RastPort;

 Move(rp, 0L, (int) line[0]);
 for (i=1; i < MAX; i++)
   Draw(rp, i, (int) line[i]);

 Delay(100);
 killscreen(screen);
 closelibs();

 exit(0);
}

fracline(a, b)
  int a, b;
{
 register int mid;
 double temp1, temp2;

 if ( (b - a) > 1 ) {
   mid = (a + b) / 2;

   temp1 = (double) ((line[a] + line[b]) / 2);
   temp2 = (ran() * 2.0) - 1.0;
   temp2 = temp2 * ((double)(b - a)) * rug;
   line[mid] = (double) (temp1 + temp2);

   fracline(a, mid);
   fracline(mid, b);
 }
}


