/*
//  nlRandom.cpp
//
//  Created by Daisuke Nogami on 9/30/05.
//  Copyright 2005 Daisuke Nogami [null-null.net]. Some rights reserved.
*/

#include "stdafx.h"

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

// http
#include <windows.h>
#include <wininet.h>

// selfmade class
#include "nlRandom.h"

// random.org param
#define GEN_RAND_INTS 10000
#define SMALLEST_VALUE -1000000000
#define LARGEST_VALUE 1000000000
#define COLUMNS 1

nlRandom::nlRandom(){
	int i;

	// initialize random source

	std::srand( time( NULL ) );

	randsrc = new int[GEN_RAND_INTS];
	for( i = 0; i < GEN_RAND_INTS; i++ ){
		randsrc[i] = -1000000001;	/* SMALLEST_VALUE -1 */
	}
	counter = 0;
}

nlRandom::~nlRandom(){
	delete []this->randsrc;
	this->randsrc = 0;
}

// [0-1]
double nlRandom::rand(){
	int res = randsrc[counter];
	int randmax;

	if( res == -1000000001 /* SMALLEST_VALUE -1 */ ){
		res = std::rand();
		randmax = RAND_MAX;
	}
	else{
		res = randsrc[counter]-(SMALLEST_VALUE);
		randmax = LARGEST_VALUE-SMALLEST_VALUE;
	}

	counter++;
	if( counter >= GEN_RAND_INTS ){
		counter = 0;
	}

	return (double)res/(double)randmax;
}

void nlRandom::load(){
	HINTERNET hInet;
	HINTERNET hFile;
	DWORD dwSize;
	char* lpszBuf = (LPTSTR)GlobalAlloc( GPTR, 1024 );
	std::string buff;
	int i, idx;

	char url[256];
	sprintf(
		url,
		"%s%d%s%d%s%d%s%d",
		"http://www.random.org/cgi-bin/randnum?num=",
		GEN_RAND_INTS,
		"&min=",
		SMALLEST_VALUE,
		"&max=",
		LARGEST_VALUE,
		"&col=",
		COLUMNS
	);

	// open url
	hInet = InternetOpen(
		"random.org",
		INTERNET_OPEN_TYPE_DIRECT,
		NULL,
		NULL,
		0
	);

	hFile = InternetOpenUrl(
		hInet,
		url,
		NULL,
		0,
		INTERNET_FLAG_RELOAD,
		0
	);
	
	// get from random.org
	while( true ){
		dwSize = 0;
		memset( lpszBuf, 0x00, sizeof( lpszBuf ) );
		if( !InternetReadFile( hFile, lpszBuf, sizeof(lpszBuf)-1, &dwSize ) ){
			break;
		}

		buff += std::string(lpszBuf);

		if( dwSize == 0){
			break;
		}
	}
	
	// convert to int from string
	i = idx = 0;
	while( (idx = buff.find('\n')) != std::string::npos && i < GEN_RAND_INTS ){
		randsrc[i] = atoi( buff.substr( 0, idx ).c_str() );
		buff = buff.substr( idx+1, buff.length() );
		i++;
	}

	// close url
	InternetCloseHandle(hFile);
	InternetCloseHandle(hInet);
}
