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

/*
Written by Kenneth E. Moore
June 5, 2000
*/

int __declspec(dllexport) APIENTRY UserGrinDefinition(double *data);
int __declspec(dllexport) APIENTRY UserParamNames(char *data);

BOOL WINAPI DllMain (HANDLE hInst, ULONG ul_reason_for_call, LPVOID lpReserved)
	{
   return TRUE;
   }

/* the data is stored as follows:
ndata = the number of elements in the array data
data[0]  = the total number of values in the passed data array
data[1]  = x
data[2]  = y
data[3]  = z
data[4]  = wavelength in microns
data[5]  = millimeters per unit length (1.0 for mm, 25.4 for inches, 10.0 for cm and 1000.0 for meters)
data[6]  = n (to be computed by the dll and returned)
data[7]  = n * dn/dx (to be computed by the dll and returned)
data[8]  = n * dn/dy (to be computed by the dll and returned)
data[9]  = n * dn/dz (to be computed by the dll and returned)
data[10] = parameter 1 from user input
data[11] = parameter 2 from user input
etc... up to data[maxdata] where maxdata = int(data[0])

The DLL must compute data 6 through 9 given the other data,
and return 0 if it works; else return -1
*/

/* this DLL models a GRIN media similar to the GRIN 9 surface type. */
/* this is n(r) = N0( 1. 0 - 1/2 A*r^g ) */

int __declspec(dllexport) APIENTRY UserGrinDefinition(double *data)
	{
	double r, g, index, B, C, k0, k1, k2, lambda2, lambda4, x, y, AL, NL, temp;

	g  = data[10];
	B  = data[11];
	C  = data[12];
	k0 = data[13];
	k1 = data[14];
	k2 = data[15];

   x = data[1];
   y = data[2];

   r = sqrt(x*x + y*y);

	lambda2 = data[4]*data[4];
	lambda4 = lambda2*lambda2;

	AL = k0 + k1/lambda2 + k2/lambda4;
	AL *= AL;

	NL = B + C/lambda2;

   index = NL * (1.0 - 0.5*AL*pow(r, g));
	data[6] = index;

   if (index < 1.0)
		{
		return -1;
		}

	/* now the derivatives, note they are multiplied by index */
	temp    = -0.5*NL*AL*g*pow(r, g-2.0)*index;
   data[7] = temp*x;
   data[8] = temp*y;
   data[9] = 0.0;
	return 0;
   }


int __declspec(dllexport) APIENTRY UserParamNames(char *data)
	{
	/* this function returns the name of the parameter requested */
	int i;
	i = (int) data[0];
	strcpy(data,"");
	if (i == 1) strcpy(data,"g");
	if (i == 2) strcpy(data,"B");
	if (i == 3) strcpy(data,"C");
	if (i == 4) strcpy(data,"k0");
	if (i == 5) strcpy(data,"k1");
	if (i == 6) strcpy(data,"k2");	
	return 0;
	}
