#include <windows.h>
#ifdef MSC_VER
#include <afxdb.h>
#include <atlstr.h>
#include <commctrl.h>
#endif
#include <stdio.h>
#include <algorithm>
#include <string>
#include <vector>
#include <map>
#include <assert.h>
#include <time.h>
#include <iostream>

#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "strmiids.lib")
#pragma comment(lib, "Ole32.lib")
#pragma comment(lib, "gdi32.lib")
#pragma comment(lib, "ddraw.lib")
#pragma comment(lib, "dxguid.lib")
#pragma comment(lib, "shell32.lib")
using namespace std;


#include <stdio.h>


#include <windows.h>

struct PAT_TABLE{
	BYTE flag;
	BYTE begin_chs[3];
	BYTE type;
	BYTE end_chs[3];
	DWORD begin_lba;
	DWORD size_lba;
};

int main(void)
{
	HANDLE hDrive;
	char drivename[30];
	unsigned char buf[512];
	unsigned long readsize;
	PAT_TABLE *pt;


	sprintf(drivename, "\\\\.\\physicaldrive0");
	hDrive= CreateFile(drivename, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);


	// 認識できるドライブがなければ終了
	if (hDrive == INVALID_HANDLE_VALUE){
		printf("cant open");
		return 0;
	}


	// bufに読み込む
	ReadFile(hDrive, buf, sizeof(buf), &readsize, NULL);
	//buf[readsize]= '\0';

	pt = (PAT_TABLE *)(buf + 0x200 - 2 - sizeof(PAT_TABLE) * 4);
	for(int i = 0; i < 4; i++){
		printf("%d:%p-%p\n", i, pt[i].begin_lba, pt[i].size_lba);
	}
	memset(&pt[1], 0, sizeof(PAT_TABLE));

	//SetFilePointer(hDrive, s, 0, 0);

	HANDLE hf = CreateFile("g:\\win7_32bit_back.img", GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
	if(hf == (HANDLE)0xffffffff){
		printf("create file error %d", GetLastError());
		return 0;
	}
	WriteFile(hf, buf, sizeof(buf), &readsize, NULL);

	//3BF F04C セクタ読む
	DWORD bufsize = 0x10000000;
	BYTE *tmp = new BYTE [bufsize];//0x80000セクタ
	for(int i = 0; i < 0x78; i++){
		ReadFile(hDrive, tmp, bufsize, &readsize, NULL);
		WriteFile(hf, tmp, bufsize, &readsize, NULL);
		printf("%d/0x78\n", i);
	}

	CloseHandle(hf);

	// ドライブ読み取りハンドルを閉じる
	CloseHandle(hDrive);




	return 0;
}