#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>

#include "xlcall.h"
#include "framewrk.h"



/* 
   A C-program for MT19937, with initialization improved 2002/1/26.
   Coded by Takuji Nishimura and Makoto Matsumoto.

   Before using, initialize the state by using init_genrand(seed)  
   or init_by_array(init_key, key_length).

   Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
   All rights reserved.                          

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:

     1. Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.

     2. Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.

     3. The names of its contributors may not be used to endorse or promote 
        products derived from this software without specific prior written 
        permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


   Any feedback is very welcome.
   http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
   email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
*/



/* Period parameters */  
#define N 624
#define M 397
#define MATRIX_A 0x9908b0dfUL   /* constant vector a */
#define UPPER_MASK 0x80000000UL /* most significant w-r bits */
#define LOWER_MASK 0x7fffffffUL /* least significant r bits */

static unsigned long mt[N]; /* the array for the state vector  */
static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */

/* initializes mt[N] with a seed */
void init_genrand(unsigned long s)
{
    mt[0]= s & 0xffffffffUL;
    for (mti=1; mti<N; mti++) {
        mt[mti] = 
	    (1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti); 
        /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
        /* In the previous versions, MSBs of the seed affect   */
        /* only MSBs of the array mt[].                        */
        /* 2002/01/09 modified by Makoto Matsumoto             */
        mt[mti] &= 0xffffffffUL;
        /* for >32 bit machines */
    }
}

/* initialize by an array with array-length */
/* init_key is the array for initializing keys */
/* key_length is its length */
/* slight change for C++, 2004/2/26 */
void init_by_array(unsigned long init_key[], int key_length)
{
    int i, j, k;
    init_genrand(19650218UL);
    i=1; j=0;
    k = (N>key_length ? N : key_length);
    for (; k; k--) {
        mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL))
          + init_key[j] + j; /* non linear */
        mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
        i++; j++;
        if (i>=N) { mt[0] = mt[N-1]; i=1; }
        if (j>=key_length) j=0;
    }
    for (k=N-1; k; k--) {
        mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL))
          - i; /* non linear */
        mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
        i++;
        if (i>=N) { mt[0] = mt[N-1]; i=1; }
    }

    mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */ 
}

/* generates a random number on [0,0xffffffff]-interval */
unsigned long genrand_int32(void)
{
    unsigned long y;
    static unsigned long mag01[2]={0x0UL, MATRIX_A};
    /* mag01[x] = x * MATRIX_A  for x=0,1 */

    if (mti >= N) { /* generate N words at one time */
        int kk;

        if (mti == N+1)   /* if init_genrand() has not been called, */
            init_genrand(5489UL); /* a default initial seed is used */

        for (kk=0;kk<N-M;kk++) {
            y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
            mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL];
        }
        for (;kk<N-1;kk++) {
            y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
            mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL];
        }
        y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
        mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL];

        mti = 0;
    }
  
    y = mt[mti++];

    /* Tempering */
    y ^= (y >> 11);
    y ^= (y << 7) & 0x9d2c5680UL;
    y ^= (y << 15) & 0xefc60000UL;
    y ^= (y >> 18);

    return y;
}

/* generates a random number on [0,0x7fffffff]-interval */
long genrand_int31(void)
{
    return (long)(genrand_int32()>>1);
}

/* generates a random number on [0,1]-real-interval */
double genrand_real1(void)
{
    return genrand_int32()*(1.0/4294967295.0); 
    /* divided by 2^32-1 */ 
}

/* generates a random number on [0,1)-real-interval */
double genrand_real2(void)
{
    return genrand_int32()*(1.0/4294967296.0); 
    /* divided by 2^32 */
}

/* generates a random number on (0,1)-real-interval */
double genrand_real3(void)
{
    return (((double)genrand_int32()) + 0.5)*(1.0/4294967296.0); 
    /* divided by 2^32 */
}

/* generates a random number on [0,1) with 53-bit resolution*/
double genrand_res53(void) 
{ 
    unsigned long a=genrand_int32()>>5, b=genrand_int32()>>6; 
    return(a*67108864.0+b)*(1.0/9007199254740992.0); 
} 
/* These real versions are due to Isaku Wada, 2002/01/09 added */

