/* Mandelbrot Set, 2003 */

#include <windows.h>
#include <math.h>

#define N 1024.00
#define DIM 512

const char g_szClassName[] = "Mandelbrot Set";

int function(double x, double y) {

	if( log(x) - y <= 0.01 && log(x) - y >= -0.01)
		return 1;
	else
		return 0;
}

int mandelbrot(double x, double y) {
	double r, s, tmp;
	int i;

	r=x; s=y;
	for(i=0; i<255; i++) {
		tmp=r;
		r = r*r - s*s + x;
		s = 2*tmp*s + y;
		if(r*r + s*s > 4) break;
	}

	return i;

}

// Step 4: the Window Procedure
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {

	PAINTSTRUCT ps;
	HDC hdc;
	double x, y;
	double p, q;
	double h=2.00;
	int t;

	switch(msg)	{
		case WM_PAINT:
            hdc = BeginPaint(hwnd, &ps);
			for(y=0.94, p=0; y>=0.94-h; y=y-h/N, p=p+(double)DIM/N) {
				for(x=-1.50, q=0; x<=-1.50+h; x=x+h/N, q=q+(double)DIM/N) {
					t=mandelbrot(x, y);
					SetPixel(hdc, q, p, RGB(256-t, 256-t, 256-t));
				}
			}
			TextOut(hdc, 5, 5, "Coded by koby.", 14);
			EndPaint(hwnd, &ps);
			return 0L;
		case WM_CLOSE:
			DestroyWindow(hwnd);
		break;
		case WM_DESTROY:
			PostQuitMessage(0);
		break;
		default:
			return DefWindowProc(hwnd, msg, wParam, lParam);
	}
	return 0;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
	LPSTR lpCmdLine, int nCmdShow)
{
	WNDCLASSEX wc;
	HWND hwnd;
	MSG Msg;

	//Step 1: Registering the Window Class
	wc.cbSize		 = sizeof(WNDCLASSEX);
	wc.style		 = 0;
	wc.lpfnWndProc	 = WndProc;
	wc.cbClsExtra	 = 0;
	wc.cbWndExtra	 = 0;
	wc.hInstance	 = hInstance;
	wc.hIcon		 = LoadIcon(NULL, IDI_APPLICATION);
	wc.hCursor		 = LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
	wc.lpszMenuName  = NULL;
	wc.lpszClassName = g_szClassName;
	wc.hIconSm		 = LoadIcon(NULL, IDI_APPLICATION);

	if(!RegisterClassEx(&wc))
	{
		MessageBox(NULL, "Window Registration Failed!", "Error!",
			MB_ICONEXCLAMATION | MB_OK);
		return 0;
	}

	// Step 2: Creating the Window
	hwnd = CreateWindowEx(
		WS_EX_CLIENTEDGE,
		g_szClassName,
		"Mandelbrot Set",
		WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT, CW_USEDEFAULT, DIM, DIM,
		NULL, NULL, hInstance, NULL);

	if(hwnd == NULL)
	{
		MessageBox(NULL, "Window Creation Failed!", "Error!",
			MB_ICONEXCLAMATION | MB_OK);
		return 0;
	}

	ShowWindow(hwnd, nCmdShow);
	UpdateWindow(hwnd);

	// Step 3: The Message Loop
	while(GetMessage(&Msg, NULL, 0, 0) > 0)
	{
		TranslateMessage(&Msg);
		DispatchMessage(&Msg);
	}
	return Msg.wParam;
}
