/* Copyright Abandoned 1996 TCX DataKonsult AB & Monty Program KB & Detron HB
   This file is public domain and comes with NO WARRANTY of any kind */

#ifndef _my_sys_h
#define _my_sys_h
#ifdef	__cplusplus
extern "C" {
#endif

#ifdef HAVE_AIOWAIT
#include <sys/asynch.h>		/* Used by record-cache */
typedef struct my_aio_result {
  aio_result_t result;
  int	       pending;
} my_aio_result;
#endif

#ifdef THREAD
extern int *_my_errno(void) __attribute__ ((const));
#define my_errno  (*_my_errno())
#else
extern int NEAR my_errno;		/* Last error in mysys */
#endif

#define MYSYS_PROGRAM_USES_CURSES()  { error_handler_hook = my_message_curses;	mysys_uses_curses=1; }
#define MYSYS_PROGRAM_DONT_USE_CURSES()  { error_handler_hook = my_message_no_curses; mysys_uses_curses=0;}
#define MY_INIT(name);		{ my_progname= name; my_init(); }

#define MAXMAPS		(4)	/* Number of error message maps */
#define ERRMOD		(1000)	/* Max number of errors in a map */
#define ERRMSGSIZE	(SC_MAXWIDTH)	/* Max length of a error message */
#define NRERRBUFFS	(2)	/* Buffers for parameters */
#define MY_FILE_ERROR	((uint) ~0)
#define MY_FILEPOS_ERROR	((ulong) ~0L)

	/* General bitmaps for my_func's */
#define MY_FFNF		1	/* Fatal if file not found */
#define MY_FNABP	2	/* Fatal if not all bytes read/writen */
#define MY_NABP		4	/* Error if not all bytes read/writen */
#define MY_FAE		8	/* Fatal if any error */
#define MY_WME		16	/* Write message on error */
#define MY_WAIT_IF_FULL 32	/* Wait and try again if disk full error */
#define MY_LINK_WARNING 32	/* my_redel() gives warning if links */
#define MY_COPYTIME	64	/* my_redel() copys time */
#define MY_HOLD_ORIGINAL_MODES 128  /* my_copy() holds to file modes */
#define MY_SEEK_NOT_DONE 32	/* my_lock may have to do a seek */
#define MY_DONT_WAIT	64	/* my_lock() don't wait if can't lock */
#define MY_ZEROFILL	32	/* my_malloc(), fill array with zero */
#define MY_ALLOW_ZERO_PTR 64	/* my_realloc() ; zero ptr -> malloc */
#define MY_FREE_ON_ERROR 128	/* my_realloc() ; Free old ptr on error */
#define MY_HOLD_ON_ERROR 256	/* my_realloc() ; Return old ptr on error */

#define MY_CHECK_ERROR	1	/* Params to my_end; Check open-close */
#define MY_GIVE_INFO	2	/* Give time info about process*/

#define ME_HIGHBYTE	8	/* Shift for colours */
#define ME_NOCUR	1	/* Don't use curses message */
#define ME_OLDWIN	2	/* Use old window */
#define ME_BELL		4	/* Ring bell then printing message */
#define ME_HOLDTANG	8	/* Don't delete last keys */
#define ME_WAITTOT	16	/* Wait for errtime secs of for a action */
#define ME_WAITTANG	32	/* Wait for a user action  */
#define ME_NOREFRESH	64	/* Dont refresh screen */
#define ME_NOINPUT	128	/* Dont use the input libary */
#define ME_COLOUR1	((1 << ME_HIGHBYTE))	/* Possibly error-colours */
#define ME_COLOUR2	((2 << ME_HIGHBYTE))
#define ME_COLOUR3	((3 << ME_HIGHBYTE))


	/* My seek flags */
#define MY_SEEK_SET	0
#define MY_SEEK_CUR	1
#define MY_SEEK_END	2

	/* Some constants */
#define MY_WAIT_FOR_USER_TO_FIX_PANIC	60	/* in seconds */
#define MY_WAIT_GIVE_USER_A_MESSAGE	10	/* Every 10 times of prev */

	/* defines when allocating data */

#ifdef SAFEMALLOC
#define my_malloc(SZ,FLAG) _mymalloc( SZ, __FILE__, __LINE__, FLAG )
#define my_realloc(PTR,SZ,FLAG) _myrealloc( PTR, SZ, __FILE__, __LINE__, FLAG )
#define my_checkmalloc() _sanity( __FILE__, __LINE__ )
#define my_free(PTR,FLAG) _myfree( PTR, __FILE__, __LINE__,FLAG)
#define my_memdup(A,B,C) _my_memdup(A,B,__FILE__,__LINE__,C)
#define my_strdup(A,C) _my_strdup(A,__FILE__,__LINE__,C)
#define QUICK_SAFEMALLOC sf_malloc_quick=1
#define NORMAL_SAFEMALLOC sf_malloc_quick=0
extern uint sf_malloc_prehunc,sf_malloc_endhunc,sf_malloc_quick;
#else
#define my_checkmalloc() (0)
#define TERMINATE(A) {}
#define QUICK_SAFEMALLOC
#define NORMAL_SAFEMALLOC
extern gptr my_malloc(uint Size,myf MyFlags);
extern gptr my_realloc(gptr oldpoint,uint Size,myf MyFlags);
extern void my_no_flags_free(gptr ptr);
extern gptr my_memdup(const byte *from,uint length,myf MyFlags);
extern string my_strdup(const byte *from,myf MyFlags);
#define my_free(PTR,FG) my_no_flags_free(PTR)
#endif
#ifdef HAVE_ALLOCA
#define my_alloca(SZ) alloca((size_t) (SZ))
#define my_afree(PTR) {}
#else
#define my_alloca(SZ) my_malloc(SZ,MYF(0))
#define my_afree(PTR) my_free(PTR,MYF(MY_WME))
#endif /* HAVE_ALLOCA */
#ifdef MSDOS
#ifdef __ZTC__
void * __CDECL halloc(long count,size_t length);
void   __CDECL hfree(void *ptr);
#endif
#if defined(USE_HALLOC)
#if defined(_VCM_) || defined(M_IC80386)
#undef USE_HALLOC
#endif
#endif
#ifdef USE_HALLOC
#define malloc(a) halloc((long) (a),1)
#define free(a) hfree(a)
#endif
#endif /* MSDOS */


#ifdef HAVE_ERRNO_AS_DEFINE
#include <errno.h>			/* errno is a define */
#else
extern int errno;			/* declare errno */
#endif
extern char ** NEAR errmsg[];
extern char NEAR errbuff[NRERRBUFFS][ERRMSGSIZE];
extern char *home_dir;			/* Home directory for user */
extern char *my_progname;		/* program-name (printed in errors) */
extern char NEAR curr_dir[];		/* Current directory for user */
extern int (*error_handler_hook)(const char *str,myf MyFlags);
extern int (*fatal_error_handler_hook)(const char *str,myf MyFlags);

					/* Point to current my_message() */
extern void (*my_sigtstp_cleanup)(void),
					/* Executed before jump to shell */
	    (*my_sigtstp_restart)(void),
	    (*my_abort_hook)(int);
					/* Executed when comming from shell */
extern int NEAR my_umask,		/* Default creation mask  */
	   NEAR my_recived_signals,	/* Signals we have got */
	   NEAR my_safe_to_handle_signal, /* Set when allowed to SIGTSTP */
	   NEAR my_dont_interrupt,	/* call remember_intr when set */
	   NEAR mysys_uses_curses;
extern long lCurMemory,lMaxMemory;	/* from safemalloc */

extern uint	my_default_record_cache_size;
extern int NEAR my_disable_locking,NEAR my_disable_async_io;
extern char	wild_many,wild_one,wild_prefix;

typedef struct wild_file_pack	/* Struct to hold info when selecting files */
{
  uint		wilds;		/* How many wildcards */
  uint		not_pos;	/* Start of not-theese-files */
  string	*wild;		/* Pointer to wildcards */
} WF_PACK;

typedef struct st_typelib {	/* Different types saved here */
  uint count;			/* How many types */
  string name;			/* Name of typelib */
  string *type_names;
} TYPELIB;

enum cache_type {READ_CACHE,WRITE_CACHE};

typedef struct st_record_cache	/* Used when cacheing records */
{
  File file;
  int	rc_seek,error,inited;
  uint	rc_length,read_length,reclength;
  ulong rc_record_pos,end_of_file;
  byte	*rc_buff,*rc_buff2,*rc_pos,*rc_end,*rc_request_pos;
#ifdef HAVE_AIOWAIT
  int	use_async_io;
  my_aio_result aio_result;
#endif
  enum cache_type type;
} RECORD_CACHE;

enum file_type { UNOPEN = 0, FILE_BY_OPEN, FILE_BY_CREATE,
		   STREAM_BY_FOPEN, STREAM_BY_FDOPEN };

extern struct my_file_info
{
  string		name;
  enum file_type	type;
} my_file_info[MY_NFILE];


typedef struct st_dynamic_array {
  char *buffer;
  uint elements,max_element;
  uint alloc_increment;
  uint size_of_element;
} DYNAMIC_ARRAY;

typedef struct st_dynamic_string {
  char *str;
  uint length,max_length,alloc_increment;
} DYNAMIC_STRING;


typedef struct st_io_cache		/* Used when cacheing files */
{
  byte	*rc_pos,*rc_end,*buffer,*rc_request_pos;
  File file;
  int	seek_not_done,error;
  uint	buffer_length,read_length;
  ulong pos_in_file,end_of_file;
  myf	myflags;			/* Flags used to my_read/my_write */
#ifdef HAVE_AIOWAIT
  uint inited;
  ulong aio_read_pos;
  my_aio_result aio_result;
#endif
  enum cache_type type;
  int (*read_function)(struct st_io_cache *,byte *,uint);
  char *file_name;			/* if used with 'open_cacheed_file' */
} IO_CACHE;

	/* defines for mf_iocache */

	/* Test if buffer is inited */
#define my_b_clear(info) (info)->buffer=0
#define my_b_inited(info) (info)->buffer
#define my_b_EOF INT_MIN

#define my_b_read(info,Buffer,Count) \
  ((ulong) (info)->rc_pos + (Count) <= (ulong) (info)->rc_end ?\
   (memcpy(Buffer,(info)->rc_pos,(size_t) (Count)), \
    ((info)->rc_pos+=(Count)),0) :\
   (*(info)->read_function)((info),Buffer,Count))

#define my_b_get(info) \
  ((info)->rc_pos != (info)->rc_end ?\
   ((info)->rc_pos++, (int) (info)->rc_pos[-1]) :\
   _my_b_get(info))

#define my_b_write(info,Buffer,Count) \
  ((ulong) (info)->rc_pos + (Count) <= (ulong) (info)->rc_end ?\
   (memcpy((info)->rc_pos,Buffer,(size_t) (Count)), \
    ((info)->rc_pos+=(Count)),0) :\
   _my_b_write(info,Buffer,Count))

	/* my_b_write_byte dosn't have any err-check */
#define my_b_write_byte(info,chr) \
  (((ulong) (info)->rc_pos < (ulong) (info)->rc_end) ?\
   ((*(info)->rc_pos++)=(chr)) :\
   (_my_b_write(info,0,0) , ((*(info)->rc_pos++)=(chr))))

#define my_b_fill_cache(info) \
  (((info)->rc_end=(info)->rc_pos),(*(info)->read_function)(info,0,0))

#define my_b_tell(info) ((info)->pos_in_file + \
			 (uint) ((info)->rc_pos - (info)->rc_request_pos))

	/* Prototypes for mysys and my_func functions */