int main(void)
{
    int i;
    unsigned long init[4]={0x123, 0x234, 0x345, 0x456}, length=4;
    init_by_array(init, length);
    printf("1000 outputs of genrand_int32()\n");
    for (i=0; i<1000; i++) {
      printf("%10lu ", genrand_int32());
      if (i%5==4) printf("\n");
    }
    printf("\n1000 outputs of genrand_real2()\n");
    for (i=0; i<1000; i++) {
      printf("%10.8f ", genrand_real2());
      if (i%5==4) printf("\n");
    }
    return 0;
}





//####################### EXCEL I-FACE #######################################
// 2003-2005 (c). RiskServers.  John Tissieres All Rights Reserved. 
// This Excel C Wrapper is the copyright of RiskServers SA. 
// This code can be reproduced and/or modified as long as this notice remains.
//####################### EXCEL I-FACE #######################################
// Change this to any maximum your hardware can handle 
const int MAX_LENGTH=100000;
// This is the Maximum number of Seeds Allowed
const int MAX_SEEDS=N;
#define SEED_TYPE unsigned long
// if seed is 0, or no seed is provided, then we impose this (see main())
const int MAX_DEFAULT_SEEDS=4;
SEED_TYPE next_seeds[MAX_DEFAULT_SEEDS]={0x123, 0x234, 0x345, 0x456};
static SEED_TYPE seeds[MAX_SEEDS];
// see below EXCEL doesn't have an unsigned long
const int MAX_LENGTH_OF_UNSIGNED_LONG_AS_STRING=10;
// pascal string to c string
// Excel represents strings as pascal strings 
void pstr(char *s,char *tmp2)
{
	for(int i=1;(i<=(BYTE) s[0]) ;i++)
    tmp2[i-1]=s[i];
	tmp2[i-1]='\0';
	return;
}

// c string to pascale string
void strp(char *s,const char *lpstr)
{
  
	lstrcpy(s + 1, lpstr);
    s[0] = lstrlen(lpstr);	
	return;
}


// constants used by I-Face 
const int MERSENNE_TWISTER_INT=32;
const int MERSENNE_TWISTER_INT_1=31;
const int MERSENNE_TWISTER_REAL_1=1;
const int MERSENNE_TWISTER_REAL_2=2;
const int MERSENNE_TWISTER_REAL_3=3;
const int MERSENNE_TWISTER_REAL_53=53;

const int MERSENNE_TWISTER_DEFAULT=MERSENNE_TWISTER_INT;
const int MERSENNE_TWISTER_DEFAULT_REAL=MERSENNE_TWISTER_REAL_1;
const int MERSENNE_TWISTER_DEFAULT_INT=MERSENNE_TWISTER_INT;



int  streamType(char *conv)
{
int Type=MERSENNE_TWISTER_DEFAULT,i=1;
  if(conv[0]!=0)
  {
	char   *Typetoken=conv;
    while (*Typetoken && isspace(*Typetoken))
        ++Typetoken;
	if(!isdigit(Typetoken[0]))
	{
			char check=toupper(Typetoken[0]);
			if( check=='R' ||  check=='D' )
			{			
				size_t len=strlen(Typetoken);
				while(i <len && (!isdigit(Typetoken[i]))) i++;
				if(i<len)
				{
					switch(atoi(Typetoken+i)) 
					{
					case MERSENNE_TWISTER_REAL_1:
					Type=MERSENNE_TWISTER_REAL_1;								
					break;
					case MERSENNE_TWISTER_REAL_2:
					Type=MERSENNE_TWISTER_REAL_2;								
					break;
					case MERSENNE_TWISTER_REAL_3:
					Type=MERSENNE_TWISTER_REAL_3;								
					break;
					case MERSENNE_TWISTER_REAL_53:
					Type=MERSENNE_TWISTER_REAL_53;								
					break;
					default:
					Type=MERSENNE_TWISTER_DEFAULT_REAL;
					break;
					}
				}
				else
				{
				Type=MERSENNE_TWISTER_DEFAULT_REAL;
				}
			}
			else if( check=='I')
			{
				size_t len=strlen(Typetoken);
				while(i <len && (!isdigit(Typetoken[i]))) i++;
				if(i<len)
				{
					switch(atoi(Typetoken+i))
					{
					case 1:
					case MERSENNE_TWISTER_INT_1:
					Type=MERSENNE_TWISTER_INT_1;								
					break;
					case 0:
					case 2:
					case MERSENNE_TWISTER_INT:
					Type=MERSENNE_TWISTER_INT;
					break;
					default:
					Type=MERSENNE_TWISTER_DEFAULT_INT;
					break;
					}
				}
				else
				{
					Type=MERSENNE_TWISTER_DEFAULT_INT;
				}

			}
			else
			{
					Type=MERSENNE_TWISTER_DEFAULT_INT;
			}
	}
	else
		Type=atoi(Typetoken);

  }
  return Type;
}









