#include "random.h"

int Generate() {

	HCRYPTPROV provider;
	BYTE bytes[sizeof(wchar_t)];

	const double max = (double) (1 << sizeof(wchar_t) * 8) - 1;
	unsigned short int random;
	int index;

	if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
		fwprintf(stderr, L"context acquire failure\n");
		return 0;
	}

	for (unsigned int i = 0; i < parameters.lines; i++) {

		for (unsigned int j = 0; j < parameters.count; j++) {

			if (!CryptGenRandom(provider, sizeof(wchar_t), bytes)) {
				fwprintf(stderr, L"random failure\n");
				return 0;
			}

			random = bytes[0] << 8 | bytes[1];
			index = (int) ((((double) random) / max) * parameters.range);

			wprintf(L"%c", parameters.characters[index]);

		}

		wprintf(L"\n");

	}

	if (!CryptReleaseContext(provider, 0)) {
		fwprintf(stderr, L"context release failure\n");
	}

	return 1;

}