extern int my_copy(const char *from,const char *to,myf MyFlags);
extern int my_append(const char *from,const char *to,myf MyFlags);
extern int my_delete(const char *name,myf MyFlags);
extern int my_getwd(string buf,uint size,myf MyFlags);
extern int my_setwd(const char *dir,myf MyFlags);
extern int my_lock(File fd,int op,ulong start, ulong length,myf MyFlags);
extern gptr my_once_alloc(uint Size,myf MyFlags);
extern void my_once_free(void);
extern string my_tempnam(const char *dir,const char *pfx,myf MyFlags);
extern File my_open(const char *FileName,int Flags,myf MyFlags);
extern File my_create(const char *FileName,int CreateFlags,
			  int AccsesFlags, myf MyFlags);
extern int my_close(File Filedes,myf MyFlags);
extern uint my_read(File Filedes,byte *Buffer,uint Count,myf MyFlags);
extern uint my_pread(File Filedes,byte *Buffer,uint Count,ulong offset,
			 myf MyFlags);
extern ulong my_lread(File Filedes,byte *Buffer,ulong Count,myf MyFlags);
extern int my_rename(const char *from,const char *to,myf MyFlags);
extern ulong my_seek(File fd,ulong pos,int whence,myf MyFlags);
extern ulong my_tell(File fd,myf MyFlags);
extern uint my_write(File Filedes,const byte *Buffer,uint Count,
			 myf MyFlags);
