#include "..\CookHeader.h"
#include <Windows.h>
#include <atlimage.h>
#include <conio.h>

CString filename = "c:/CookDataC/PNG/pet02.png";
const int ROW = 512, COL = 512;
COLORREF imageAry[ROW][COL];

void readImage() {
	CImage image;
	image.Load(filename);

	for (int i = 0; i < ROW; i++)
		for (int k = 0; k < COL; k++)
			imageAry[i][k] = image.GetPixel(k, i);
}

void printImage() {
	HWND hwnd;
	HDC hdc;
	hwnd = GetForegroundWindow();
	hdc = GetDC(hwnd);  // 또는 hdc = GetDC(NULL);

	for (int i = 0; i < ROW; i++)
		for (int k = 0; k < COL; k++) {
			int r = GetRValue(imageAry[i][k]);
			int g = GetGValue(imageAry[i][k]);
			int b = GetBValue(imageAry[i][k]);
			SetPixel(hdc, k + 100, i + 100, RGB(r, g, b));
		}
	ReleaseDC(hwnd, hdc);
}

void qSort(Array <int>& arr, int start, int end) {
	if (end <= start)
		return;

	int low = start;
	int high = end;

	int pivot = arr[(low + high) / 2];	
	while (low <= high) {
		while (arr[low] < pivot)
			low++;
		while (arr[high] > pivot)
			high--;
		if (low <= high) {
			int temp = arr[low];
			arr[low] = arr[high];
			arr[high] = temp;
			low++;
			high--;
		}
	}

	int mid = low;

	qSort(arr, start, mid - 1);
	qSort(arr, mid, end);
}

void quickSort(Array <int>& ary) {
	qSort(ary, 0, len(ary) - 1);
}

int main() {
	_getch();
	readImage();

	Array <int> photoAry;
	for (int i = 0; i < ROW; i++)
		for (int k = 0; k < COL; k++) {
			int r = GetRValue(imageAry[i][k]);
			int g = GetGValue(imageAry[i][k]);
			int b = GetBValue(imageAry[i][k]);
			int value = (r + g + b) / 3;
			photoAry.push_back(value);
		}

	// 중앙값 찾기
	Array <int> dataAry;
	copyArray(photoAry, dataAry);
	quickSort(dataAry);
	int midValue = dataAry[ROW * COL / 2];

	// GrayScale(256색) --> BW Image(2색)
	for (int i = 0; i < len(photoAry); i++) {
		if (photoAry[i] < midValue)
			photoAry[i] = 0;
		else
			photoAry[i] = 255;
	}

	// imageAry를 BW로 변경
	int pos = 0;
	for (int i = 0; i < ROW; i++)
		for (int k = 0; k < COL; k++) {
			int r, g, b;
			r = g = b = photoAry[pos];
			imageAry[i][k] = RGB(r, g, b);
			pos++;
		}
	printImage();
}