use warnings;
use Inline C => Config => CLEAN_AFTER_BUILD => 0, 
	CC => '/usr/bin/gcc',
	CCFLAGS => '-fopenmp', BUILD_NOISY => 1, 
	LIBS => '-lgomp -lpthread -ldl -lm';
use Inline C =><<'END_OF_C_CODE';

#include <omp.h>

int escapes(double cr, double ci, int it) {
  double zr = 0;
  double zi = 0;
  double zrtmp;
  int i;
  
  for(i=0; i<it; i++) {
    // z <- z^2 + c
    zrtmp = zr*zr - zi*zi + cr;
    zi = 2*zr*zi + ci;
    zr = zrtmp;
    if (zr*zr + zi*zi > 4) {
      return 1;
    }
  }
  return 0;
}

void mandel(double xmin, double xmax, int xstep, double ymin, double ymax, int ystep, int iters) {
  int yc;
     
  // array of string to store result
  char *m = (char *) malloc(ystep * (xstep + 1) * sizeof(char));
  
  #pragma omp parallel for
  for(yc=0; yc<ystep; yc++) {
    double y = yc*(ymax-ymin)/ystep + ymin;
    int xc;
    
    for(xc=0; xc<xstep; xc++) {
      double x = xc*(xmax-xmin)/xstep + xmin;
      if (escapes(x, y, iters)) {
        m[yc * (xstep + 1) + xc] = ' ';
      } else {
        m[yc * (xstep + 1) + xc] = 'X';   
      }
    }
    // add end of string
    m[yc * (xstep+1) + xstep] = '\0';  
    
  }

  for(yc=0; yc<ystep; yc++) {
	  printf("%s\n", &m[yc * (xstep+1)]);
  }
  free(m);
}

END_OF_C_CODE

mandel(-2.0, 1.0, 256, -1.0, 1.0, 256, 100000);