extern uint my_pwrite(File Filedes,const byte *Buffer,uint Count,
			  ulong offset,myf MyFlags);
extern uint my_fread(FILE *stream,byte *Buffer,uint Count,myf MyFlags);
extern uint my_fwrite(FILE *stream,const byte *Buffer,uint Count,
			  myf MyFlags);
extern ulong my_fseek(FILE *stream,ulong pos,int whence,myf MyFlags);
extern ulong my_ftell(FILE *stream,myf MyFlags);
extern ulong my_lwrite(File Filedes,const byte *Buffer,ulong Count,
			  myf MyFlags);
extern gptr _mymalloc(uint uSize,const char *sFile,
			  uint uLine, myf MyFlag);
extern gptr _myrealloc(string pPtr,uint uSize,const char *sFile,
			   uint uLine, myf MyFlag);
extern gptr my_multi_malloc _VARARGS((myf MyFlags, ...));
extern void _myfree(gptr pPtr,const char *sFile,uint uLine, myf MyFlag);
extern int _sanity(const char *sFile,unsigned int uLine);
extern gptr _my_memdup(const byte *from,uint length,
			   const char *sFile, uint uLine,myf MyFlag);
extern string _my_strdup(const byte *from, const char *sFile, uint uLine,
			     myf MyFlag);
