#include <stdio.h>
#include <stdlib.h>
#include <cv.h>
#include <highgui.h>
#include <math.h>
#define IMAGE_SIZE 512
IplImage *pImg;
double delta = 4.0 / IMAGE_SIZE, a=-2.0,  b=-2.0;
double k1=0.0,t1=0.0;
int event1=-5,xx=-5,yy=-5,flags1=-5;
int mSetTest(double c_re, double c_im)
{
    int i=1;double x=0.0,y=0.0;
    for (i;i<=200;i++)
    {
        double k=x;
        x=x*x-y*y+c_re;
        y=2*k*y+c_im;
    	  if((x*x+y*y)>=4.0)
    	  {
    		return i;
		    }
    }
    return 0;
}
void swap(int *p1,int *p2)
{

  int temp=*p1;
  *p1=*p2;
  *p2=temp;
}
int findmax (int a,int b)
{
  if(a>b)
  {
    return a;
  }
  else return b;
}
void painting()
{
 int i,j; CvScalar sca;
   for(i=0;i<IMAGE_SIZE;i++)
   {
	   for (j=0;j<IMAGE_SIZE;j++)
	  {
		  double i_=a+delta*i;double j_= b+delta*j;
		  if (mSetTest(i_,j_)==0)
        {
          sca.val[0]=178;   //ue
          sca.val[1]=67;    //green
          sca.val[2]=45;    //red
          cvSet2D(pImg,j,i,sca);
        }
          else
        {
          sca.val[0]=0;
          sca.val[1]=255;
          sca.val[2]=25;
          cvSet2D(pImg,j,i,sca);
        }
	  }
   }
   cvShowImage("mandelbrot", pImg);
}
void on_mouse( int event, int x, int y, int flags,void* param)
{
   if (event==CV_EVENT_LBUTTONDOWN)
   {
     event1=event,xx=x,yy=y,flags1=flags;
   }
   else if (event==CV_EVENT_RBUTTONDOWN)
   {
     event1=event,xx=x,yy=y,flags1=flags;
   }
   if(event== CV_EVENT_LBUTTONUP)
   {
      if (event1==CV_EVENT_LBUTTONDOWN)
    {
      printf("%lf,%lf\n",a,b);
      a+=(xx-IMAGE_SIZE/2.0)*delta,b+=(yy-IMAGE_SIZE/2.0)*delta;
      printf("%lf,%lf",a,b);
      painting();
    }
   }
   else if(event == CV_EVENT_RBUTTONUP)
    {
      int m=findmax(abs(y-yy),abs(x-xx));int k=(xx+x)/2,t=(yy+y)/2;
      k1+=(k*1.0-IMAGE_SIZE/2.0)*delta,t1+=(t*1.0-IMAGE_SIZE/2.0)*delta;
      delta=delta*m/IMAGE_SIZE;
      a=k1-delta*IMAGE_SIZE/2.0,b=t1-delta*IMAGE_SIZE/2.0;
      printf("%d,%d,%lf,%lf\n",k,t,k1,t1);
      painting();

    }
}
int main()
{
   printf("                         H E L L O ! ! !                  \n");
   printf ("The left button will control the move of this picture\n");
   printf ("The right button will control the zooming in and out of the picture");

   pImg = cvCreateImage(/*size*/cvSize(IMAGE_SIZE, IMAGE_SIZE), /*depth*/ 8, /*nChannels*/3);
	 cvNamedWindow(/*name of the window*/"mandelbrot", 1);
	 painting();
	 cvSetMouseCallback("mandelbrot",on_mouse,0);
	 cvWaitKey(/*delay*/0);
	 cvDestroyWindow("mandelbrot");
	 //cvRelease(&pImg);
	 return 0;
}
