#include <stdio.h>
#include <string.h>
#include <conio.h>
#include "bitmap.h"

#define MAXLEN 100

void drawBmp(Bitmap*);
Bitmap** splitBmp(Bitmap*,int32_t,int32_t,int32_t&);
Bitmap* extractBmp(Bitmap* , int32_t, int32_t, int32_t, int32_t);

int main(int argc, char* argv[]) {

	if (argc < 6 || strcmp(argv[2], "-h") || strcmp(argv[4], "-w"))
		return 0;

	Bitmap* img = newBitmapFromFile(argv[1]);

	int32_t nHeight = atoi(argv[3]);
	int32_t nWidth = atoi(argv[5]);

	if (img != NULL) {

		drawBmp(img);

		int32_t nImgs;
		Bitmap** smallImgs = splitBmp(img, nHeight, nWidth, nImgs);
		char s[MAXLEN];
		for (int32_t i = 0; i < nImgs; i++) {
			sprintf(s,"/Users/hans/Desktop/%03d.bmp", i+1);
			writeBitmapToFile(s, smallImgs[i]);
			freeBitmap(smallImgs[i]);	
		}

		free(smallImgs);
		freeBitmap(img);
	}
	getch();
	return 0;
}

Bitmap** splitBmp(Bitmap* img, int32_t nHeight, int32_t nWidth, int32_t& nImgs) {
	int32_t sHeight = img->dib.bmHeight / nHeight;
	int32_t sWidth = img->dib.bmWidth / nWidth;
	int32_t sLastHeight = img->dib.bmHeight % nHeight + sHeight;
	int32_t sLastWidth = img->dib.bmWidth % nHeight + sWidth;

	nImgs = nWidth * nHeight;
	Bitmap** smallImgs = (Bitmap**) malloc(sizeof(Bitmap*) * nImgs);

	int32_t i = 0;
	int32_t height, width;


	for (int32_t x = 0; x < img->dib.bmHeight; x += height) {

		if (x + sLastHeight == img->dib.bmHeight)
			height = sLastHeight;
		else
			height = sHeight;

		for (int32_t y = 0; y < img->dib.bmWidth; y += width) {
			if (x + sLastWidth == img->dib.bmWidth)
				width = sLastWidth;
			else
				width = sWidth;

			smallImgs[i++] = extractBmp(img,x,y,height,width);		
		}
	}

	return smallImgs;
}


Bitmap* extractBmp(Bitmap* img, int32_t x, int32_t y, int32_t height, int32_t width) {

	Bitmap* newImg = (Bitmap*) malloc(sizeof(Bitmap));
	*newImg = *img;

	newImg->dib.bmWidth = width;
	newImg->dib.bmHeight = height;

	setRowSize(newImg);
	newImg->dib.dataSize = newImg->rowSize * newImg->dib.bmHeight;

	newImg->data = (uint8_t*) malloc(sizeof(uint8_t)*newImg->dib.dataSize);

	for (int32_t i = 0; i < newImg->dib.bmHeight; i++) {
		for (int32_t j = 0; j < newImg->dib.bmWidth; j++) {
			(*newImg)(i,j) = (*img)(x + i, y + j);
		}
	}

	return newImg;
}


#ifdef _WIN32
#define _CRT_SECURE_NO_WARNINGS
#include <windows.h>
void drawBmp(Bitmap* img) {
	HWND console = GetConsoleWindow();
	HDC hdc = GetDC(console);

	for (int i = img->dib.bmHeight - 1; i >=0; i--) {
		for (int j = 0; j < img->dib.bmWidth; j++) {
			Pixel pixel = (*img)(i,j);
			SetPixel(hdc, j, img->dib.bmHeight-1 - i, RGB(pixel.R, pixel.G, pixel.B));
		}
	}

	ReleaseDC(console, hdc);
}
#else
void drawBmp(Bitmap* img) {
	printf("Can't draw on console\n");
}
#endif