#ifndef TERMINATE
extern void TERMINATE(FILE *file);
#endif
extern void init_glob_errs(void);
extern FILE *my_fopen(const char *FileName,int Flags,myf MyFlags);
extern FILE *my_fdopen(File Filedes,int Flags,myf MyFlags);
extern int my_fclose(FILE *fd,myf MyFlags);
extern int my_chsize(File fd,ulong newlength,myf MyFlags);
extern int my_error _VARARGS((int nr,myf MyFlags, ...));
extern int my_printf_error _VARARGS((const string format,myf MyFlags, ...));
extern int my_message(const char *str,myf MyFlags);
extern int my_message_no_curses(const char *str,myf MyFlags);
extern int my_message_curses(const char *str,myf MyFlags);
extern void my_init(void );
extern void my_end(int infoflag);
extern int my_redel(const char *from, const char *to, int MyFlags);
extern int my_copystat(const char *from, const char *to, int MyFlags);
extern string my_filename(File fd);

extern void dont_break(void);
extern void allow_break(void);
extern void my_remember_signal(int signal_number,sig_handler (*func)(int));
extern void caseup(string str,uint length);
extern void casedn(string str,uint length);
extern void caseup_str(string str);
extern void casedn_str(string str);
extern void case_sort(string str,uint length);
extern uint dirname_part(string to,const char *name);
extern uint dirname_length(const char *name);
#define base_name(A) (A+dirname_length(A))
extern int test_if_hard_path(const char *dir_name);
extern void convert_dirname(string name);
extern string fn_ext(const char *name);
extern string fn_same(string toname,const char *name,int flag);
extern string fn_format(string to,const char *name,const char *dsk,
			    const char *form,int flag);
extern size_s strlength(const char *str);
extern void pack_dirname(string to,const char *from);
extern uint unpack_dirname(string to,const char *from);
extern uint cleanup_dirname(string to,const char *from);
extern uint system_filename(string to,const char *from);
extern string unpack_filename(string to,const char *from);
extern string intern_filename(string to,const char *from);
extern string directory_file_name(string dst, string src);
extern int pack_filename(string to, string name, size_s max_length);
extern string my_path(string to,const char *progname,
			 const char *own_pathname_part);
extern string my_load_path(string to, const char *path,
			      const char *own_path_prefix);
extern int wild_compare(const char *str,const char *wildstr);
extern string strcasestr(const char *src,const char *suffix);
extern int my_strcasecmp(const char *s,const char *t);
extern int my_strsortcmp(const char *s,const char *t);
extern int my_casecmp(const char *s,const char *t,uint length);
extern int my_sortcmp(const char *s,const char *t,uint length);
extern WF_PACK *wf_comp(string str);
extern int wf_test(struct wild_file_pack *wf_pack,const char *name);
extern void wf_end(struct wild_file_pack *buffer);
extern size_s stripp_sp(string str);
extern void get_date(string to,int timeflag,time_t use_time);
extern void soundex(string out_pntr, string in_pntr,pbool remove_garbage);
extern int init_record_cache(RECORD_CACHE *info,uint cachesize,File file,
				uint reclength,enum cache_type type,
				pbool use_async_io);
