
#include <windows.h>

int saveBMP(int width, int height, int depth, char* bmpbuffer, char *filename)
{
	//long bsize=0;
	//pGrabber->GetCurrentBuffer(&bsize, NULL);
	//unsigned char *bmpbuffer = new unsigned char[bsize];
	//pGrabber->GetCurrentBuffer(&bsize, (long*)bmpbuffer);

	//declare bmp structures 
	BITMAPFILEHEADER bmfh;
	BITMAPINFOHEADER info;

	//andinitialize them to zero
	memset(&bmfh, 0, sizeof(BITMAPFILEHEADER));
	memset(&info, 0, sizeof(BITMAPINFOHEADER));

	//fill the fileheader with data
	bmfh.bfType = 0x4d42;       //0x4d42 = 'BM'
	bmfh.bfReserved1 = 0;
	bmfh.bfReserved2 = 0;
	bmfh.bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + width*height*depth;
	bmfh.bfOffBits = 0x36;		//number of bytes to start of bitmap bits

	//fill the infoheader
	info.biSize = sizeof(BITMAPINFOHEADER);
	info.biWidth = width;
	info.biHeight = height;
	info.biPlanes = 1;					//we only have one bitplane
	info.biBitCount = 24;				//RGB mode is 24 bits
	info.biCompression = BI_RGB;	
	info.biSizeImage = 0;				//can be 0 for 24 bit images
	info.biXPelsPerMeter = 0x0ec4;		//paint and PSP use this values
	info.biYPelsPerMeter = 0x0ec4;     
	info.biClrUsed = 0;					//we are in RGB mode and have no palette
	info.biClrImportant = 0;			//all colors are important

	//now we open the file to write to
	HANDLE file = CreateFile(filename , GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	if (!file)
	{
		CloseHandle(file);
		//delete [] bmpbuffer;
		return 0;
	}
	//write file header
	unsigned long bwritten;
	if (!WriteFile(file, &bmfh, sizeof(BITMAPFILEHEADER), &bwritten, NULL))
	{	
		CloseHandle(file);
		//delete [] bmpbuffer;
		return 0;
	}
	//write infoheader
	if(!WriteFile(file, &info, sizeof(BITMAPINFOHEADER), &bwritten, NULL))
	{	
		CloseHandle(file);
		//delete [] bmpbuffer;
		return 0;
	}
	//write image data
	if(!WriteFile(file, bmpbuffer, width*height*depth, &bwritten, NULL))
	{	
		CloseHandle(file);
		//delete [] bmpbuffer;
		return 0;
	}
	//close file
	CloseHandle(file);
	//delete [] bmpbuffer;

	return 1;
}