LPXLOPER WINAPI MersenneTwister(
							  LPXLOPER lpxSeed,
							  LPXLOPER lpxStreamType,
							  int usLength,
							  int uoffset,
							  int deal=0)
{   
static XLOPER xResult; 
   if(usLength<0)
   {
		xResult.xltype = xltypeStr;
		xResult.val.str = "\029Length Cannot be Negative";
		return (LPXLOPER) &xResult;
   }
   else if(usLength==0)
   {
		xResult.xltype = xltypeInt;
		xResult.val.num = 0;
		return (LPXLOPER) &xResult;
   }
   if(uoffset<0)
   {
		xResult.xltype = xltypeStr;
		xResult.val.str = "\029Offset Cannot be Negative";
		uoffset=0;
		return (LPXLOPER) &xResult;

   }
/////////////////////////////////////////////////////////////////////////
// Multiple Returns are Bad style, but we must inform user of problems!
/////////////////////////////////////////////////////////////////////////
 if(deal >0)
 { 
	static XLOPER *rgx;
	int cols_ret=0;
	int rows_ret=0;
    int numberOfSeeds=0,i=0,j=0;
	int seedCols=1,seedRows=1;
	bool seedColumnWise=false;
	int length=usLength;
	bool canProcess=false;
	char streamTypeTxt[32]={0x00};

	int error = -1;
	SEED_TYPE d;
	
	LPXLOPER FAR *ppxArg;   // Pointer to the argument being processed 
	XLOPER xMulti;          // Argument coerced to xltypeMulti 
	LPXLOPER pointerToXLoper;            // Pointer into array 

    int seedIter=0;
    bool processSeeds=false;
	ppxArg = &lpxSeed;	
	switch ((*ppxArg)->xltype) 
	{
	    case  xltypeMissing:
			break;
	    case  xltypeNum:
			d=(SEED_TYPE) (*ppxArg)->val.num;
			break;
		case  xltypeInt:
			d=(SEED_TYPE) (*ppxArg)->val.w;
			break;
	   	case  xltypeRef:
   		case  xltypeSRef:
		case  xltypeMulti:
        if (xlretSuccess != Excel(xlCoerce, &xMulti, 2,(LPXLOPER) *ppxArg, TempInt(xltypeMulti))) {
          return 0;
        }
		seedRows=(int) xMulti.val.array.rows;
		seedCols=(int) xMulti.val.array.columns;
		seedRows= seedRows> MAX_SEEDS ? MAX_SEEDS :seedRows ;
		seedCols= seedCols> MAX_SEEDS ? MAX_SEEDS : seedCols;				

	    if(seedCols <MAX_SEEDS && seedRows <MAX_SEEDS )
		{
			numberOfSeeds=seedRows > seedCols? seedRows: seedCols;
			processSeeds=true;
		}
	    else if(seedCols>1 && seedRows==1)
		{
			seedColumnWise=true;
			numberOfSeeds=seedCols;
			if(seedCols <MAX_SEEDS)
			processSeeds=true;
		}
		else if(seedCols==1 && seedRows>1)
		{
			seedColumnWise=false;
			numberOfSeeds=seedRows;
			if(seedRows <MAX_SEEDS)
			processSeeds=true;
		}
	    for (i = 0;
            i < (xMulti.val.array.rows * xMulti.val.array.columns);
            i++) {

          pointerToXLoper = xMulti.val.array.lparray + i;
   			switch (pointerToXLoper->xltype) 
				{
					case xltypeNum:											
						if(seedIter<MAX_SEEDS)
						  seeds[seedIter++] =(SEED_TYPE)pointerToXLoper->val.num;
  						break;
						case  xltypeInt:
						if(seedIter<MAX_SEEDS)
						  seeds[seedIter++] =(SEED_TYPE)pointerToXLoper->val.w;
						break;
					case xltypeErr:
						error = pointerToXLoper->val.err;
						break;
					case xltypeNil:
						if(seedIter<MAX_SEEDS)
						  seeds[seedIter++] =(SEED_TYPE)0.0;
	 					break;
					default:
						error = xlerrValue;
					break;
   				}  // end of inner switch
			} // end of for loop columns + lparrays
        Excel(xlFree, 0, 1, (LPXLOPER) &xMulti);
        break;

      case xltypeErr:
        error = (*ppxArg)->val.err;
        break;

      default:
        error = xlerrValue;
        break;
	  }
    //////////////////////////////////////////////////
	if(error==-1)
	{
	    //lpx = (LPXLOPER) GetTempMemory(sizeof(XLOPER)); causes GPF
		rgx=new XLOPER[usLength];
		rgx->xltype=xltypeMulti | xlbitDLLFree;   
		if(rgx==0x00)
		{
			xResult.xltype = xltypeStr;
			xResult.val.str = "\020Allocation Error";
			return (LPXLOPER) &xResult;
		}
	}
	else
	{
		xResult.xltype = xltypeStr;
		xResult.val.str = "\013Seed Error";
		return (LPXLOPER) &xResult;
	}

	if(processSeeds)
	{
	    if(numberOfSeeds==1)
		{
			if(d!=(SEED_TYPE)0)
			{
				seeds[0]=(SEED_TYPE)d;			
	
			}
			else
			{
				xResult.xltype = xltypeStr;
				xResult.val.str = "\013Seed is 0";
				return (LPXLOPER) &xResult;
			}
		}
	}
	// 
	if(!processSeeds
	||
	(seeds[0] == (SEED_TYPE)0 && seeds[1] == (SEED_TYPE)0 && seeds[2] ==(SEED_TYPE) 0 && seeds[3]==(SEED_TYPE)0)
	)
	{
		numberOfSeeds=MAX_DEFAULT_SEEDS;
		for(j=0;j< numberOfSeeds;j++)seeds[j]=(SEED_TYPE)next_seeds[j];
	}
	init_by_array(seeds,numberOfSeeds);
	// Maximum Allowed - Safeguard - remove if not needed
	if(length > MAX_LENGTH)
	{
			length=MAX_LENGTH;
	}
	// SKIP RUNS
	if(uoffset>0)
	{
	for(j=0;j<uoffset;j++)
		genrand_int32();
	}
	// sic! all this to provide a "nicer" interface!
    ppxArg = &lpxStreamType;	
	switch ((*ppxArg)->xltype) 
	{
	    case  xltypeStr:
			pstr((*ppxArg)->val.str,streamTypeTxt);				
			break;
		case  xltypeInt:
			sprintf(streamTypeTxt,"%d",(*ppxArg)->val.w);
			break;
	    case  xltypeNum:
			sprintf(streamTypeTxt,"%.0f",(*ppxArg)->val.num);
			break;
	    case  xltypeMissing:
	   	case  xltypeRef:
   		case  xltypeSRef:
		case  xltypeMulti:
        if (xlretSuccess != Excel(xlCoerce, &xMulti, 2,
	          (LPXLOPER) *ppxArg, TempInt(xltypeMulti))) 
		{
          return 0;
        }
   for (i = 0;
            i < (xMulti.val.array.rows * xMulti.val.array.columns);
            i++) {
        pointerToXLoper = xMulti.val.array.lparray + i;
   			switch (pointerToXLoper->xltype) 
				{
				    case  xltypeStr:
						pstr(pointerToXLoper->val.str,streamTypeTxt);				
					break;
					case  xltypeInt:
						sprintf(streamTypeTxt,"%d",pointerToXLoper->val.w);
					break;
					case  xltypeNum:
						sprintf(streamTypeTxt,"%.0f",pointerToXLoper->val.num);
					break;
					case xltypeErr:
					case xltypeNil:
					default:
					break;
   				}  // end of inner switch
			} // end of for loop columns + lparrays
        Excel(xlFree, 0, 1, (LPXLOPER) &xMulti);
        break;
        case xltypeErr:     
        break;

      default:

        break;
	  }

  switch(streamType(streamTypeTxt))
  {
  case MERSENNE_TWISTER_REAL_1:
  for(j=0;j<length;j++)
	{
		rgx[j].xltype=xltypeNum;  
		rgx[j].val.num=genrand_real1();
	}

	break;
  case MERSENNE_TWISTER_REAL_2:
  for(j=0;j<length;j++)
	{
		rgx[j].xltype=xltypeNum;  
		rgx[j].val.num=genrand_real2();
	}

	break;
  case MERSENNE_TWISTER_REAL_3:
  for(j=0;j<length;j++)
	{
		rgx[j].xltype=xltypeNum;  
		rgx[j].val.num=genrand_real3();
	}

	break;
  case MERSENNE_TWISTER_REAL_53: 
  for(j=0;j<length;j++)
	{
		rgx[j].xltype=xltypeNum;  
		rgx[j].val.num=genrand_res53();
	}

	break;
  //############################################################
  // We have no other choice than to use strings (!)
  // EXCEL(R) doesn't know what an unsigned long int is
  // only unsigned short int are used internally by Excel(R)
  // Tricky! this creates a memory leak if not handled correctly
  //############################################################
  case MERSENNE_TWISTER_INT_1:
  {
    char **pascalString;
	char cString2Pascal[32]={0x00};
	pascalString=new char*[length];
 	for(j=0;j<length;j++)
	{
        pascalString[j]=new char[MAX_LENGTH_OF_UNSIGNED_LONG_AS_STRING+1];
		rgx[j].xltype=xltypeStr	| xlbitXLFree;     
		sprintf(cString2Pascal,"%lu",(unsigned long)genrand_int31());
	    strp(pascalString[j],cString2Pascal);
	    rgx[j].val.str=pascalString[j];
	}
  }
  case MERSENNE_TWISTER_INT: 
  //############################################################
  // We have no other choice than to use strings (!)
  // EXCEL(R) doesn't know what an unsigned long int is
  // only unsigned short int are used internally by Excel(R)
  // Tricky! this creates a memory leak if not handled correctly
  //############################################################
  default:
  {
    char **pascalString;
	char cString2Pascal[32]={0x00};
	pascalString=new char*[length];
 	for(j=0;j<length;j++)
	{
        pascalString[j]=new char[MAX_LENGTH_OF_UNSIGNED_LONG_AS_STRING+1];
		rgx[j].xltype=xltypeStr	| xlbitXLFree;   
		sprintf(cString2Pascal,"%lu",(unsigned long)genrand_int32());
	    strp(pascalString[j],cString2Pascal);
	    rgx[j].val.str=pascalString[j];

	}
  }
  }
	// cleanup
    ///////////////////////////////////////////////////		
	xResult.xltype=xltypeMulti | xlbitDLLFree;   
	xResult.val.array.rows=length;
	xResult.val.array.columns=1;
	xResult.val.array.lparray=(LPXLOPER) &rgx[0];
	}
	else
	{
		xResult.xltype = xltypeStr;
		xResult.val.str = "\014On Standby";

	}
return (LPXLOPER) &xResult;
}







/*
***************************************************************************
				NOTE				NOTE
***************************************************************************

If you compile as a dll
1) include a .def file with  MersenneTwister
2) In the Excel sheet use the CALL or REGISTER function


=REGISTER("mt19937.dll","MersenneTwister"," RRRIII"," MersenneTwister",
		" Seeds,Type,NumberOfValues,Skips,Activation Key"," 1"," MersenneTwister Random Generator"," mt19937.hlp")



If you compile as a xll
1) download framewk.exe
2) add MersenneTwister in the .def file
3) in the generic.c file find g_rgWorksheetFuncs section
                [g_rgWorksheetFuncsRows][g_rgWorksheetFuncsCols] =

and Add
{ 
		" MersenneTwister",
		" RRRJJJ",
		" MersenneTwister",
		" Seeds,Type,NumberOfValues,Skips,Activation Key",
		" 1",
		" MersenneTwister Random Generator",
		" T_XL_LONG_CALC",
		" T_XL_LONG_CALC",
		" Generate Random Values",
		" Random Seeds. Array of 6 Seeds Maximum ",
		" The Number of Values to Generate",
		" The number of skips or advances prior to display",		
		" 0 Idle, 1 for Calculation",
		" ",
		" ",
		" "
},
  */