extern int read_cache_record(RECORD_CACHE *info,byte *to);
extern int end_record_cache(RECORD_CACHE *info);
extern int write_cache_record(RECORD_CACHE *info,ulong filepos,
				 const byte *record,uint length);
extern int flush_write_cache(RECORD_CACHE *info);
extern long my_clock(void);
extern sig_handler sigtstp_handler(int signal_number);
extern void handle_recived_signals(void);
extern int init_key_cache(ulong use_mem,ulong leave_this_much_mem);
extern byte *key_cache_read(File file,ulong filepos,byte* buff,uint length,
			       uint block_length,int return_buffer);
extern int key_cache_write(File file,ulong filepos,byte* buff,uint length,
			      uint block_length,int force_write);
extern int flush_key_blocks(int file,pbool free_used_blocks);
extern void end_key_cache(void);
extern sig_handler my_set_alarm_variable(int signo);
extern void my_string_ptr_sort(void *base,uint items,size_s size);
extern void radixsort_for_str_ptr(uchar* base[], uint number_of_elements,
				  size_s size_of_element,uchar *buffer[]);
extern int init_io_cache(IO_CACHE *info,File file,uint cachesize,
			    enum cache_type type,ulong seek_offset,
			    pbool use_async_io, myf cache_myflags);
extern void reinit_io_cache(IO_CACHE *info,enum cache_type type,
			       ulong seek_offset,pbool use_async_io);
extern int _my_b_read(IO_CACHE *info,byte *Buffer,uint Count);
extern int _my_b_get(IO_CACHE *info);
extern int _my_b_async_read(IO_CACHE *info,byte *Buffer,uint Count);
extern int _my_b_write(IO_CACHE *info,const byte *Buffer,uint Count);
extern int flush_io_cache(IO_CACHE *info);
extern int end_io_cache(IO_CACHE *info);
extern int open_cacheed_file(IO_CACHE *cache,const char *prefix,
				uint cache_size);
extern void close_cacheed_file(IO_CACHE *cache);
extern my_bool init_dynamic_array(DYNAMIC_ARRAY *array,uint element_size,
				   uint init_alloc,uint alloc_increment);
extern my_bool insert_dynamic(DYNAMIC_ARRAY *array,gptr element);
extern byte *alloc_dynamic(DYNAMIC_ARRAY *array);
extern byte *pop_dynamic(DYNAMIC_ARRAY*);
extern my_bool set_dynamic(DYNAMIC_ARRAY *array,gptr element,uint index);
extern void get_dynamic(DYNAMIC_ARRAY *array,gptr element,uint index);
extern void delete_dynamic(DYNAMIC_ARRAY *array);
extern void freeze_size(DYNAMIC_ARRAY *array);
#define dynamic_array_ptr(array,index) ((array)->buffer+(index)*(array)->size_of_element)
#define dynamic_element(array,index,type) ((type)((array)->buffer) +(index))
#define push_dynamic(A,B) insert_dynamic(A,B)

extern int find_type(string x,TYPELIB *typelib,int full_name);
extern void make_type(string to,uint nr,TYPELIB *typelib);
extern string get_type(TYPELIB *typelib,uint nr);
extern my_bool init_dynamic_string(DYNAMIC_STRING *str,string init_str,
				    uint init_alloc,uint alloc_increment);
extern my_bool dynstr_append(DYNAMIC_STRING *str,string append);
extern void dynstr_free(DYNAMIC_STRING *str);
#ifdef HAVE_MLOCK
extern byte *my_malloc_lock(uint length,myf flags);
extern void my_free_lock(byte *ptr,myf flags);
#else
#define my_malloc_lock(A,B) my_malloc((A),(B))
#define my_free_lock(A,B) my_free((A),(B))
#endif

#ifdef _MSC_VER
extern void sleep(int sec);
#endif

#ifdef	__cplusplus
}
#endif
#endif /* _my_sys_h */
