/* Copyright (C) 2002 MySQL AB

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */


#ifdef STANDARD
/* STANDARD is defined, don't use any mysql functions */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#ifdef __WIN__
typedef unsigned __int64 ulonglong;	/* Microsofts 64 bit types */
typedef __int64 longlong;
#else
typedef unsigned long long ulonglong;
typedef long long longlong;
#endif /*__WIN__*/
#else
#include <my_global.h>
#include <my_sys.h>
#if defined(MYSQL_SERVER)
#include <m_string.h>		/* To get strmov() */
#else
/* when compiled as standalone */
#include <string.h>
#define strmov(a,b) stpcpy(a,b)
#define bzero(a,b) memset(a,0,b)
#define memcpy_fixed(a,b,c) memcpy(a,b,c)
#endif
#endif
#include <mysql.h>
#include <ctype.h>

#ifdef HAVE_DLOPEN

/* These must be right or mysqld will not find the symbol! */

my_bool ltrim_junk_init(UDF_INIT *initid, UDF_ARGS *args, char *message);
void ltrim_junk_deinit(UDF_INIT *initid);
char *ltrim_junk(UDF_INIT *initid, UDF_ARGS *args, char *result,
	       unsigned long *length, char *is_null, char *error);



my_bool ltrim_junk_init(UDF_INIT *initid __attribute__((unused)), 
                        UDF_ARGS *args, char *message)
{
  if (args->arg_count != 1 || args->arg_type[0] != STRING_RESULT)
  {
    strcpy(message,"Usage: ltrim_junk(s)");
    return 1;
  }
  return 0;
}


void ltrim_junk_deinit(UDF_INIT *initid __attribute__((unused)))
{
}



char *ltrim_junk(UDF_INIT *initid __attribute__((unused)),
               UDF_ARGS *args, char *result, unsigned long *length,
               char *is_null, char *error __attribute__((unused)))
{
  const char *s=args->args[0];
  const char* s_end;
  unsigned long res_len = 0;

  if (!s)
  {
     *is_null = 1;
     return 0;
  }
  s_end = s + args->lengths[0];

  while (!isalpha(*s) && s < s_end)
    s++; 

  if (s < s_end)
  {
    res_len = s_end - s; 
    memcpy(result,s,res_len);
  }

  *length= res_len;
  return result;
}



#endif /* HAVE_DLOPEN */