#ifdef STANDARD
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#ifdef __WIN__
typedef unsigned __int64 ulonglong;
typedef __int64 longlong;
#else
typedef unsigned long long ulonglong;
typedef long long longlong;
#endif /*__WIN__*/
#else
#include <my_global.h>
#include <my_sys.h>
#include <m_string.h>
#endif
#include <mysql.h>
#include <ctype.h>

#define PI 3.1415926535

#ifdef HAVE_DLOPEN

extern "C" {
    my_bool distance_init(UDF_INIT *, UDF_ARGS *args, char *message);
    double distance(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error);
}

my_bool distance_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
  if ( args->arg_count != 4 )
  {
    strcpy(message,"usage: DISTANCE(x1,y1,x2,y2)");
    return 1;
  }

  for (uint i=0 ; i < args->arg_count; i++)
    args->arg_type[i]=STRING_RESULT;
  initid->maybe_null=1;
  initid->decimals=2;
  initid->max_length=6;
  return 0;
}


double distance(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error)
{
    double x1, x2, y1, y2;
    double result;
    
    x1 = (double) atof(args->args[0]);
    y1 = (double) atof(args->args[1]);
    x2 = (double) atof(args->args[2]);
    y2 = (double) atof(args->args[3]);
	    
    result = 111.13384*acos(cos(x1*(PI/180))*cos(x2*(PI/180))*cos((y1-y2)*(PI/180))+sin(x1*(PI/180))*sin(x2*(PI/180)))/(PI/180);
	      
    *is_null = 0;
    *error = 0;
		  
    return result;
}

#endif

