#ifndef _INTERNETSQLLIBH_
#define _INTERNETSQLLIBH_

#ifndef SUNUNIX
#include <windows.h>
#include <windowsx.h>
#include <winsock.h>
#define DIR_SLASH "\\"
#define TABLEDIR "table\\"
#define USERDIR "user\\"
#define INDEXDIR "index\\"
#define FILESYSDIR "filesystem\\"
#define STOREDPROC "storedproc\\"

#else
#define TRUE 1
#define FALSE 0
extern int INVALID_SOCKET;
extern int SOCKET_ERROR ;
#define WSAEWOULDBLOCK 1      
#define DIR_SLASH "/"
#define TABLEDIR "table/"
#define USERDIR "user/"
#define INDEXDIR "index/"
#define FILESYSDIR "filesystem/"
#define STOREDPROC "storedproc/"
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>

#endif

#if 0
typedef struct KINT64
{
	unsigned KINT64 Low;
	unsigned KINT64 High;
}KINT64;

typedef struct kuint32
{
	unsigned short int Low;
	unsigned short int High;
} KUINT32;
#endif

#ifndef SUNUNIX
typedef  double KDOUBLE;
/* Genuine 64-bit record number / file offset type (Part 17 of
 * WEBSUPPORT_ICPP_PLAN.md: "ISQL 64-bit build + trillion-record scale").
 * 'long long' is used rather than reviving the MSVC-specific '__int64'
 * seen commented out just above, since 'long long' is the one integer
 * type guaranteed 64-bit on both the MSVC and gcc toolchains this engine
 * must build under (LLP64 Windows has a 32-bit 'long'; LP64 Linux has a
 * 64-bit 'long' but 'long long' is 64-bit on both, so it's the portable
 * choice regardless of platform's data model). This is a genuine
 * on-disk format break: every struct with an embedded KINT64/UKINT64
 * field (STORAGE_FIELD_INFO, STORAGE_BLOCK_HEADER, table/index headers)
 * changes size - old-format database files are not compatible with an
 * engine built from this header. See db_backup_pre64bit_* for the
 * pre-change snapshot of every database this project had on disk. */
typedef long long KINT64;
#else
typedef long long KINT64;
typedef double KDOUBLE;
#endif


//#include "tblstrct.h"
//#define EMBEDDED_RDBMS

#define ELSE_BEGIN else {
#define ELSE_END }

#define TRANSACTION_RECORD_FIELD 'X'
#define TIME_FIELD 'Q'  //format hh:mm:ss:ss/100
#define DIR_FIELD  'W'  
#define SUBDIR_FIELD  'Z'  
#define FILE_FIELD  'Y'  
#define BINARY_FIELD  'B'  
#define BLOB_FIELD  'U' 
#define ENUM_FIELD  'E'  
#define PASSWORD_FIELD 'R' 
#define DOUBLE_TYPE 'n'
#define FLOAT_TYPE  'n' 
#define LONG_FIELD_TYPE 'n'
#define INT_FIELD_TYPE  'n'
//#define MAXINDEXKEYLEN 	256
//#define MAXINDEXKEYCOUNT 1

#define MAXINDEXKEYLEN 	2048
#define MAXINDEXKEYCOUNT 48

#ifndef EMBEDDED_RDBMS
//#define INDEX_NODE_SIZE 1024
#define INDEX_NODE_SIZE 16384
#define NAME_BUF_SIZE 256
#define MAX_CHAR_FIELD_SIZE 255
//#define EXTENDED_FIELDHEADER_SIZE 256 
#define EXTENDED_TABLETYPE 'K'
#define MAX_UPLOAD_SIZE 65536
#define KAMMAX_RECORDLEN 65536

#define MAX_XBASE_RECORDLEN 65536
#define MAX_EXTENDED_RECORDLEN 0x50000  // 64k * 5
//#define MAX_EXTENDED_RECORDLEN MAX_XBASE_RECORDLEN

#define INDEX_BUF_SIZE 0x20000 //128k 


#define TABLE_RECORD_CACHE_SIZE 0x10000 //64k
#define ORGBUFSIZE    MAX_EXTENDED_RECORDLEN

//#define BUFSIZE       0x100000 
#define BUFSIZE  MAX_EXTENDED_RECORDLEN
#define COMMAND_BUFFER_SIZE  MAX_EXTENDED_RECORDLEN
#define COMMDATABUFLEN  COMMAND_BUFFER_SIZE

//#define MAX_QRY_BUFFER_SIZE 0x80000 //512 k
#define MAX_QRY_BUFFER_SIZE MAX_EXTENDED_RECORDLEN


#else
#if 0
#define INDEXNODESIZE 512
#define NAME_BUF_SIZE 64
#define MAX_CHAR_FIELD_SIZE 64
#define EXTENDED_FIELDHEADER_SIZE 64 
#define EXTENDED_TABLETYPE 'E'
#define MAX_UPLOAD_SIZE 8000
#define COMMAND_BUFFER_SIZE 12000
#define KAMMAX_RECORDLEN 16000
#define INDEXBUFSIZE 0x1000
#define BUFSIZE 0x2000 
#define MAX_QRY_BUFFER_SIZE 0x2000 //32k
#endif
 




#endif

#define INDEX_HEADER_SIZE INDEX_NODE_SIZE
#define INDEX_ROOTDIR_SIZE INDEX_NODE_SIZE

#define LASTLEFT INDEX_HEADER_SIZE
#define INDEXNODE_LEAF_TYPE  0xAA
#define INDEXNODE_ROOT_TYPE 0xAC
#define INDEXNODE_DIR_TYPE 0xAB

#define LISTBUF_HEADER_SIZE 16
#define LISTBUFFER_RECORD_NUMBER_CAPACITY 8000

#define LISTBUFSIZE ((sizeof(KINT64) * LISTBUFFER_RECORD_NUMBER_CAPACITY) + LISTBUF_HEADER_SIZE)
#define MAXLISTKEYLEN 120
#define MAX_DOWNLOAD_SIZE MAX_UPLOAD_SIZE

#define STORE_DATA_FIRST  0x01
#define STORE_DATA_APPEND 0x02
#define STORE_DATA_LAST   0x03

#define LONGINT_FIELD_LEN 20
#define DOUBLE_FIELD_LEN  40
#define DOUBLE_DECIMAL_LEN  16
#define TIME_FIELD_LEN 8
#define DATE_FIELD_LEN 8


#define RESERVED 16
#define INTTYPE 1
#define SHORTINTTYPE 2
#define KINT64TYPE    3
#define KINT64DOUBLETYPE    4
#define FLOATTYPE    5
#define DOUBLETYPE    6
#define STRINGTYPE    7
#define TOP    -1   //record no 1
#define BOTTOM -2   //last record
#define ZERO    0   //begining of data
#define EVALSTACKDYNAMIC 1
#define EVALSTACKSIZE 128
#define Min(a,b)  ((a) <(b)) ? (a): (b)
#define Minimum(a,b)  ((a) <(b)) ? (a): (b)
#define Maximum(a,b)  ((a) >(b)) ? (a): (b)
#define __RECVAR__ 11
#define __SYSVAR__ 12
#define  __SQLFIELDQRY__ 13
#define  __SQLEXPRQRY__  14
#define  __SQLCONSTSTRINGQRY__ 15
#define  __SQLCONSTNUMBERQRY__ 16
#define  __GROUPBYCOLUMNFUNCSI__ 17
#define  __SQLRECNOQRY__  18
#define  __DATETOCHAR__  19
#define __WINDOWSHDR__ 1
#define SHOWNODEFAULT 0
#define SHOWDEFAULT 1

#define SELECT_MARK   0x01
#define EMPTY_MARK    0x02
#define ROLLBACK_MARK 0x04
#define DELETE_MARK   0x08
#define CLEAR_MARK    0x20

#define MODALFORM 1
#define MODELESSFORM 0
#define FUNCCLASS 1
#define VARCLASS 2


#define FIELDNAMELEN 10

#define MAX_FIELD_BUFFER_SIZE 260
#define MAX_PARTIAL_MATCH_COUNT 16

#define MAXBUF_RDWR_SIZE 65000 

//#define BUFSIZE 0x7ffff //512 k
#define NO_WILD_CARD_IN_LIKE_OPERATOR 0xffffffff;
#define LISTEN_MAXCLIENT 20
#define LISTEN_MAX_PARALLEL_SERVER 5


#ifdef SUNUNIX
typedef int HWND,HINSTANCE,HDC,HANDLE;
#endif
  
typedef short int INT16;
typedef unsigned short int UINT16;
typedef unsigned short int WORD;
typedef double NUMBERTYPE;
typedef long KAM_INT32;
typedef unsigned long KAM_UINT32;
typedef unsigned char BYTE;
typedef unsigned long long UKINT64;

typedef char DATETYPE[8];
typedef char *CHARTYPE;
typedef char *KEYPOINTER;
typedef int  (*CONDITIONPROC)(void);
typedef int (*INDEXPROC)(void);
typedef int (*LISTPROC)(void);
typedef enum {ANDRELATION,ORRELATION} RELATION;
typedef enum {CHARACTER,NUMERIC} INDEXDATATYPE;


#define COMMANDFAILED        0 
#define SELECTCOMMAND 		 1
#define UPDATETABLECOMMAND   2
#define RECOVERTABLECOMMAND  3
#define DROPTABLECOMMAND 	 4
#define DROPVIEWCOMMAND 	 5
#define CREATETABLECOMMAND	 6
#define CREATEVIEWCOMMAND	 7
#define CREATEINDEXCOMMAND	 8
#define ALTERTABLECOMMAND	 9
#define INSERTCOMMAND		 10
#define DELETEFROMCOMMAND	 11
#define DELETETABLECOMMAND	 12
#define DELETEVIEWCOMMAND	 13
#define DELETEINDEXCOMMAND	 14
#define UNDELETEFROMCOMMAND  15
#define REINDEXCOMMAND		 16
#define RECOVERINDEXCOMMAND  17
#define RECOVERVIEWCOMMAND   18
#define DROPINDEXCOMMAND 	 19
#define CREATEDATABASECOMMAND	 20
#define COMMITCOMMAND      21
#define ROLLBACKCOMMAND    22
#define INCLUDECOMMAND     23
#define PACKCOMMAND        24
#define CONNECTCOMMAND     25
#define DISCONNECTCOMMAND  26
#define GRANTCOMMAND       27
#define REVOKECOMMAND      28
#define EXPANDDATABASECOMMAND      29
#define LOCKCOMMAND        30
#define UNLOCKCOMMAND      31
#define LOGINCOMMAND       32
#define LOGOUTCOMMAND      33
#define REMOTECOMMAND      34
#define ADDUSERCOMMAND     35
#define DROPUSERCOMMAND    36
#define CHANGEUSERSTATCOMMAND      37
#define LOCKDATABASECOMMAND        38
#define UNLOCKDATABASECOMMAND      39
#define DESCRIBECOMMAND            40
#define SHOWCOMMAND                41
#define SETMODECOMMAND             42
#define CREATESUPERUSERCOMMAND     43
#define LISTCOMMAND                44
#define ZAPCOMMAND                 45
#define UPLOADCOMMAND              46
#define DOWNLOADCOMMAND            47
#define EXPORTCOMMAND              48
#define IMPORTCOMMAND              49
#define WRITESTORAGECOMMAND        50
#define READSTORAGECOMMAND         51
#define GETCOMMAND                 52
#define ADDGROUPCOMMAND            53
#define DROPGROUPCOMMAND           54
#define LOCKTOPLEVELCOMMAND        55
#define UNLOCKTOPLEVELCOMMAND      56
#define UNLOCKGROUPCOMMAND         57
#define LOCKGROUPCOMMAND           58 
#define ADDDATABASECOMMAND         59
#define DROPDATABASECOMMAND        60
#define ADDHOSTCOMMAND             61
#define DELETEHOSTCOMMAND          62
#define CREATECURSORCOMMAND        63
#define DELETECURSORCOMMAND        64
#define OPENCOMMAND                65
#define CLOSECOMMAND               66
#define OPENCURSORCOMMAND          67
#define CLOSECURSORCOMMAND         68
#define HELPCOMMAND                69
#define ADDBACKGROUNDCOMMAND       70
#define DELETEBACKGROUNDCOMMAND    71
#define DROPBACKGROUNDCOMMAND      72
#define RECOVERDATABASECOMMAND            73
#define RECOVERHOSTCOMMAND                74
#define DELETEDATABASECOMMAND             75
#define USECOMMAND                     76
#define SERVERCOMMAND                  77
#define RUNCOMMAND                  78
#define FETCHCOMMAND                79
#define DROPTRIGGERCOMMAND          80
#define CREATETRIGGERCOMMAND        81
#define RECOGNIZECOMMAND            82
//Vector nearest-neighbour search (VECTOR.CPP). Next free code
//after RECOGNIZE - these are a dense numbering, not a bitmask.
#define VECTORCOMMAND               83


#define TRIGGER_TIME_BEFORE 0x01
#define TRIGGER_TIME_AFTER 0x02

#define TRIGGER_CATEGORY_INSERT 1
#define TRIGGER_CATEGORY_DELETE 2
#define TRIGGER_CATEGORY_UPDATE 4
#define TRIGGER_CATEGORY_CREATE_TABLE 8
#define TRIGGER_CATEGORY_DROP_TABLE 0x10
#define TRIGGER_CATEGORY_ALTER_TABLE 0x20
#define TRIGGER_CATEGORY_CREATE_DATABASE 0x40
#define TRIGGER_CATEGORY_DROP_DATABASE 0x80
#define TRIGGER_CATEGORY_LOGON 0x100


#define SYSFILE_KMGACCESS  1
#define SYSFILE_KMGLOCK    2
#define SYSFILE_KMGINDEX   3
#define SYSFILE_SYSTABLE   4
#define SYSFILE_KMGGRP     5
#define SYSFILE_KMGACCESS_BAK  6
#define SYSFILE_KMGLOCK_BAK    7
#define SYSFILE_KMGINDEX_BAK   8
#define SYSFILE_SYSTABLE_BAK   9
#define SYSFILE_KMGGRP_BAK     10
#define SYSFILE_KMGRELATION    11
#define SYSFILE_KMGTRIGGER     12
#define SYSFILE_KMGRELATION_BAK  13
#define SYSFILE_KMGTRIGGER_BAK   14

#define DONOT_DISPLAY_FORMATTED 1  

#define    KMGINSERTLOCK    1
#define    KMGDELETELOCK 2
#define    KMGTABLELOCK  3
#define    KMGREADLOCK   4
#define    KMGUPDATELOCK 5
#define    KMGALTERLOCK  6
#define    USDATE        1
#define    ENGLISHDATE   4



#define    NUMBERMONTH     1
#define    SHORTCHARMONTH  2
#define    FULLCHARMONTH   3
#define    NUMBERDAY       4
#define    SHORTCHARDAY    5
#define    FULLCHARDAY     6
#define    SHORTYEAR       7
#define    FULLYEAR        8

#define DONOT_CARE       0
#define SELECTED         1
#define UNSELECTED       2


#define DECIMAL_POINT_LENGTH 20
#define KEY_LENGTH 128
#define PWD_BUF_LENGTH 300
#define DATABASE_NAME_SIZE  32
#define GROUP_NAME_SIZE  32
#define HOST_NAME_SIZE  32
#define USER_NAME_SIZE  32
#define USER_PWD_SIZE  PWD_LENGTH
#define SERVER_NAME_SIZE  32
 
#define INDEX_SIGNATURE_SIZE 8
#define GROUP_DROP 1
#define GROUP_RENAME 2
#define GROUP_LOCK 3
#define GROUP_UNLOCK 4
#define GROUP_CHANGE_MANAGER 5
#define GROUP_CHANGE_OWNER 6
#define GROUP_SET_ALLOW_ADMIN 7
#define MONITOR_OUTPUT_SCREEN 0
#define MONITOR_OUTPUT_LOGFILE 1
#define  INDEX_VERSION_AUTO 1
#define  INDEX_VERSION  1 //autoindexing version


#define NO_JOIN           0x00
#define JOIN_OUTER_RIGHT  0x01
#define JOIN_OUTER_LEFT   0x02
#define JOIN_OUTER_FULL   0x03
#define JOIN_INNER        0x04


#define DONOT_USE_SEPERATOR 0
#define USE_SEPERATOR 1

#define SELECT_FOR_VIEW              0x01
#define SELECT_NOT_FOR_VIEW          0x00

#define EXEC_FOR_VIEW              0x01
#define EXEC_NOT_FOR_VIEW          0x00

#define QUERY_TYPE_VIEW_SELECT       0x01
#define QUERY_TYPE_VIEW              0x02 
#define QUERY_TYPE_CREATE_CURSOR     0x03
#define QUERY_TYPE_SELECT            0x04
#define QUERY_TYPE_FROM_TYPE_SELECT  0x05
#define  SORT_ORDER_ASCENDING         0x00
#define  SORT_ORDER_DESCENDING        0x01
#define  INDEX_ORDER_ASCENDING         0x00
#define  INDEX_ORDER_DESCENDING        0x01
#define SRC_BUF_SZ  MAX_EXTENDED_RECORDLEN
#define MAXSORTKEYLEN 300
#define CMDLINE_BUFFER_SIZE MAX_EXTENDED_RECORDLEN
#define Max(a,b) ((a) > (b) ) ? (a) : (b)
#define NUM_VALUE 1
#define CHAR_VALUE 0
#define SOCKET_CLOSED 100
#define MEMORY_POOL_BUF_SIZE_FOR_SERVER  0x400000
#define MEMORY_POOL_BUF_SIZE_FOR_REMOTE_CLIENT  MEMORY_POOL_BUF_SIZE_FOR_SERVER

#define DEFAULT_TEXT_FIELD_SIZE 32000

#define MAX_BYTE_USED_FOR_NUMBERS 30
//-----------------------------------------
#ifdef CPU32
#pragma pack(push,1)   /* exact, padding-free on-disk layout for the 32-bit build */
#endif
typedef struct xbase_table_header
{
 unsigned char FileType;
 unsigned char Update[3];
#ifdef CPU32
 unsigned long TotalRecord;   /* 32-bit record count for a 32-bit (CPU32) build */
#else
 KINT64 TotalRecord;          /* 64-bit record count (default 64-bit build) */
#endif
 unsigned short PositionOfData;
#ifdef CPU32
 unsigned short LengthOfRecord;
#else
 unsigned int LengthOfRecord;   /* widened 2->4 bytes for 64-bit */
#endif
#ifdef CPU32
 char Reserved[18];
#else
 char Reserved[12];   /* TotalRecord +4, LengthOfRecord +2, minus 1 for WordSize marker */
#endif
 char WordSize;   /* word-size marker: '6' = table made by a 64-bit build, '3' = 32-bit build */
 char View;
} XBASE_TABLE_HEADER;
#ifdef CPU32
#pragma pack(pop)
#endif

//-----------------------------------
typedef struct xbasefieldstruct
{
	char fieldname[10+1];
	char fieldtype;
	long displacement;
	unsigned char fieldwidth;
	char decimalpos;
	char notnull;
	char keytype;
	char autoinc;
	char has_reference_table;
	char reserved[2];
	unsigned long incval;
	char reserved2;
	char unique;
	unsigned short int max_field_byte_used;
} XBASEFIELDHEADER;

#define XBASEFIELDHEADER_SIZE 32 
#define EXTENDED_FIELDNAMELEN 218  // 38 bytes used for field property purposes
#define EXTRA_FIELD_STRUCT_BUF_SIZE  (1284+1024-256)
typedef struct kamrangafieldstruct
{
	char fieldname[EXTENDED_FIELDNAMELEN+1]; // EXTENDED_FIELDNAMELEN==218
	char fieldtype;
	long displacement;
	long fieldwidth;
	char decimalpos;
	char notnull;
	char keytype;
	char autoinc;
	unsigned long incval;
	long max_field_byte_used;
    char unique;
	char has_reference_table;
	char international_language;
	char flags; 
	char reserved[4];  
	short int extension_size;
    short int enumcount;
    char defaultvalue[256];  //if this field is not used in the namelist of insert then use this default val
    char parentdir[256];  
    char reference_table_name[256];  
    char extra[EXTRA_FIELD_STRUCT_BUF_SIZE];
} KAMRANGAFIELDHEADER;  //3kb
#define EXTENDED_FIELDHEADER_SIZE sizeof (KAMRANGAFIELDHEADER);


typedef union fieldstruct
{
	XBASEFIELDHEADER xBaseHdr;
	KAMRANGAFIELDHEADER KmgHdr;
} FIELDSTRUCT;



typedef struct kam_tablehdrstruct
{

 //keep this this portion identical for xbase compatibility
 char FileType;
 unsigned char Update[3];
 //compatibility ends
 KINT64 TotalRecord; 
 long PositionOfData;
 long LengthOfRecord;
 long DeleteCount;
 long RollBackCount;
 KINT64 EndOfFile; 
 unsigned long CreateTime;
 unsigned long ChangeTime;
 unsigned long AccessTime;
 char Reserved[24];
 char Notes[64];
 char View;
 char HasCheck;
 char Reserved2[3];
 int CheckOffset; 
 int CheckLength; 
 char Future[363];
}KAM_TABLE_HEADER_STRUCT;  //total 512 bytes

typedef union table_header
{
  XBASE_TABLE_HEADER Xbase;
  KAM_TABLE_HEADER_STRUCT Kam;
}TABLE_HEADER;

typedef struct reference_table_for_foreign_key
{
	char fieldname[EXTENDED_FIELDNAMELEN+1]; // EXTENDED_FIELDNAMELEN==218
	char tablename[256];
	char ondelete_flag;
	char onupdate_flag;
	struct reference_table_for_foreign_key *next,*prev;
}REFTABLE;

#define ON_DELETE_CASCADE   0x10
#define ON_DELETE_NO_ACTION 0x20
#define ON_UPDATE_CASCADE   0x40
#define ON_UPDATE_NO_ACTION 0x80

typedef struct relation_table
{
	char owner_tablename[256];
	char relation_fieldname[EXTENDED_FIELDNAMELEN+1]; // EXTENDED_FIELDNAMELEN==218
	char relation_tablename[256];
	char relation_type[32];
	struct relation_table *next,*prev;
}RELATION_TABLE;

typedef struct trigger_table
{
	char owner_tablename[256];
	char trigger_type[32];
	int trigger_buf_len;
	char *trigger_buf;
	struct trigger_table *next,*prev;
}TRIGGER_TABLE;

typedef struct check_string
{
	int buf_len;
	char *buf;
	struct check_string *next,*prev;
}*CHECK_STRING;

typedef struct MutexStruct
{
    int EntityType;
	char useflag;
	char used;
	char reserved2;
	char reserved3;
	int write_request_pending;
	long time;
	char ServerName[SERVER_NAME_SIZE];
	char UserName[USER_NAME_SIZE];
	char DbName[DATABASE_NAME_SIZE];
	char TableName[256];
	KINT64 WriteMutex;
	KINT64 LockMutex;
	KINT64 AlterMutex;
	KINT64 mutexid;
	int mutextype;
	long count;
	int next_valid;
   struct MutexStruct *next,*prev;
} KAM_MUTEX;


typedef struct database_mutex
{
 	char DbName[DATABASE_NAME_SIZE];
	int EntityType;
#if 0
      case MUTEX_TABLE_READ:
      case MUTEX_TABLE_WRITE:
      case MUTEX_SYS_TABLE_READ:
      case MUTEX_SYS_TABLE_WRITE:
      case MUTEX_KMGACCSS_READ:
      case MUTEX_KMGACCSS_WRITE:
      case MUTEX_KMGLOCK_READ:
      case MUTEX_KMGLOCK_WRITE:
      case MUTEX_KMGINDEX_READ:
      case MUTEX_KMGINDEX_WRITE:
      case MUTEX_KMGGRP_READ:
      case MUTEX_KMGGRP_WRITE:
      case MUTEX_USER_RIGHT_READ:   
      case MUTEX_USER_RIGHT_WRITE: 

#endif
    KAM_MUTEX *MutexTable; //this covers index and table and storage etc
    KAM_MUTEX MutexKmgSysTable;
    KAM_MUTEX MutexKmgAccssTable;
    KAM_MUTEX MutexKmgLockTable;
    KAM_MUTEX MutexKmgIndexTable;
    KAM_MUTEX MutexKmgGrpTable;
    KAM_MUTEX *MutexUserRightsTable;
    KAM_MUTEX *MutexUserTransactionTable;
	int next_valid;
    struct database_mutex *next,*prev;
} DATABASE_MUTEX_LIST;

typedef struct MutexList
{
	char Home[256];
	int EntityType;
	int next_valid;
#if 0
      case MUTEX_DBLIST_READ:
      case MUTEX_DBLIST_WRITE:  
		  
#endif
    KAM_MUTEX MutexHostList;
    KAM_MUTEX MutexDbList;

	struct MutexList *next;
    struct MutexList *HomeList;
	DATABASE_MUTEX_LIST *DatabaseList;
} MUTEX_LIST ;

//-----------------------------
typedef struct _fieldslist_
{
  char fieldname[NAME_BUF_SIZE];
  char MarkedRevoked; 
  char fieldvalue[MAX_FIELD_BUFFER_SIZE];
  struct _fieldslist_ *next;
  struct _fieldslist_ *prev;
  class internetsqlobject *obj;
}FIELD_NAME_LIST,ENUM_LIST;

typedef struct field_attribute_for_insert
{
 char *fieldname;
 int fieldlength;
 char fieldtype;
 char decimalpoint;
 int fieldnamelen;
 char notnull;
 char keytype;
 char has_reference_table;
 char autoinc;
 char unique;
 ENUM_LIST *enumlist;
} INSERT_FIELD_ATTRIBUTE;

#define WRITE_MUTEX 0x01
#define LOCK_MUTEX 0x02
#define ALTER_MUTEX 0x03
#define READ_MUTEX 0x04


#define MAX_KAM_MUTEX 64
#define LOCAL_MUTEX_REQUEST  0x00
#define REMOTE_MUTEX_REQUEST 0x01
//KAM_MUTEX KamrangaMutex[MAX_KAM_MUTEX];
MUTEX_LIST *FindHomeMutexNode(MUTEX_LIST *head,char *home);
KAM_MUTEX *FindTableMutexNode(MUTEX_LIST *hn,char *dbname,char *tablename);
KAM_MUTEX *FindSystableMutexNode(MUTEX_LIST *hn,char *dbname);
KAM_MUTEX *FindKmgAccessMutexNode(MUTEX_LIST *hn,char *dbname);
KAM_MUTEX *FindKmgLockMutexNode(MUTEX_LIST *hn,char *dbname);
KAM_MUTEX *FindKmgIndexMutexNode(MUTEX_LIST *hn,char *dbname);
KAM_MUTEX *FindKmgGrpMutexNode(MUTEX_LIST *hn,char *dbname);
KAM_MUTEX *FindDbListMutexNode(MUTEX_LIST *hn);
KAM_MUTEX *FindKmgUserRightMutexNode(MUTEX_LIST *hn,char *dbname,char *username);
KAM_MUTEX *FindHostListMutexNode(MUTEX_LIST *hn);
KAM_MUTEX *FindKmgUserTransMutexNode(MUTEX_LIST *hn,char *dbname,char *username);
MUTEX_LIST *CreateHomeMutexNode(MUTEX_LIST **head,char *home);
KAM_MUTEX *CreateTableMutexNode(MUTEX_LIST *hn,char *dbname,char *tablename);
KAM_MUTEX *CreateSystableMutexNode(MUTEX_LIST *hn,char *dbname);
KAM_MUTEX *CreateKmgAccessMutexNode(MUTEX_LIST *hn,char *dbname);
KAM_MUTEX *CreateKmgLockMutexNode(MUTEX_LIST *hn,char *dbname);
KAM_MUTEX *CreateKmgIndexMutexNode(MUTEX_LIST *hn,char *dbname);
KAM_MUTEX *CreateKmgGrpMutexNode(MUTEX_LIST *hn,char *dbname);
KAM_MUTEX *CreateDbListMutexNode(MUTEX_LIST *hn);
KAM_MUTEX *CreateKmgUserRightMutexNode(MUTEX_LIST *hn,char *dbname,char *username);
KAM_MUTEX *CreateHostListMutexNode(MUTEX_LIST *hn);
KAM_MUTEX *CreateKmgUserTransMutexNode(MUTEX_LIST *hn,char *dbname,char *username);

void InitKamMutex(void);
long FindKmgMutex(char *home,char *dbname,char *username,char *tablename);
KAM_MUTEX *FindKmgMutexPtr(char *home,char *dbname,char *username,char *tablename,int mutextype);

long WaitForKamMutex(struct userslot *slot,char *servername,char *databasehome,char *dbname,char *username,char *tablename,int mutextype, int timeout);
long WaitForParallelServerMutex(struct userslot *slot,char *servername,char *databasehome,char *dbname,char *username,char *tablename,int mutextype);


long GetMutex(struct userslot *slot,char *servername,char *databasehome,char *dbname,char *username,char *tablename,int mutextype);
int FreeKamMutex(struct userslot *slot,long mutexid);
KAM_MUTEX *CreateKmgMutex(struct userslot *slot,char *databasehome,char *dbname,char *username,char *tablename,int mutextype);
typedef struct transaction_record_fields
{
   char rectype;
   char reserved[3];
   char recno[32];
   char reserved2[32];
} TANSACTION_RECORD_FIELDS;
//-----------------------------------------
typedef struct help_struct
{
	 char helpname[256];
	 int max_help_string_len;
	 int help_line_count;
	 char **helpdata;
}HELP_STRUCT;


//-----------------------------------------
typedef class __sysvartable__
       {
       public:
        char VarType;
        char VarClass;
        char Fieldname[NAME_BUF_SIZE];  //name of field
        char *Data;  //it can be string , pointer to numbers,pointer to array
        char FieldType;      //type of field or if it is a function then return type
        char DataType[20];
        //HANDLE ThisHandle;
        KDOUBLE number(void);
        __sysvartable__ (void);
        class __sysvartable__ *next;
        class __sysvartable__ *prev;

        
        void  *operator new(size_t amount);
      

        char ArgType;
        char FuncRetType;
        char* (*StringFunction)(char*);
        float (*FFunction)(char*);
        KDOUBLE (*DFunction)(char*);
        KDOUBLE (*LDFunction)(char*);
        KINT64  (*LFunction)(char*);
        int  (*IFunction)(char*);
        short int  (*SiFunction)(char*);
		class internetsqlobject *obj;
       
       } *SYSVARS;
//----------------------------------
typedef class __postfixlink__
        {
         
          
          public:
          char *value;
		  char value_allocated;
		  int subselect_operation;
          char VarType;
          KINT64 token; 
          KINT64 ArgToken; 
		  //char *DataString;
		  char DataString[MAX_FIELD_BUFFER_SIZE];
  		  char SetExpressionData[MAX_FIELD_BUFFER_SIZE];
  		  KDOUBLE SetExpressionNumber;
		  int set_expression;
          char FuncName[NAME_BUF_SIZE];
          KDOUBLE number;
			 //for handling SQL operation
          //----------------------------
          class SQL_SelItems   *ReturnTo_SelItem;
          //class SQL_SubSelect  *SQL_SubSelItem;
          class MainSelect  *SQL_SubSelItem;
          class __postfixlink__ *FuncArgExpr;
          class __postfixlink__ *ReturnTo;
          class __postfixlink__ *Set;
		  class __postfixlink__ *NextSet;
          char SubSelectEvaluated;
          KINT64  SubSelReturnToken;
          KINT64 SetToken;
          char ItemName[NAME_BUF_SIZE]; 
          char TableName[NAME_BUF_SIZE]; 
          char HostName[NAME_BUF_SIZE]; 
		  char DatabaseName[NAME_BUF_SIZE]; 
		  char remote;
          class TABLEOBJECT *Table;
          class RECORDOBJECT  *FieldRecList;
          class RECORDOBJECT *GroupByMap;
		  class internetsqlobject *obj;
          char *Parent;  
          KINT64 qrycount;
          char colfunc;
          //----------------------------
			 //for handling user defined functions and vars
          SYSVARS sv;

          //HANDLE ValueHandle;
          //HANDLE ThisHandle;
          class RECORDOBJECT *rl;
          class __postfixlink__ *next;
          class __postfixlink__ *prev;
		
           void  *operator new(size_t amount);
          
          char ClearValue(void);
          char AllocValue(size_t len);
          __postfixlink__(void);
        } *POSTFIXLINK;

//-------------------------
//this is the dbf field
//definitions
//-------------------------
typedef class FIELDOBJECT
                 {
                  public:
				  char tabletype; //'K' is for the extended filedname

                  char Kamranga;
				  char SelectFlag;
                  char fieldprefix[NAME_BUF_SIZE];   //field prefix, usually the owner table name
                  char fieldname[NAME_BUF_SIZE];     //field name
                  char fieldtype;         //c char
                                          //n numeric
                                          //l logical
                                          //m memo
                                          //g general
                                          //d date
                                          //f float
                                          //p picture           
                                          //type of field char or int
				  char notnull;
                  char keytype;
				  char autoinc;
				  KINT64 incval;
				  char has_reference_table;
				  char reference_table_name[256];  
				  char defaultvalue[256];
                  char parentdir[256];  
                  char extra[EXTRA_FIELD_STRUCT_BUF_SIZE];
				  short int enumcount;
                  class internetsqlobject *obj;
				  long max_field_byte_used;
				  int international_language;
				  char unique;
                  long  fieldwidth;        //column width
                  KAM_UINT32 displacement;      //position in the record
                  char decimalpos;        //decimal point position
                  char reserved[19];
                  long Selected;
                  char *data;
                  class TABLEOBJECT *Owner;
                  class FIELDOBJECT *next,*prev; //link to the another field
                  class KEYOBJECT *KeyList;
                  //HANDLE ThisHandle; 
       			  
                  void  *operator new(size_t amount);
                 

                  FIELDOBJECT(void);  
                 } *FIELDLIST;

//--------------------------------------
typedef class KEYOBJECT
        {
          public:
          char tabletype; //'K' is for the extended filedname
          char Kamranga;
          char fieldname[NAME_BUF_SIZE];
          FIELDLIST key;
		  char notnull;
		  char keytype;
		  char has_reference_table;
		  char autoinc;
		  char unique;
          class _groupitem_ *GroupItem;
          class _groupitem_  *OrderItem;
          class RECORDOBJECT *SelectItem;
          char fieldtype;         //c char
          KINT64  fieldwidth;        //column width
          KAM_UINT32 displacement;      //position in the record
          char decimalpos;        //decimal point position
          char *Data;
          KINT64 Selected;
          //HANDLE DataHandle;
          class KEYOBJECT *next;
          class KEYOBJECT *prev;
		  class internetsqlobject *obj;
          //HANDLE ThisHandle; 
       
          void  *operator new(size_t amount);
         
          KEYOBJECT(void);
       } *KEYLIST;
KEYLIST CreateKeyInfo(class internetsqlobject *obj,KEYLIST *keyhead,char *keyname,char unique);

typedef struct index_key_entry_info
{
	KINT64 node_offset_or_record_no;
	long entry_status;
} KEY_ENTRY_INFO;

#define KEY_ENTRY_INFO_SIZE sizeof(KEY_ENTRY_INFO)
#define LEAF_NOT_FULL 0x00000001


typedef struct index_leaf_header
{
          unsigned short int  Debug;
          unsigned char  Type;   //kind of index
		  char  Flag;
          KINT64   NumberOfKey; //count of key
          KINT64 Left;        //left node ptr 
          KINT64 Right;       //right node ptr
          KINT64 SelfOffset;
		  KINT64 ParentOffset;
		  char reserved[20];  //64 byte aligned
} INDEXNODEHEADER;

#define INDEXNODEHEADERSIZE sizeof(INDEXNODEHEADER)
//------------------
//declare index node
//------------------
typedef class __NODE
         {
          //-------------------         
          //declare node buffer
          //-------------------
          public:
          char Kamranga;
		  char tabletype; //'K' is for the extended filedname
          char NodeBuf[INDEX_NODE_SIZE];
          INDEXNODEHEADER *NodeHdr;
          INDEXNODEHEADER *TmpNodeHdr;
          char *TmpBuf;
          char *TmpKeyArea;
          char *KeyArea; 
		  class internetsqlobject *obj;
          __NODE(void);
         } INDEXNODE;


typedef struct index_hops
{
  INDEXNODE Node;
  struct index_hops *next;
  struct index_hops *prev;
  int entryindex;
  int status;
  int keyno;
  class internetsqlobject *obj;
} INDEX_HOPS;
//--------------------
//declare index header
//--------------------
typedef struct indexcorehraeder
{
   char  Signature[INDEX_SIGNATURE_SIZE];
   KINT64 PointerToRootNode; //where index starts  
   KINT64 PointerToEof;      //end of file
   KINT64 LeafCount;
   KINT64 LeafCaps;
   KINT64 TotalKey;
   KINT64 KeyCount;
   KINT64  Start;
   KINT64  End;
   INT16   KeyLength;         //width of key value
   char  DelFlag;
   char  Unique;
   char  IndexVersion; //to check if auto indexing is allowed
   char  ForExist;
   char  indexorder;
   char  reserved[3];
   KINT64  FirstLeafOffset;
   char  Key[MAXINDEXKEYCOUNT * NAME_BUF_SIZE];        //the key itself (name of the key)
}INDEX_CORE_HEADER;
typedef struct indexfileheader
{
	INDEX_CORE_HEADER CoreHdr;
    char  ForPtr[INDEX_NODE_SIZE - sizeof(INDEX_CORE_HEADER)];
} INDEX_FILE_HEADER;

typedef class INDEXOBJECT
        {
         public: 
           unsigned char tabletype; //'K' is for the extended filedname
           char FileName[NAME_BUF_SIZE];
		   char IndexDirectory[NAME_BUF_SIZE];
           char UniqueBuffer[INDEX_NODE_SIZE];
           KINT64 FileHandle;
		   char HostIp[24];
		   char HostPort[24];
		   char remote_index;
       
           //-------------------------       
           //declare the header buffer
           //-------------------------
          // char Kamranga;
           //char KamrangaHead[513];
		   INDEX_FILE_HEADER Header;
           KINT64 CurrentKeyCount;  //inside the index file
           char  Direction;
           char  TempKeyBuffer[INDEX_NODE_SIZE];
           KINT64   CurrentKeyNo;   //inside a node
           INDEXNODE  Node;
		   unsigned long FreeNodes;
           INDEXNODEHEADER TmpNodeHeader;
           KEYLIST   kl;
           POSTFIXLINK pl;
           INDEX_HOPS *Hops;
           INDEX_HOPS *CurrentHopPtr;
           char GreaterThanRootElements;
           class TABLEOBJECT *Owner;
           class INDEXOBJECT   *next;
           class INDEXOBJECT   *prev;
           KEYPOINTER FileBuf;
           char BufferMode;
           //HANDLE   FileBufHandle;
           KINT64 FileBufferPtr;
           KINT64 LastLeft;
           char FirstTime;
           class internetsqlobject *obj;
           INDEXDATATYPE DataType;
           INDEXOBJECT(void);
          char OkIndex(char chkeof);
          char GotoRoot(void);
          char *KeyName(void);
          char ReadNode(void);
          char TmpReadNode(void);
          KINT64 GetNextPointer(int lastkey);
          KINT64 GetTmpNextPointer(int lastkey);
          char *GetKeyFromNode(int count);
          long GetLeafStatus(int count);
          int GetKeyInfo(int count, KEY_ENTRY_INFO *ki);
          KINT64 FindKey(char *KeyValue,
                                char *KeyValue2,
                                char range);
         KINT64 FindPartial(char *KeyValue,int matchlen);
		 KINT64 FindNotPartial(char *KeyValue,int matchlen);
         KINT64 FindExact(char *); 
         KINT64 FindNotExact(char *); 
		 KINT64 FindLike(char *); 
         KINT64 FindNotLike(char *);
         KINT64 FindLessThan(char *); 
         KINT64 FindLessOrEqual(char *); 
         KINT64 FindGreaterThan(char *); 
         KINT64 FindGreaterThanOrEqual(char *); 
         KINT64 FindNotWithin(char *, char *); 
         KINT64 FindWithin(char *,char *); 
         KINT64 FindUnique(char *fieldname); 
         KINT64 FindCount(char *fieldname); 
         KINT64 GoTo(KINT64 recno);
         KINT64 Previous();
         KINT64 Next();
         KINT64 Skip(KINT64 count);
         char LoadLeaf(KINT64 leafno);
         char Delete();
         unsigned char LeafType(void); 
         unsigned char DirType(void); 
         unsigned char RootType(void); 
         char AutoIndexType(void); 

         KINT64 GetCurrentKeyCount(int keyno);
		 KINT64 GoToFirstLeaf(void);
         KINT64 FindExactForAutoInsert(char *keyvalue);
         INDEX_HOPS  *AddHop(void);
         void FreeHops(void);
         //HANDLE ThisHandle; 
       	 
           void  *operator new(size_t amount);
       
         char AllocFileBuf( KINT64 size);
         char DeAllocFileBuf(void);
        } *INDEX;


typedef struct __group__{
                 //HANDLE handle;
                 struct __group__ *next;
                 struct __group__ *newgroup;
                 char *field;
                 char ok;
               } *FIELDGROUP;
//----------------------------------
//----------------------------------
//----------------------------------
//----------------------------------
//----------------------------------
//holds the real data record from the 
//dbf file
//also this class is used to search 
//data by filling up the required 
//fields
//------------------------------------

typedef class RECORDOBJECT
      {
       public:
           //---------------------------------
           //SQL variables
           //---------------------------------
 		   char SelectFlag;
		   long flags;
           long sqlqrytype; //field or expression qry
           long token;
           class SQL_SelItems *SelItem;
           class RECORDOBJECT *SqlField;
           class RECORDOBJECT *GroupByMap;
           class SQL_SelItems *Si;
           char ForGroupByOnly;
           char Alias[64];
		   char ScratchPad[128];
           KDOUBLE number;
           //---------------------------------
           char tabletype; //'K' is for the extended filedname
		   int FieldNameLen;
           char Kamranga;
           char  VarType;
           class TABLEOBJECT *Table;  //name of field
           char FieldPrefix[NAME_BUF_SIZE];  //name of field
           char Fieldname[NAME_BUF_SIZE];  //name of field
           long  FieldWidth;     //length of field never change it
           long  ModifiedWidth;  //modify length for import needs
           char FieldType;      //type of field
		   char notnull;
		   char keytype;
		   char has_reference_table;
		   char autoinc;
		   char unique;
		   KINT64 incval;
		   char defaultvalue[256];
		   short int enumcount;
		   char extra[EXTRA_FIELD_STRUCT_BUF_SIZE];
           char parentdir[256];
		   char reference_table_name[256];  
		   char international_language;
		   long max_field_byte_used;
           char DecimalPos;     //decimal position if numeric
           long Displacement;   //position of the field in the record
           long FieldPos;      
           long  Selected;       //select requested when >0
           char Deleted;
           char RollBacked;
           KINT64 RecordNo;
           long RecordLength;
           class internetsqlobject *obj;
           //HANDLE DataHandle; 
           char * Data;          //field data
           //HANDLE ThisHandle; 
           class RECORDOBJECT *Map;
           class RECORDOBJECT *next,*prev;
       	 
           void  *operator new(size_t amount);
        
           RECORDOBJECT(void);
           char ClearData(  void );
           char AllocData(  void );
        
          
      } *RECORDLIST,RECORDINFO,*QUERYITEMSLIST,*QUERYROW, *CURSORROW,*CURSORFIELD;   
       
//----------------------------------------
#define SELECT_FLAG_FINAL_SELECT 0x00
#define SELECT_FLAG_FUNCTION_ARG 0x01

   
//----------------------------------------
//----------------------------------------
typedef class LISTOBJECT
        {
         public:
          char tabletype; //'K' is for the extended filedname
          char ListBuf[LISTBUFSIZE];
          UINT16  *Count;  //can hold LISTBUFFER_RECORD_CAPACITY records
          KINT64 *BufferNo;
          KINT64  ListHandle;
          KINT64 TotalList;
          KINT64 CurrentList;
          KINT64 PickCount;
          char delstatus;
          class TABLEOBJECT *Owner;
          class KEYOBJECT *KeyList;
          RECORDOBJECT *ListRec;
          POSTFIXLINK Pf;
		  class internetsqlobject *obj;
          //HANDLE ThisHandle;
          class LISTOBJECT *next;
          class LISTOBJECT *prev;
          LISTOBJECT (void);
          KINT64 GoTo(KINT64);
          KINT64 Next(void);
          KINT64 Previous(void);
          KINT64 Bottom(void);
          KINT64 Top(void);
       	
           void  *operator new(size_t amount);
       
        } *LISTINFO;

//--------------------------------------
typedef class LOGOBJECT
{
   public:
   KINT64 id;
   //HANDLE ThisHandle;
   class LOGOBJECT *next;
   class LOGOBJECT *prev;
   class internetsqlobject *obj;   
   void  *operator new(size_t amount);
} *LOGINFO;

typedef struct 
{
  char tablename[NAME_BUF_SIZE];
  char tabletype[4];
  char dropped[4];
  char owner[68];
  char group[68];
  char createdate[12];
  char createtime[12];
  char version[20];
  char groupname[68];
  char groupread[4];
  char groupwrite[4];
  char groupalter[4];
  char grouplock[4];
  char groupdrop[4];
  char grouprevoke[4];

  char allread[4];
  char allwrite[4];
  char allalter[4];
  char alllock[4];
  char alldrop[4];
  char allrevoke[4];

  KINT64 recno;
} TABLE_INFO;
int ValidTablePermission(char *);
int SetTableInfo(char *infoname,char *infoval,TABLE_INFO *tinfo);
int SetTableInfoInSysTable(class internetsqlobject *obj,KINT64 recno,TABLE_INFO *tblinfo);
int CheckTableSetAuthorization(class internetsqlobject *obj,TABLE_INFO *tblinfo);
#if 0
//---------------------------------------
typedef struct KMG_TableHeader
{
  char    A;      
  char    B[3];   
  KINT64    C;      
  UINT16  D;      
  UINT16  E;      
  char    F[20];  
} KAMRANGA_TABLE_HEADER;
#endif
//---------------------------------------
typedef class TABLEOBJECT
      {
       public:
		//KAMRANGA_TABLE_HEADER KmgTableHeader;
        //KAM_TABLE_HEADER_STRUCT
        TABLE_HEADER Header;
        TABLE_HEADER TmpHeader;
        int dump_table;
		int HaveMutex;

        //char tabletype; //'K' is for the extended filedname
		int FieldNameLen;
        int Instance;
        char FileName[NAME_BUF_SIZE];
		char TableDirectory[NAME_BUF_SIZE];
		char HostName[NAME_BUF_SIZE];
		char HostIp[24];
		char HostPort[24];
		class internetsqlobject *obj;
		int socket;
	    int remote_sql_error;
		int exclusive_open;
		char for_primary_or_foreign_key_create_only;
		char AutoIndexMgMt;
        KAM_MUTEX *mutex;
        struct _lockinfo_     *lockinfo;
        TABLE_INFO            *systableinfo; 

#ifndef SUNUNIX
		SOCKADDR_IN ServerAddr;
        SOCKADDR_IN ClientAddr;
#else
        struct  sockaddr_in  ServerAddr;
        struct  sockaddr_in  ClientAddr;
#endif
        KINT64  FileHandle;
		char littleendian;
		char remote_table;

        //int  ScratchPadHandle;
        //unsigned int PadSize;
        //char PadHeader[33];
        //char LockBuffer[17];

        KINT64 FileSize;
        char *HeaderTop;
        //char TableType;
        char *FileType;
        char *Update;

        char Terminator;
        char          Modified;
        INT16       FieldCount;
        char TransactionTable;
		struct _storage_file_info_ *Storage;
		char HasStorageField;
		char HasDirField;
        FIELDOBJECT *Fields;
        RECORDOBJECT *RecordInfo;
        LISTINFO ListInfo;
        INDEX      Index;
        KINT64      CurrentRecord;
        KINT64      AbsoluteRecordNo;
        KINT64      FilePos;
        char AutoIndexUpdate;
        char AutoReindex;
        char *      data;
        //char *      RecBuf;
		char RecBuf[TABLE_RECORD_CACHE_SIZE];
        char     BufferMode;
        KINT64 first;
        KINT64 last; 
        class TABLEOBJECT *next;
        class TABLEOBJECT *prev;
        KINT64  LockFrom;
        KINT64  LockLen;
        char Locked;
		RELATION_TABLE *relations;
		TRIGGER_TABLE  *triggers;
        INDEXPROC IndexProc;
        LISTPROC ListProc;
        TABLEOBJECT(void);
       
         void  *operator new(size_t amount);
      
        char AllocData(void);
        char DeAllocDbf(void );
        char DeAllocData(void );
        char DeleteId(KINT64 id);
        KINT64  GetRecordCount(void);
        KINT64  GetRecordCount(INDEX ndx);
		KINT64  RemoteGetRecordCount(void);
        KINT64  RemoteGetRecordCount(INDEX ndx);

        KINT64  GetRecordCount(LISTINFO);
        KINT64  GetCurrentTotal(void);
        char AutoIndexUpdateOn(void);
        char AutoIndexUpdateOff(void);
        char AutoReindexOn(void);
        char AutoReindexOff(void);
        char Changed(void);
        char CheckFormat(void);
        char SetFormat(void);
       int DeleteTable();
       char *ReadRec(KINT64 recno,char percent);
       KINT64  GetListNumber(LISTINFO lst);
       KINT64  GetKeyNumber(INDEX ndx);
       char AllocRecBuf(void);
       char DeAllocRecBuf(void);
       KINT64 GetTableHeaderInfo(void);
       char AddRecordNoUpdateHeader( RECORDLIST Rec);             //Adds record
       char UpdateDbfFile(void);
       char AddEndMark(void);
       char FixFieldDisplacement(void);
       KINT64 SkipRecordCount(KINT64 count);
       INDEX AddIndex(INDEX);
       INDEX Reindex(INDEX *);
       INDEX IndexCommand(char *indexstr);
       LISTINFO ListCommand(char *liststr);
       char DeleteCommand(char *deletestr);
       char UnDeleteCommand(char *undeletestr);
       char Replace(char *fieldname,char *value);
       char ReplaceBuffered(char *fieldname,char *value,KINT64 from ,KINT64 to);
       char DeleteBuffered(KINT64 from,KINT64 to);
       char UnDeleteBuffered(KINT64 from,KINT64 to);
       char  RemoveIndex(char *name);
       INDEX FindIndex(char *name);
       RECORDOBJECT *Top(INDEX ndx);
       RECORDOBJECT *Top(LISTINFO);
       RECORDOBJECT *Top(void);
       char MakeIndexProc(INDEXPROC);
       void FreeIndexProc(void);
       char MakeListProc(INDEXPROC);
       void FreeListProc(void);
       char  ResetRecordCount(void);
       FIELDOBJECT *InsertField( char *field, KINT64 *lengthchk );
       RECORDOBJECT * CreateEmptyRecord(void);  //creates an
                                          //empty record
       int  SetMark(KINT64 recno, int mark);
       int  ClearMark(KINT64 recno,int mark);
       int  GetFieldsCount(void);
       char GotoAbsDataEndPos(void);
       char GetFieldInfo(void);              //reads dbf file
       char ScratchBuffer(void);
       char CreateScratchBuffer(void);
       void ShowFieldList(void);             //shows full field
                                          //definitions in the
                                          //database
                              //return null on failure


       char DeleteRecord(void           //deletes       
                  );                   //data 

       char AddRecord(              //Adds record
                   RECORDOBJECT *Recinfo //in the 
                  );                   //data base

       char AddRecordNoTrim(              //Adds record
                   RECORDOBJECT *Recinfo //in the 
                  );                   //data base

       char Add(              //Adds record
                   RECORDOBJECT *Recinfo //in the 
                  );                   //data base

       char AddIgnoreOwner(              //Adds record
                   RECORDOBJECT *Recinfo, //in the 
                   char matchingfieldsonly
                  );                   //data base
       RECORDOBJECT *ReadRecordFullBuffer(KINT64);
       RECORDOBJECT *RemoteReadRecordFullBuffer(KINT64);

       char FoxBaseNoMemo(void);
       char FoxBaseMemo(void);
       char FoxProMemo(void);
       char FoxProNoMemo(void);
       char DbaseIIINoMemo(void);
       char DbaseIIIMemo(void);
       char DbaseIVMemo(void);
       char DbaseIVNoMemo(void);
       char MemoFileType(void);
       char NoMemoFileType(void);
       char DbfFileTypes(void);
       char Save(              //save changes
                  RECORDOBJECT *Recinfo //record in the 
                );                   //data base

	   char Save(              
                  char *data
                );      
       char CheckDbf(KINT64 handle);
       KINT64 GotoRecordNoTranslation(KINT64 recordno);         //go to particular


      char *GetRecord(void);            //reads one record
                                            //and updates recno
                                            //file pointer

      KINT64 GetRecordNumber(void);       //get current record no.
      KINT64 GetRecordNumber(INDEX);       //get current record no.
      KINT64 GetRecordNumber(LISTINFO);       //get current record no.

      char Eof(void);
      char UnDelete(void);
      char Deleted(void);
      char UnDeleteAll(void);
      char DeleteAll(void);
      char *ReadForIndexBoth(KINT64 recno);
      char *ReadForIndexDeleted(KINT64 recno);
      char *ReadForIndex(KINT64 recno);
      char  DeleteIndex(char *name);
      RECORDOBJECT *TopEx(INDEX ndx);
      RECORDOBJECT *TopEx(LISTINFO);
      RECORDOBJECT *BottomEx(INDEX ndx);
      RECORDOBJECT *BottomEx(LISTINFO);
      RECORDOBJECT *Bottom(void);

      RECORDOBJECT *TopEx(void);
      RECORDOBJECT *BottomEx(void);
      
      RECORDOBJECT * DescendNext(INDEX ndx);
      RECORDOBJECT * DescendPrevious(INDEX ndx);
      RECORDOBJECT * DescendTop(INDEX ndx);
      RECORDOBJECT * DescendBottom(INDEX ndx);

      RECORDOBJECT * DescendNextEx(INDEX ndx);
      RECORDOBJECT * DescendPreviousEx(INDEX ndx);
      RECORDOBJECT * DescendTopEx(INDEX ndx);
      RECORDOBJECT * DescendBottomEx(INDEX ndx);

      KINT64 GotoRecord(KINT64 recordno);         //go to particular
      RECORDOBJECT * GoTo(KINT64 recordno);         //go to particular
      RECORDOBJECT * GoTo(INDEX,KINT64 recordno);         //go to particular
      RECORDOBJECT * GoTo(LISTINFO,KINT64 recordno);         //go to particular
      RECORDOBJECT * GoToEx(KINT64 recordno);         //go to particular
      RECORDOBJECT * GoToEx(INDEX,KINT64 recordno);         //go to particular
      RECORDOBJECT * GoToEx(LISTINFO,KINT64 recordno);         //go to particular
	  INDEX CreateAutoIndex(KEYLIST *k);

     char GoIndexTop(INDEX ndx);
     RECORDOBJECT * GoTop(void);
     char GoDbfBottom(void);
     RECORDOBJECT * GoBottom(void);
     char SqlAddNoRollBack(void *);
     char SqlSaveNoRollBack(void *);
     char SqlSaveNoRollBack(void);
                                    //record number
     char SetField(char *fieldname,char *value);
     char SetField(int fieldno,char *value);
     char Add(void);
      char GotoAbsDataPos(void);
      RECORDOBJECT *GetDbRecord(void);    //always shows
      RECORDOBJECT * GetSequentialDbRecord(void);     //always shows
      char GetAbsSequentialDbRecordNoTranslation(void);     //always shows
      RECORDOBJECT * Next(void);
      RECORDOBJECT * Next(INDEX);
      RECORDOBJECT * Next(LISTINFO);
      RECORDOBJECT * Previous(INDEX);
      RECORDOBJECT * Previous(LISTINFO);

      RECORDOBJECT * NextEx(void);
      RECORDOBJECT * NextEx(INDEX);
      RECORDOBJECT * NextEx(LISTINFO);
      RECORDOBJECT * PreviousEx(INDEX);
      RECORDOBJECT * PreviousEx(LISTINFO);
      RECORDOBJECT * PreviousEx(void);

      char Delete(void);
      char Delete(INDEX);

      RECORDOBJECT * TopDel(INDEX ndx);
      RECORDOBJECT * TopDel(LISTINFO);
      RECORDOBJECT * BottomDel(INDEX ndx);
      RECORDOBJECT * BottomDel(LISTINFO);
      RECORDOBJECT * TopDel(void);
      RECORDOBJECT * BottomDel(void);
      RECORDOBJECT * GoToDel(KINT64 recordno);
      RECORDOBJECT * GoToDel(INDEX ndx,KINT64 recordno);         //go to particular
      RECORDOBJECT * GoToDel(LISTINFO ,KINT64 recordno);         //go to particular
      RECORDOBJECT * DescendNextDel(INDEX ndx) ;
      RECORDOBJECT * DescendPreviousDel(INDEX ndx);
      RECORDOBJECT * DescendTopDel(INDEX ndx)      ;
      RECORDOBJECT * DescendBottomDel(INDEX ndx)    ;
      RECORDOBJECT * NextDel(void)                   ;
      RECORDOBJECT * NextDel(INDEX ndx)            ;
      RECORDOBJECT * NextDel(LISTINFO)            ;
      RECORDOBJECT * PreviousDel(INDEX ndx)       ;
      RECORDOBJECT * PreviousDel(LISTINFO)       ;
      RECORDOBJECT * PreviousDel(void)           ;
      RECORDOBJECT *GetDelRecord(KINT64 recordno);
      INDEX GetIndexObject(int count);
      char EmptyIndex(char *name);
      char EmptyIndex(INDEX);
      char *GetField(int fieldno);
      KINT64 GetFieldSerial(char *field);
      RECORDOBJECT * AbsNext(void);     //always shows
      RECORDOBJECT * Skip(KINT64 count);
      char  NextNoTranslation(void);
      char  AbsNextNoTranslation(void);     //always shows
      char SaveSequentialRecordNoTranslation(void);     //always shows
      char SetSequentialFieldNoTranslation(FIELDOBJECT *ff,char *value);     //always shows
      char  ShowRecordNoTranslation(void);     //always shows
      char * GetSequentialFieldNoTranslation(FIELDOBJECT *ff);     //always shows
      char GetSequentialDbRecordNoTranslation(void);     //always shows
      RECORDOBJECT *GetAbsRecord(KINT64 recno);    //get undeleted and
                                          //deleted records
      RECORDOBJECT *RemoteGetAbsRecord(KINT64 recno);    //get undeleted and deleted records
                                          

      char MakeRecordInfo(void);
      RECORDOBJECT *GetCurrentDbRecord(void);     //always shows
                                     //current record
      KINT64 GetFileSize(void);
      char Zap(void);
      char CloseTable(void);
      char CloseTableEx(void);
      char CloseTable(KINT64 id );
      INDEX RemoteOpenIndex(char *FileName);  //opens index 

      INDEX OpenIndex(char *FileName);  //opens index 
      INDEX OpenIndexEx(char *FileName);  //opens index 
      char CloseIndex(INDEX *ndx);      //closes index
      char CloseAllIndex(void);
      char  ReadNode(int fieldwidth,KINT64 handle, KINT64 ptr);
	  int SwapRecord(KINT64 first,KINT64 second);
	  int MoveRecord(KINT64 from,KINT64 to);
      FIELDLIST GetFieldList(void);
      RECORDOBJECT *GetRecordList(void);
     
      RECORDOBJECT * GetIndexedRecord(KINT64 recno); //reads a absolute record
                                                          //returns null if marked

	  RECORDOBJECT * SeekDistinct(INDEX , char *fieldname); //reads a absolute record
      RECORDOBJECT * SeekNotEqual(    //searches for
                         INDEX index,
                         char  *value       //record in the 
                        );                   //data base
                                                          //deleted
      RECORDOBJECT * Seek(    //searches for
                         INDEX index,
                         char  *value       //record in the 
                        );                   //index for this value
      
      KINT64 SeekCount(INDEX,char *data);    //searches for
      RECORDOBJECT * SeekPartial(    //searches for
                         INDEX index,
                         char  *value,
                         int part       //record in the 
                        );                   //index for this value
	  RECORDOBJECT * SeekNotPartial(    //searches for
                         INDEX index,
                         char  *value,
                         int part       //record in the 
                        );                   //index for this value
      RECORDOBJECT * SeekLess(    //searches for
                         INDEX index,
                                char  *value       //record in the index
                              );                   //all less than this value

      RECORDOBJECT * SeekLessOrEqual(    //searches for
                         INDEX index,
                                char  *value       //record in the index
                              );                   //all less than this value

      RECORDOBJECT * SeekGreater(    //searches for
                         INDEX index,
                         char  *value              //record in the index
                        );                         //all greater than 
                                                   //this value

      RECORDOBJECT * SeekGreaterOrEqual(    //searches for
                         INDEX index,
                         char  *value              //record in the index
                        );                         //all greater than 
                                                   //this value

      RECORDOBJECT * SeekWithin(      //searches for
                         INDEX index,
                         char  *value1,            //record in the index
                         char  *value2             //record in the index
                        );                         //all within value1
                                                   //and value2 
      RECORDOBJECT * SeekNotWithin(      //searches for
                         INDEX index,
                         char  *value1,            //record in the index
                         char  *value2             //record in the index
                        );                         //all within value1
                                                   //and value2
	  RECORDOBJECT * SeekLike(      
                         INDEX index,
                         char  *pattern            
                                      
                        );  
	  RECORDOBJECT * SeekNotLike(      
                         INDEX index,
                         char  *pattern            
                                      
                        );            
                                                   
	  //----------------------------------------------
	  RECORDOBJECT * SQLSeekDistinct(class FromTable *ft, char * fieldname); //reads a absolute record
      RECORDOBJECT * SQLSeekNotEqual(   
                         class FromTable *ft,
                         char  *value);  
                                                          
      RECORDOBJECT * SQLSeek(    
                         class FromTable *ft,
                         char  *value);    
      
      KINT64 SQLSeekCount(class FromTable *ft, char *data); 
	  
      RECORDOBJECT * SQLSeekPartial(   
                         class FromTable *ft,
                         char  *value,
                         int part);
	  RECORDOBJECT * SQLSeekNotPartial(   
                         class FromTable *ft,
                         char  *value,
                         int part);
	  
      RECORDOBJECT * SQLSeekLess(    
                                 class FromTable *ft,
                                 char  *value);  

      RECORDOBJECT * SQLSeekLessOrEqual(   
                         class FromTable *ft,
                         char  *value);
      RECORDOBJECT * SQLSeekGreater(   
                         class FromTable *ft,
                         char  *value);         
                                                   

      RECORDOBJECT * SQLSeekGreaterOrEqual(   
                         class FromTable *ft,
                         char  *value);           
                                                   

      RECORDOBJECT * SQLSeekWithin(      
                         class FromTable *ft,
                         char  *value1,           
                         char  *value2);          
                                                   
      RECORDOBJECT * SQLSeekNotWithin(      
                          class FromTable *ft,
                         char  *value1,           
                         char  *value2);         
      RECORDOBJECT * SQLSeekLike(      
                         class FromTable *ft,
                         char  *pattern            
                                      
                        );  
	  RECORDOBJECT * SQLSeekNotLike(      
                         class FromTable *ft,
                         char  *pattern            
                                      
                        );                                                         
      //-----------------------------------------------------------------------
      char  SeekToFile(    //searches for
                         INDEX index,
                         char  *value,       //record in the 
                         char *file
                         );                   //data base
      char  SeekLessToFile(    //searches for
                         INDEX index,
             char  *value,       //record in the index
             char  *file
           );                   //all less than this value
      char  SeekGreaterToFile(    //searches for
                         INDEX index,
                          char  *value,       //record in the index
                          char  *file
                        );                   //all less than this value
     char SeekWithinToFile(      //searches for
                         INDEX index,
                   char  *value1,            //record in the index
                   char  *value2,             
                   char *file);

      void ShowRecordList(void);
      INDEX GoIndexTopAuto(char *key);
      //-----------------------------------------------------------------------
       KINT64 FindExact(INDEX ,char *); 
       KINT64 FindNotExact(INDEX, char *); 
       KINT64 FindLessThan(INDEX, char *); 
       KINT64 FindLessOrEqual(INDEX ,char *); 
       KINT64 FindGreater(INDEX, char *); 
       KINT64 FindGreaterOrEqual(INDEX, char *); 
       KINT64 FindNotWithin(INDEX, char *, char *); 
       KINT64 FindWithin(INDEX, char *,char *); 
       INDEX FindKey(char *name);
      //-----------------------------------------------------------------------
      char  DeleteField(char *fieldname); //removes a field in existing 
                                          //table
       char  AddField( char *fieldname,  //adds or redefines a field
                                       //in a existing table
                        int fieldwidth,       
                        char fieldtype,
                        char decimalpoint,
						char notnull,
						char keytype,
						char autoinc,
						char unique
                       );
      FIELDOBJECT *SearchDefn(char *name);  //search for a field name
                                          //name in the field list
      int GetFieldLength(char *field);
      char GetFieldType(char *field);
      char GetDecimalPos(char *field);
      char GetFieldDecimalPos(char *field);
      char *GetFieldName(int serial);
	  char GetNotNull(char *field);
	  char GetKeyType(char *field);
	  char GetAutoInc(char *field);
	  char GetUnique(char *field);

	  KINT64 GetIncval(char *field);
	  char *GetDefaultValue(char *field);
	  char *GetParentDir(char *field);
	  char *GetEnum(char *field);
	  int GetEnumCount(char *field);
	  unsigned short int  GetMaxBytesUsed(char *field);

      FIELDLIST GetFieldList(int serial);
      int GetFieldLength(int serial);
      char GetFieldType (int serial);
      char GetDecimalPos(int serial);
	  char GetNotNull(int serial);
	  char GetKeyType(int serial);
	  char GetAutoInc(int serial);
	  char GetUnique(int serial);
	  char GetInternationalLanguage(int serial);
	  KINT64 GetIncval(int serial);
	  char *GetDefaultValue(int serial);
	  char *GetParentDir(int serial);
	  char *GetEnum(int serial);
	  int GetEnumCount(int serial);
	  long  GetMaxBytesUsed(int serial);

	  char GetFieldDecimalPos(int serial);
      
      UINT16 GetRecordLength(void);
      KINT64 GetRecordFilePos(KINT64 recno);

      char WriteAllFields(char ZAPFLAG);          //writes field defns to the 
                                          //dbf header

      char * GetField(FIELDOBJECT *ff,KINT64 recno);
      char * GetDelField(FIELDOBJECT *ff,KINT64 recno);
      char * GetBothField(FIELDOBJECT *ff,KINT64 recno);
      char * GetField(char *fieldname);
      char AddRecordNoUpdateHeader(              //Adds record
                        RECORDOBJECT *Rec, //in the 
                        int ingnoreowner
                        );
          char ModifyTable(void);
          FIELDOBJECT *ModifyFieldDefn( 
                          char *fieldname,
                          int fieldlength,
                          char fieldtype,
                          char decimalpoint,
						   char notnull,
						   char keytype, 
						   char autoinc,
						   char unique
                          );
      FIELDOBJECT *InsertFieldToNewTable(   //insert fields to a newly created 
                                          //table
                          char *fieldname,
                          int fieldlength,
                          char fieldtype,
                          char decimalpoint,
						  char notnull,
						   char keytype,
						   char autoinc,
						   char unique
		
                          );
      char CloseListInfo(void);
      char *GetRecordString(void);
      char *ReadRecordString(KINT64 recno);
      char *RemoteReadRecordString(KINT64 recno);
      KINT64 GetLastIncValue(void);
      char DoIndex(char *KeyName,
                   char *Filename,
                   char uniqflg,
                   RECORDOBJECT *condition,
                   char notdeleted 
                  );
      char RegainDbf(void);
      char AppendBlank(void);
      char * GetAbsField(FIELDOBJECT *ff,KINT64 recno);
      char * GetIndexedField(FIELDOBJECT *ff,KINT64 recno);
      //char (*ShowIndex)(KINT64 i,HDC hdc);
      char AddRecordNoTranslation(char *rec);
      char AddRecordNoTranslationNoUpdate(char *rec);
      char *GetAbsRecordNoTranslation(KINT64 recno);
      char *GetIndexedRecordNoTranslation(KINT64 recno);
     RECORDOBJECT *Previous(void);
     char Clear(void);
     char Blank(void);
     char Save(void);
     char SaveRecStringAsIs(char *);
     char SaveIgnoreOwner(RECORDLIST, char matchingfieldsonly);
     RECORDOBJECT *Bottom(INDEX);
     RECORDOBJECT *Bottom(LISTINFO);
    char CreateIndexEvalStack(
                      KEYLIST *kl,   //pointer to keys
                      KINT64 start,
                      KINT64 end,
                      char *Filename,  //name of the index file
                      POSTFIXLINK *pl,
                      char notdeleted ,//undeleted only or not
                      char unique,
                      char *forstring
                      ); 
    KINT64 ReCreateIndexEvalStack(INDEX *);

    KINT64 CreateIndexEvalStack2(
                      KEYLIST *kl,   //pointer to keys
                      KINT64 start,
                      KINT64 end,
                      char *Filename,  //name of the index file
                      POSTFIXLINK *pl,
                      char notdeleted ,//undeleted only or not
                      char unique,
                      char *forstring,
					  char for_primary_or_foreign_key_create_only
                      ); 

    KINT64 RollBack(KINT64 recno);
    char *GetTableName(void);

    char LockTable(KINT64 trialtime);
    char LockRecord(KINT64 trialtime);

    char LockGroup(KINT64 fron,KINT64 count,KINT64 trialtime);
    char LockGroup(KINT64 from,KINT64 count);

    char LockAppend(KINT64 trialtime);
    char LockAppend(void);

    char LockTable(void);
    char LockRecord(void);

    char UnLock(void);
    char ShowLockInfo(void);
    char Pack(void);
    char ModifyTable(FIELDLIST fld);
    char ModifyTable(RECORDLIST rec);
    char Select(char *fieldname);
    
     KINT64 ResetAndSearchField(char *fieldname,char *value);
     //char Satisfied(char *fieldname);
     char SortOn(char *field);
     KINT64 CountCommand(char *commandstr);
     char UpdateField(void);
     FIELDOBJECT * InsertSqlQryField( 
                          char *fieldname,
                          int fieldlength,
                          char fieldtype,
                          char decimalpoint,
						  char notnull,
						  char keytype,
						  char autoinc,
						  char unique
                          );
      FIELDOBJECT * InsertField( 
                          char *fieldname,
                          int fieldlength,
                          char fieldtype,
                          char decimalpoint,
						  char notnull,
						  char keytype,
						  char autoinc,
						  char unique
						  );
      char AddRecordString(char *str);
      char AddRecordString(void);
      char *CopyField(char *src,char *fieldname);
      char *CopyRecordString(char *dst);
      char *GetRecordBuffer(void);
      char *GetFieldBuffer(char *field);
      RECORDOBJECT *PickFromList(LISTINFO);
      char LookAheadOff(void);
      char LookAheadOn(void);
      char AddKey(INDEX *ndx,KINT64 recno);
      char DeleteKey(INDEX *ndx,KINT64 recno);

      char DeleteKeyEx(INDEX *ndx,KINT64 keyno);
      char RemoveRecordFromIndex(INDEX *ndx,KINT64 recno);
      char DeleteCurrentKey(INDEX *ndx);
      char DeleteKeyIndexAuto(INDEX *ndx,KINT64 recno);
      char AddKeyIndexAuto(INDEX *ndx,KINT64 recno);

      char ExamineKey(INDEX *ndx,KINT64 recno);
      LISTINFO SortListToFile(KEYLIST kl,
                              POSTFIXLINK pl,
                              char unique,
                              KINT64 start,
                              KINT64 end,
                              char *forstring,
                              char *listfile);
      LISTINFO SortListToBuffer(KEYLIST kl,
                              POSTFIXLINK pl,
                              char unique,
                              KINT64 start,
                              KINT64 end,
                              char *forstring,
                              char *listfile);
     char   CompareFields(char *table);
     char   CompareFields(class TABLEOBJECT * tbl);
     LISTINFO GetListInfo(void);
     char CopyTable(char *copyname);
     char KamrangaExtendedTable(void);
     KDOUBLE SumCommand(class internetsqlobject *obj,char *command,char *retcode);
     KDOUBLE AvgCommand(class internetsqlobject *obj,char *command,char *retcode);
     KDOUBLE MinCommand(class internetsqlobject *obj,char *command,char *retcode);
     KDOUBLE MaxCommand(class internetsqlobject *obj,char *command,char *retcode);
     int RepairTable(KINT64 handle , KINT64 filesize);
     int CreateBackUp(char *filename,KINT64 *handle);
     KINT64 KamrangaRecordLength(void);
     int UpdateFieldInfo(void);
     char *ReferenceTableName(int serial);
	 int ForeignKeyFlag(int serial);

     }*DATABASE,*TABLE,*QUERYRESULTTABLE; 
	 //------------------------------------------------------
#define STORAGE_TITLE_LEN 220    

typedef struct _storage_field_info_
	{
		int status;
	    char fieldname[NAME_BUF_SIZE];
	    char fieldvalue[NAME_BUF_SIZE];

		KINT64 HeaderPointer;
		KINT64 LastBlockPointer;
		KINT64 CurrentBlockOffset;
		KINT64 CurrentBlockPointer;
		KINT64 DataSize;
		KINT64 selfoffset;
		KINT64 next;
		KINT64 prev;
		
	}STORAGE_FIELD_INFO;
#define STORAGE_FIELD_INFO_FREED      0x01
#define STORAGE_FIELD_INFO_DELETED    0x02
#define STORAGE_FIELD_INFO_ROLLBACKED 0x03

#define STORAGE_BLOCK_POINTER 8 //bytes to represent file node pointer
                                //in the table.str file
#define STORAGE_RECORD_NUMBER 8 //
#define STORAGE_FIELD_LEN 255

#define STORAGE_BLOCK_FREED      0x01
#define STORAGE_BLOCK_DELETED    0x02
#define STORAGE_BLOCK_ROLLBACKED 0x03
#define STORAGE_BLOCK_SIZE       1024*4

#define STORAGE_WRITE			0x01
#define STORAGE_APPEND			0x02
#define STORAGE_TRUNC			0x04
#define STORAGE_CLOSE			0x08
#define STORAGE_WRITE_FROM_CURRENT_PTR		0x10

#define FIRST_STORAGE_BLOCK 0L
typedef struct _storage_block_header_
{
	
	int status;
	int  data_count;
	KINT64 blockno;
	KINT64 selfoffset;
    KINT64 next;
	KINT64 prev;
	int reserved[2];
    
} STORAGE_BLOCK_HEADER;

typedef struct _storage_header_
{
	char Signature[16];
	char OwnerTableName[NAME_BUF_SIZE];
	char LastUpdateDate[8];
    KINT64 storage_file_size;
	KINT64 storage_block_buffer_size;
	STORAGE_BLOCK_HEADER free_block_head;
	STORAGE_BLOCK_HEADER free_block_tail;
	STORAGE_BLOCK_HEADER used_block_head;
	STORAGE_BLOCK_HEADER used_block_tail;
	STORAGE_FIELD_INFO   free_fieldinfo_head;
	STORAGE_FIELD_INFO   free_fieldinfo_tail;
	STORAGE_FIELD_INFO   used_fieldinfo_head;
	STORAGE_FIELD_INFO   used_fieldinfo_tail;

} STORAGE_HEADER;


#define STORAGE_BUFFER_CAPACITY (STORAGE_BLOCK_SIZE-sizeof(STORAGE_BLOCK_HEADER))
typedef struct _storage_block_
{
 STORAGE_BLOCK_HEADER sbheader;
 char buffer[STORAGE_BUFFER_CAPACITY];
} STORAGE_BLOCK;

typedef struct _storage_file_info_
{
	char FileName[NAME_BUF_SIZE];
	KINT64  FileHandle;
    TABLE ParentTable; 
	STORAGE_HEADER Header;
	STORAGE_BLOCK CurrentBlock;
	KINT64 CurrentBlockOffset;
	STORAGE_FIELD_INFO   CurrentField;
	KINT64 CurrentFieldOffset;
} STORAGE_FILE;
STORAGE_FILE *CreateStorageFile(class internetsqlobject *obj,TABLE tbl);
STORAGE_FILE *OpenStorageFile(class internetsqlobject *obj,TABLE tbl);
void CloseStorageFile(class internetsqlobject *obj,STORAGE_FILE *sf);
KINT64 SaveStorageData(class internetsqlobject *obj,STORAGE_FILE *sf,
				   KINT64 buffer_offset,
				   char *buffer, 
				   KINT64 size, 
				   char flag);
int CreateStorageFieldInfoEntry(TABLE tbl,char *fieldname,char *fieldvalue,STORAGE_FIELD_INFO *sfi);
int UpdateStorageFieldInfo(STORAGE_FILE *sf,STORAGE_FIELD_INFO *sfi,long offset);

KINT64 CreateNewStorageBlock(class internetsqlobject *obj,STORAGE_FILE *sf,STORAGE_BLOCK_HEADER *sbh);
KINT64 GetStorageHeaderPointer(RECORDLIST rec, char *fieldname);
KINT64 GetStorageRecordNumber(RECORDLIST rec,char *fieldname);
KINT64 GetStorageHeaderPointer(RECORDLIST rec, int fieldno);
KINT64 GetStorageRecordNumber(RECORDLIST rec,int fieldno);

KINT64 SetStorageHeaderPointer(RECORDLIST rec, char *fieldname,KINT64 pointer);
KINT64 SetStorageRecordNumber(RECORDLIST rec,char *fieldname,KINT64 number);
KINT64 SetStorageHeaderPointer(RECORDLIST rec, int fieldno,KINT64 pointer);
KINT64 SetStorageRecordNumber(RECORDLIST rec,int fieldno,KINT64 number);
KINT64 FindFreeStorageBlock(STORAGE_FILE *);
KINT64 UpdateStorageHeader(STORAGE_FILE *sf);
KINT64 ReadBlock(STORAGE_FILE *sf,KINT64 offset);
KINT64 GetStorageFieldInfo(TABLE tbl, char *fieldname, char *fieldvalue,STORAGE_FIELD_INFO *sfi);
KINT64 GetStorageHeaderPointer(RECORDLIST rec, char *fieldname);
KINT64 GetStorageLastBlockPointer(RECORDLIST rec, char *fieldname);
KINT64 GetStorageCurrentReadOffset(RECORDLIST rec, char *fieldname);
KINT64 GetStorageCurrentReadBlock(RECORDLIST rec, char *fieldname);
KINT64 GetStorageDataSize(RECORDLIST rec, char *fieldname);
KINT64 SetStorageHeaderPointer(RECORDLIST rec, char *fieldname,KINT64 num);
KINT64 SetStorageLastBlockPointer(RECORDLIST rec, char *fieldname,KINT64 num);
KINT64 SetStorageCurrentReadOffset(RECORDLIST rec, char *fieldname,KINT64 num);
KINT64 GetStorageCurrentReadBlock(RECORDLIST rec, char *fieldname,KINT64 num);
KINT64 UpdateBlockHeader(STORAGE_FILE *sf,STORAGE_BLOCK_HEADER *bh);
KINT64 AllocStorageBlock(STORAGE_FILE *sf);
KINT64 FreeStorageBlock(STORAGE_FILE *sf);
KINT64 PushToUsedStorageBlock(STORAGE_FILE *sf,KINT64 blockptr);
int ReadStorageData(TABLE tbl,
					char *fieldname,
					char *fieldvalue,
					KINT64 offset,
					KINT64 readsize,
					char *buffer,
					int readdone);
KINT64 ReadStorage(TABLE tbl,
				 KINT64 blockptr, 
				 KINT64 offsetwithinblock, 
				 KINT64 readsize,
				 char *buffer,
				 STORAGE_FIELD_INFO *sfi);
KINT64 WriteStorageData(TABLE tbl,
					char *fieldname,
					char *fieldvalue,
					KINT64 offset,
					KINT64 writesize,
					char *buffer,
					int writeflag
					);
KINT64 WriteStorage(TABLE tbl,
				 KINT64 blockptr, 
				 KINT64 offsetwithinblock, 
				 KINT64 readsize,
				 char *buffer,
				 STORAGE_FIELD_INFO *sfi);

KINT64 HexKINT64ToKINT64(char *);
KINT64 KINT64ToHexKINT64(KINT64 num,char *);
KINT64 GetStorageBlockDataSize(TABLE tbl,KINT64 blockptr,STORAGE_BLOCK_HEADER *sbh);
KINT64 GetBlockPtr(STORAGE_FILE *sf,int blockno,STORAGE_FIELD_INFO *sfi,STORAGE_BLOCK_HEADER *sbh);
KINT64 FreeStorageBlocks(TABLE tbl, STORAGE_FIELD_INFO *sfi);
KINT64 SetStorageFieldInfo(RECORDLIST rec,char *fieldname,STORAGE_FIELD_INFO *sfi);
KINT64 ReadBlockHeader(STORAGE_FILE *sf,STORAGE_BLOCK_HEADER *sbh,unsigned long blockptr);
int ReadStorageFieldInfo(class internetsqlobject *obj,STORAGE_FILE *sf,STORAGE_FIELD_INFO *sfi,long offset);







#define SAVE_STORAGE_DATA_FIRST    0x01
#define SAVE_STORAGE_DATA_CONTINUE 0x02
#define SAVE_STORAGE_DATA_LAST     0x03

typedef struct userinfo
{
	char username[40];
	char firstname[40];
	char lastname[40];
	char contactinfo[256];
	char pwd[PWD_BUF_LENGTH];
	char pwr[4];
	char mgrname[40];
	char group[64];
	KINT64 recno;
}USERINFO;


//-----------------------------
typedef struct _lockinfo_
{
 char locktype; //1 read lock 1,  2 modify lock,3 add lock , 4 entire table lock no op 
 KINT64 from;
 KINT64 to;
 KINT64 RecNoInLockTable;
 char thisuser;  //if it is locked by this user
 char Deleted;
 char RecentLock;
 char systemlock;
 char reserved[7];
 char TableName[NAME_BUF_SIZE];
 char UserName[32];
 char MgrName[32];
 char UnlockMarked;
 struct _lockinfo_ *next;
 class internetsqlobject *obj;
}LOCKINFO;
//--------------------------------
typedef class _range_
{
  public:
  KINT64 token;
  KINT64 recno;
  class _range_ *next;
  class internetsqlobject *obj;
} RECORDRANGE;
  
typedef class _groupitem_
{
  public:
  char FieldName[NAME_BUF_SIZE];
  char TableName[NAME_BUF_SIZE];
  char HostName[NAME_BUF_SIZE];
  char DatabaseName[NAME_BUF_SIZE]; 
  char remote;
  KINT64 token;
  class _groupitem_ *next;
  class _groupitem_ *prev;
  RECORDLIST rec;
  class internetsqlobject *obj;
} GROUPITEM,ORDERITEM;
//-----------------------------
typedef class _groupby_
{
  public:
  TABLE output;
  KINT64 count;
  KINT64 tempcount;
  KINT64 handle;
  char sortorder;
  char SortFileName[NAME_BUF_SIZE];
  char TableName[NAME_BUF_SIZE];
  char FileName[NAME_BUF_SIZE];
  KINT64     keylentotal;
  KINT64      keyperbuffer;
  KINT64 keycnt;
  KEYLIST kl;
  GROUPITEM *gi;
  ORDERITEM *oi;
  POSTFIXLINK Having;
  class internetsqlobject *obj;
} GROUPBY,ORDERBY,UNIQUESORT;
//-----------------------------
typedef class FromTable
{
  public:
  char tablealias[NAME_BUF_SIZE];
  char tablename[NAME_BUF_SIZE];
  TABLE Table;
  char HostName[NAME_BUF_SIZE];
  char DatabaseName[NAME_BUF_SIZE];
  char remote;
  INDEX Index;
  KINT64  SystableRecno;
  LOCKINFO *LockInfo;
  char fromtype;
  class MainSelect *View;
  class MainSelect *Select;
  class FromTable *next;
  class FromTable *prev;
  class internetsqlobject *obj;
} FROMTABLE ;
#define FROM_TYPE_NORMAL_TABLE 0x00
#define FROM_TYPE_VIEW         0x01
#define FROM_TYPE_SELECT       0x02
//-----------------------------
typedef class SQL_SelItems
{
  public:
  KINT64  UpdateToken;
  char UpdateFieldName[NAME_BUF_SIZE];
  SYSVARS into;  //select into c variable
  class SQL_SelItems *next;
  class SQL_SelItems *prev;
  POSTFIXLINK Expr;
  KINT64 ReturnToken;
  KDOUBLE number;
  char *value;
  KINT64 count;
  char Alias[NAME_BUF_SIZE];
  char GroupByColFunc;
  char ReturnString[MAX_FIELD_BUFFER_SIZE];
  class internetsqlobject *obj;

} SELECTEDITEM ,INSERTITEM ;
//----------------------------
#if 0
typedef class SQL_SubSelect
{
  public:
  SELECTEDITEM    SelItem;
  char            Distinct;
  char            UseIndex;
  char IndexFileName[NAME_BUF_SIZE];
  FROMTABLE       FromTable;
  POSTFIXLINK     Where;
  POSTFIXLINK     BackLink;
  TABLE Result;     //this will use kamranga table structure
  RECORDLIST RecList;
  long rowcount;
  KINT64 count;
  TABLE   GroupByOutPut;
  char  GroupByOutPutName[NAME_BUF_SIZE];
  GROUPBY *GroupBy;
  int executed;
  char colfunc; //if there is any column function in the selection item, ie, avg,min,max,sum.
  class internetsqlobject *obj;

}SUBSELECT;
#endif
//-----------------------------
typedef struct qryrecord_buf
{
	KINT64 From;
	KINT64 To;
	KINT64 Count;
	struct qryrecord_buf *next;
	struct qryrecord_buf *prev;
	char *Buffer;
    class internetsqlobject *obj;
} QUERY_OUTPUT_ROW_BUFFER;

#define CONJUNCTION_TYPE_NONE      0x00
#define CONJUNCTION_TYPE_UNION     0x01
#define CONJUNCTION_TYPE_INTERSECT 0x02
#define CONJUNCTION_TYPE_MINUS     0x03

//-----------------------------
typedef class MainSelect
 {
  public:
//------for sub select
  int executed;
  POSTFIXLINK     BackLink;
  int subselect_operation;
  int typecheck;
  int typecheck_done;
//-------- subselect ends
  int insertselect_operation;
  //RECORDLIST GetRecord(void); //this is for view 
  KINT64 SqlCommandType;
  KINT64 SelItemCount;
  SELECTEDITEM       *SelItems;
  char               Distinct;
  char joinflag;
  char conjunctionflag;
  class MainSelect    *UnionInterSectMinus;
  FROMTABLE          *FromTables;
  int FromTableCount;
  char CurrentRecordMark;
  POSTFIXLINK        Where;
  POSTFIXLINK        JoinOn;

  //FIELD_NAME_LIST *WhereKeyList;
  char UseIndex;
  char create_cursor;
  char IndexFileName[NAME_BUF_SIZE];
  char CursorName[NAME_BUF_SIZE];
  
  TABLE Result;     //this will use kamranga table structure
  char IntoTableName[NAME_BUF_SIZE];
  char intotable;
  char SelectDumpTableName[NAME_BUF_SIZE];
  class internetsqlobject *obj;
  //char SortIndexName[32];
  RECORDLIST RecList;
  QUERY_OUTPUT_ROW_BUFFER *QryBuffer;
  QUERY_OUTPUT_ROW_BUFFER *CurrentQryBufferNode;
  RECORDLIST GoToRow(KINT64 row);
  QUERY_OUTPUT_ROW_BUFFER *AllocQryBufferNode(void);
  QUERY_OUTPUT_ROW_BUFFER *GetQryBufferNode(KINT64 row);
  int SetMark(KINT64 recno, int mark);
  int ClearMark(KINT64 recno,int mark);
  int DeleteRow(KINT64 recno);
  int Pack(void);
  KINT64 RowLen;
  KINT64 QryBufferCapacity;
  KINT64 QryBufferSize;
  KINT64 AddRowToBuffer();
  KINT64 Save();  //save the reclist to the buffer
  char *GetRowPtr(KINT64 row);
  char QryBufferOverflow;
  long (*RetrieveFunc)(class internetsqlobject *);
  long (*UserFunc)(class internetsqlobject *);
  KINT64 FromRow;
  KINT64 ToRow;
  KINT64 RowCount;
  QUERYITEMSLIST  GetQueryRow(KINT64 rowno);
  QUERYITEMSLIST  GetQueryItems(void);
  QUERYITEMSLIST  GetCursorRow(KINT64 rowno);
  QUERYITEMSLIST  GetCursorItems(void);

  KINT64 CurrentRow;

  KINT64 GetQueryCount(void);
  KINT64 GetQueryRowLength(void);
  QUERYITEMSLIST  GetNextRow(void);
  QUERYITEMSLIST  GetPrevRow(void);
  QUERYITEMSLIST  GetBottomRow(void);
  QUERYITEMSLIST  GetTopRow(void);
  char *GetFieldData(char *fieldname);
  KINT64 GetNumField(char *fieldname);
  char *GetCharField(char *fieldname); 
  int CopyFieldData(char *fieldname,char *databufer);
  QUERYITEMSLIST  GetRow(KINT64 rowno);
  int Free(void);
  double GetDoubleField(char *fieldname);
  char * GetFieldDataByFieldNumber(long fieldno);
  char * GetFieldName(long fieldno);
  int GetFieldCount(void);
  char *GetFieldType(char *fieldname);
  int GetFieldLength(char *fieldname);

  char *GetFieldTypeByFieldNumber(long fieldno);
  int GetFieldLengthByFieldNumber(long fieldno);
  double GetDoubleFieldByFieldNumber(long fieldno);

  KINT64  GetInsertRowId(void);
  int GetMaxBytesUsed(char *fieldname);

char    GetFieldNotNull(int fieldno);
char    GetFieldAutoInc(int fieldno);
char    GetFieldUnique(int fieldno);
char    GetFieldKeyType(int fieldno);
KINT64  GetFieldDecPos(int itemno);
char    *GetFieldFormula(int fieldno);
char    *GetFieldDefault(int fieldno);
int     GetFieldEnum(int fieldno,char **enumbuf);


  int MoveRow(KINT64 from,KINT64 to);
  int SwapRow(KINT64 first,KINT64 second);
  char colfunc; //if there is any column function in the selection item, ie, avg,min,max,sum.
  char QryFailed;
  char FromTypeSelect;
  //char into;
  KINT64 QryType;
  TABLE   GroupByOutPut;
  char  GroupByOutPutName[NAME_BUF_SIZE];
  GROUPBY *GroupBy;
  ORDERBY *OrderBy;
  UNIQUESORT *Usort; 
  char GroupByDistinctOrderByFlag;
  class MainSelect *prev;
  class MainSelect *next;
  class MainSelect *CursorPointer;
  KINT64 CursorTime;
  KINT64 CursorId;
  KINT64 LastKeepAliveTime;
  KINT64  insertno;
  char CursorMode;
  class internetsqlobject *isqlobject;
 } MAINSELECT,*QUERYRESULTOBJECT,*QUERYRESULT,*QUERYOBJECT, *CURSOR,SUBSELECT;

typedef struct _ClientEntry_
{
   unsigned long ClientNo;				  //client will fill this
   unsigned long ClientRegisterTime;  //server will fill this
   unsigned long ServerStartTime;	  //number given at registration time
   long     ClientRequestMsgQid;
   long     ServerReplyMsgQid;
} KMGCLIENTENTRY;

//typedef class affected
//{
//  KINT64 capacity;
//  KINT64 count;
//  KINT64 *recbufer;
//  class affected *next;
//} MODIFIEDRECORDS;
//  
//typedef class Transaction
//{
// char TranTableName[32];
// TABLE OriginalTable;
// TABLE TransactionTable; 
// TABLE SysTable; 
// KINT64  RecCountBeforeTrans;
// MODIFIEDRECORDS  *ModifiedRecords;
// class Transaction *next;
// class Transaction *prev;
//} TRANSACTIONTABLE;

//a transaction table has the following fields
//orginal record count before transaction started  (orgreccnt)
//record number of the record that is affected     (recno)
//record string from the original table before alter (recstring)




typedef struct _lockstruct_
{
  char  TableUseLockUser[10];
  KINT64  tableuselocked;

  char  KmgAccessLockUser[10];
  KINT64  kmgaccsscount;
  KINT64  kmgaccsslocked;

  char  KmgLockLockUser[10];
  KINT64  kmglockcount;  
  KINT64  kmglocklocked;

  char  KmgIndexLockUser[10];
  KINT64  kmgindexcount;
  KINT64  kmgindexlocked;

  char  KmgSysTableLockUser[10];
  KINT64  kmgsystablecount;
  KINT64  kmgsystablelocked;

  char  KmgRightsLockUser[10];
  KINT64  kmgrightscount;
  KINT64  kmgrightslocked;

  char  KmgDbLockUser[10];
  KINT64  kmgdatabaselocked;
}KMGLOCKINFO;
typedef struct _filepool_
{
	char name[NAME_BUF_SIZE];
	struct _filepool_ *next;
	struct _filepool_ *prev;
} KAM_TEMP_FILENAME_POOL;
int AllocateNewFileName(class internetsqlobject *obj,char *filename);
void FreeFileName(class internetsqlobject *obj,char *filename);
void FreeFilePools(struct userslot *slot);
KAM_TEMP_FILENAME_POOL *FindTempFileFromFreeList(class internetsqlobject *obj);
KAM_TEMP_FILENAME_POOL *FindTempFileFromUsedList(class internetsqlobject *obj,char *filename);
void PushTempFileToUsedList(class internetsqlobject *obj,KAM_TEMP_FILENAME_POOL *tmp);
void PushTempFileToFreeList(class internetsqlobject *obj,KAM_TEMP_FILENAME_POOL *tmp);

typedef struct InstanceList
{
	struct userslot *instanceid;
    struct InstanceList *next,*prev;
}INSTANCE_LIST;



typedef struct lockcache_database
{
  char dbname[256];
  int next_valid;
  struct _lockinfo_ *linfo;
  struct lockcache_database *next;
  struct lockcache_database *prev;
}LOCK_CACHE_DATABASE;

typedef struct lockcache
{
  char home[256];
  int next_valid;
  LOCK_CACHE_DATABASE *database;
  struct lockcache *next_home;
  struct lockcache *prev_home;
}LOCK_CACHE;

struct _lockinfo_ *FindTableLockInfo(char *DatabaseHome,char *DatabaseName,char *KmgCurrentUser,char *tablename);

typedef struct syscache_database
{
  char dbname[256];
  int next_valid;
  TABLE_INFO     *tableinfo;
  struct syscache_database *next;
  struct syscache_database *prev;
}SYS_CACHE_DATABASE;

  

typedef struct systablecache
{
  char home[256];
  int next_valid;
  SYS_CACHE_DATABASE *database;
  struct systablecache *next_home;
  struct systablecache *prev_home;
}SYSTABLE_CACHE;

TABLE_INFO  *FindSystableInfo(char *DatabaseHome,char *DatabaseName,char *tablename); 
typedef struct index_info
{
  char tablename[256];
  char indexname[256];
  char dropped[4];
  char key1[256];
  char key2[256];
  char key3[256];
  char key4[256];
  char key5[256];
  char key6[256];
}INDEX_INFO;
typedef struct indexcache_database
{
  char dbname[256];
  int next_valid;
  INDEX_INFO     *indexinfo;
  struct indexcache_database *next;
  struct indexcache_database *prev;
}INDEX_CACHE_DATABASE;

typedef struct indexcache
{
  char home[256];
  int next_valid;
  INDEX_CACHE_DATABASE *database;
  struct indexcache *next_home;
  struct indexcache *prev_home;
}INDEXTABLE_CACHE;


typedef struct group_info
{
  char groupname[256];
  char groupmanager[256];
  char locked[4];
  char lockedby[256];
  char owner[256];
  char allowadmin[4];
}GROUP_INFO;
typedef struct groupcache_database
{
  char dbname[256];
  int next_valid;
  GROUP_INFO     *groupinfo;
  struct groupcache_database *next;
  struct groupcache_database *prev;

}GROUP_CACHE_DATABASE;

typedef struct groupcache
{
  char home[256];
  int next_valid;
  GROUP_CACHE_DATABASE *database;
  struct indexcache *next_home;
  struct indexcache *prev_home;
}GROUPTABLE_CACHE;


typedef struct auto_info
{
  char auto_id[32];
  char username[32];
  char password[PWD_BUF_LENGTH];
  char databasename[256];
  char userpwr[4];
  char KmgUserNo[32];
  char KmgMgrName[256];
  char KmgGroupName[256];
  char KmgUserDbName[256];
  char DebugMode[4];
  char CursorMode[4];
  char startdate[32];
  char expiredate[32];
  char starttime[32];
  char expiretime[32];
  char execinterval[32];
  char execintervalunit[32];
  char lastexecdate[32];
  char lastexectime[32];
  char enabled[32];
  char locked[4];
  char lockedby[4];
  char transmitoutputflag[32];
  char transmitip[32];
  char transmitport[32];
  char name[64];
  char command[64000];
}AUTO_TABLE_INFO;

typedef struct autotblcache
{
  char home[256];
  int next_valid;
  AUTO_TABLE_INFO autotbl_info;
  struct autotblcache *next_home;
  struct autotblcache *prev_home;
}AUTOTABLE_CACHE;





typedef struct dblist_info
{
  char dbname[256];
  char dropped[4];
  char ip[32];
  char port[32];
  char creator[64];
  char locked[4];
  char lockedby[64];
}DBLIST_INFO;

typedef struct dblistcache
{
  char home[256];
  int next_valid;
  DBLIST_INFO dblist_info;
  struct dblistcache *next_home;
  struct dblistcache *prev_home;
}DBLIST_CACHE;



typedef struct host_info
{
 char databasename[256];
 char hostname[64];
 char ip[32];
 char port[32];
 char dropped[4];
}HOST_INFO;


typedef struct hostcache
{
  char home[256];
  int next_valid;
  HOST_INFO host_info;
  struct hostcache *next_home;
  struct hostcache *prev_home;
}HOSTNAME_CACHE;


typedef struct sysdb_info
{
 char locked[4];
}SYSDB_INFO;

typedef struct sysdbcache
{
  char home[256];
  int next_valid;
  SYSDB_INFO    *sysdbinfo;
  struct sysdbcache *next_home;
  struct sysdbcache *prev_home;
}SYSDB_CACHE;

typedef struct GlobalConfig
{
 KINT64 DumpFileNameMutex;
 KINT64 CircularQMutex;

  int CircularQInitialized;
  KINT64 MaxKmgUser;
  char KmgUseDynamicLibrary;
  KINT64 KMGLOCKRETRYCOUNT;
  int MaxKmgGroup;
  KINT64 EvalStackSize;
  int ExpDecimalPos;
  KINT64 TransactionBufferCapacity;
  KINT64 TransactionBufferOverflowCount; /* #63: bumped instead of writing past recbuffer - never crash */
  KINT64 VlrEnabled; /* #72 module 3.6b: master switch for the VLR (variable-length-record) path. 0=OFF (default, shipping behavior byte-identical). When 1, CREATE recordformat=vlr / VLR tables route through vlrlib. */
  KINT64 TranTableExtraFieldLen;
  KINT64 ClientTimeoutTick;
  KINT64 MaxUserNameLen;
  KINT64 MaxUserPwdLen;
  char  SysResourceLockFlag;
  KINT64 INDEXBUFFERSIZE;
  KINT64 NODESPERBUFFER;
  KINT64 KMGLOCKTRY;
  KINT64 KMGTASKDELAY;//5 seconds sleep
  KINT64 MaxParallelServer;
  char KmgVersion[128];
  char blankfield[256];
   KINT64 ClientTickDelay;  //10 ms
   long limitimposed;
   long calllimit;
   MUTEX_LIST *MutexList;
   INSTANCE_LIST *Instances;
   KINT64 MutexAccessMutex;
   KINT64 ExecMutex;   /* serialises internetsqlobject::Exec()/Execute() across all
                        objects in a process - the engine's command-execution path
                        uses diffuse shared working state that is not thread-safe;
                        this coarse lock makes concurrent Exec correct. */
   LOCK_CACHE       *lock_cache;
   SYSTABLE_CACHE   *systable_cache;
   INDEXTABLE_CACHE *indextable_cache;
   AUTOTABLE_CACHE  *autotable_cache;
   DBLIST_CACHE     *dblist_cache;
   HOSTNAME_CACHE   *hostname_cache;
   SYSDB_CACHE      *sysdb_cache;
   GROUPTABLE_CACHE *grouptable_cache;

   KINT64 lock_cache_mutex;
   KINT64 systable_cache_mutex;
   KINT64 indextable_cache_mutex;
   KINT64 autotable_cache_mutex;
   KINT64 dblist_cache_mutex;
   KINT64 hostname_cache_mutex;
   KINT64 sysdb_cache_mutex;
   KINT64 grouptable_cache_mutex;

 }GLOBAL_CONFIG;

typedef class affected
{
  public:
  KINT64 capacity;
  KINT64 count;
  KINT64 *recbuffer;
  class affected *next;
} MODIFIEDRECORDS;

typedef class _TransactionInfo_
{
 public:
 char  UserName[64];
 KINT64  UserNo;
 char  TranTableName[NAME_BUF_SIZE];
 TABLE OriginalTable;
 TABLE TransactionTable; 
 TABLE SysTable; 
 KINT64  SysTableRecNo; 
 KINT64  RecCountBeforeTrans;
 MODIFIEDRECORDS  *ModifiedRecords;
 void *RecnoIndexRoot;   /* #63: in-memory B-tree of transaction record numbers -> O(log n) FindTransRecNo instead of O(n) linear scan (was O(n^2) inserts) */
 class _TransactionInfo_ *next;
 class _TransactionInfo_ *prev;
} TRANSACTIONTABLE;

typedef struct application_context
{ 
   char KmgUserPwr;
   char DebugMode;
   char MemDebug;
   char CommDebug;
   char compress;
   char encrypt;
   char CursorMode;
   char SecureLink;
   char reserved[4];
   char UserName[32];
   char Password[PWD_BUF_LENGTH];
   char KmgMgrName[32];
   char DatabaseName[DATABASE_NAME_SIZE];
   char KmgGroupName[GROUP_NAME_SIZE];
   char KmgUserDbName[DATABASE_NAME_SIZE];
   char HostName[HOST_NAME_SIZE];
   char encryptionkey[KEY_LENGTH];
   long KmgUserNo;
   long contextid;

} APPLICATION_CONTEXT;

typedef struct memblk
 {
  char   *Start; 
  char   *End; 
  KINT64   size; 
  KINT64   Handle; 
  KINT64   Usage; 
 } KMGMEMORYBLOCK;

#define KMGMEMORYBLOCKSIZE 2048
#define USERALLOC   0x00
#define MODULEMSG   0x01
#define SYSMSGMGR   0x02
#define TASKLOADER  0x03
#define DISKDRIVE   0x04
#define EXPORTTABLE 0x05
////////////////////////////////
#if 0
typedef struct userslot
{
 struct userslot *displayslot;
 char command[MAX_EXTENDED_RECORDLEN];
 int Token;
 int SqlCommandCode;
 char logout;
 char *bufferp;
 int PeCountBufIndex;
 int NotPeCountBufIndex;
 int like_token_found;
 char WordBuffer[MAX_EXTENDED_RECORDLEN];
 long server_logfilesize;
 int SqlErrorCode;
 int insertno;
 int autoincvalue;
 char CursorMode;
 char GenBuf[MAX_EXTENDED_RECORDLEN];
 int current_command;
 int commandlen;
 char server_monitor_mode;
 char personal;
 char distributed;
 char ScratchPad[MAX_EXTENDED_RECORDLEN];
 struct CallQueue *Call;
 char serverdisplay;
 char DisableMessages;
 char LocalClientMode;
 char ServerMode;
 MAINSELECT *CURRENTQUERY;
 TABLE QRYOUTPUTTABLE;
 long (*QryRetrieveFunc)(class internetsqlobject *);
 long (*QrySelectItemFunc)(class internetsqlobject *);
 long (*QryUserFunc)(class internetsqlobject *);

 char SqlError[65000];
 char SqlQryStat[65000];
 KINT64 KamrangaCursorId;
 MAINSELECT *CURRENTVIEW;
 SELECTEDITEM *CURSELITEM;
 SUBSELECT *CURRENTSUBSELECT;
 SYSVARS SYSVARROOT;
 char aggregate;
 char qryabort;
 char *spacep;
 char _chr;
 char SpaceBuffer[65536];
 char num_buffer[256];
 char *wordp;
 char *nump;
 double *TableTop;
 char FunctionNameBuffer[256];
 char server_monitor_output;
 char SqlIdentifier[256];
 char SqlDotIdentifier[256];
 char SqlDotIdentifierDotIdentifier[256];
 DATABASE TABLESCOPE;
 char   errorshow;



KINT64 line_number;   //line being read
char SourceBuffer[SRC_BUF_SZ];
char pathbuf[256];
char pathbuf2[256];



FIELDOBJECT *FF;
KINT64 totalkey;
KINT64 leafcount;
KINT64 ReadIndexBegin;
KINT64 ReadIndexEnd;
char Rb[256];
char Wb[256];
KINT64 Buffer1Begin;
KINT64 Buffer1End;
KINT64 Buffer2Begin;
KINT64 Buffer2End;
char Buffer1Changed;
char Buffer2Changed;
KINT64 BufferPerBlock;

KINT64 RecordCount;
  

char HostName[256];
char LocalHostName[256];
char RemoteKmgDisConnectUser[256];
char RemoteKmgDisConnectPassword[PWD_BUF_LENGTH];

char RemoteKmgCurrentUser[256];
char RemoteKmgCurrentPassword[PWD_BUF_LENGTH];
     
char RemoteKmgManager[256];
char RemoteKmgManagerPassword[PWD_BUF_LENGTH];

char KmgDisConnectUser[256];
char KmgDisConnectPassword[PWD_BUF_LENGTH];
char KmgMonitorUser[256];
char KmgMonitorDb[256];
char KmgCurrentUser[256];
char KmgCurrentPassword[PWD_BUF_LENGTH];
char KmgGroupName[256];
char KmgResourceLocked;
char KmgManager[256];
char KmgManagerPassword[PWD_BUF_LENGTH];
char DatabaseName[NAME_BUF_SIZE];
//char RemoteClientHomeDir[260]={0};
char ProgramStartDir[260];

char CurrentDirectoryName[260];
char CurrentDataBase[256];
char LastDirectoryName[256];
char KmgDebugUserName[256];
char KmgDebugUserPwd[PWD_BUF_LENGTH];
char KmgUserDbName[256];
char KmgUserPwr;
long KmgUserNo;




char KAM_SqlCommandBuffer[COMMAND_BUFFER_SIZE];
char DownLoadBuffer[MAX_DOWNLOAD_SIZE];



TRANSACTIONTABLE * _TRANSACTIONHEADER_;


KINT64 CURRENTCOUNT;
KDOUBLE CURRENTSUM;
KDOUBLE CURRENTAVG;
KDOUBLE CURRENTMIN;
KDOUBLE CURRENTMAX;
TABLE CURRENTTABLE;
INDEX CURRENTINDEX;
LISTINFO CURRENTLIST;
MAINSELECT *MAINSELECTROOT;

KINT64 QryOutPutCount;


char KmgDateBuffer[16];
char KmgDateChar[64];
char KmgMgrName[32];
char KmgRemoteServer;
char KmgAutoSystemLocking;
char KmgGrantRevokeChecking;
char KmgCommitRollBacking;
long KmgTryCount;



char ServerIpString[NAME_BUF_SIZE];
char ServerPortString[NAME_BUF_SIZE];
char ParallelServerPortString[NAME_BUF_SIZE];
char MutexServerPortString[NAME_BUF_SIZE];
char ClientPortString[NAME_BUF_SIZE];
KINT64 parallel_serverport;
KINT64 mutex_serverport;
int clientport;
int serverport;
KINT64 serverip;
char KmgSuperUserName[256];
char KmgSuperUserPwd[PWD_BUF_LENGTH];
char DatabaseDirectoryPath[1024];
char DatabaseHome[256];
int  unixdebug;
int dlldebug;
char KamrangaSqlStarted;
char usesqlindex;
int current_command_object;
char server_compress_mode;
char server_encryption_mode;
char KmgRdbmsDisabled;
char master_server_mode;
char mutex_server_mode;
char thread_server_mode;
int parallel_server_count;
char DebugMode;

char _OrgBuf[ORGBUFSIZE];
char _ReadBuf[INDEX_BUF_SIZE];
char _WriteBuf[INDEX_BUF_SIZE];
char _SqlWriteBuf[INDEX_BUF_SIZE];
char TemporaryField[MAX_EXTENDED_RECORDLEN];
char KmgTmpBuf[MAX_EXTENDED_RECORDLEN];
//char *MemoryPoolBuf[MEMORY_POOL_BUF_SIZE];

char *MemoryPoolBuf;
KMGMEMORYBLOCK MemBlocks[KMGMEMORYBLOCKSIZE];
int  MemBlockIndex;
char *CurrentMemBlockPtr;

char DateSetting;
KAM_INT32 LockRequestQ;
KAM_INT32 LockRequestReplyQ;
KAM_INT32 LockRequestReplyAckQ;
char  SysResourceLockFlag;
char KmgUseDynamicLibrary;
KMGCLIENTENTRY KmgClientRegistration;							  
KMGCLIENTENTRY KmgRegInfo;	     
KAM_INT32 KmgClientRequestQ;						  
KAM_INT32 KmgServerReplyQ;						  
char KmgServerRunning;
KINT64 KmgPacketCount;
int sqlclientsocket;
int sqlserversocket;
char servername[32];
int server_stopflag;
char MessageRelay;
KINT64 tempfilecount;
KAM_TEMP_FILENAME_POOL *UsedFilePool;
KAM_TEMP_FILENAME_POOL *FreeFilePool;
KINT64 PeCountBuf[MAX_PARTIAL_MATCH_COUNT];
KINT64 NotPeCountBuf[MAX_PARTIAL_MATCH_COUNT];

int ReturnCode;


char RunScriptBuffer[CMDLINE_BUFFER_SIZE+1];
char RunScriptCommand[CMDLINE_BUFFER_SIZE+1];
KINT64 RunScriptCount;
int (*RunScriptOutputFunction)(struct userslot *slot,char *msg);
int (*RunScriptUserFunction)(struct INTERNET_SQL_OBJECT *obj);

char StopRunScript;
char QuitRunScript;
char SqlScriptSingleStepMode;
FILE *scriptlogfp;


char extended_table_mode;
int MutexServerPortNoFromMaster; 
char mutex_debug;

int mutexsocket;
char quitserver;
char sqlcommfailed;

int waitsocket;
KAM_INT32 RequestQ;
KAM_INT32 ReplyQ;
KINT64 StartTime;
struct _commpacket_  *ClientMsg,*ParallelMsg;  
int ParallelServerPortNoFromMaster; 
KINT64 TransmitSeq;
KINT64 ServerIp;
KINT64 ServerPort;
int CommandType;
char timeout;
char ConnectDbError;
struct parallel_server_info *ParallelServer;

struct CallQueue *RequesterQueue;
char KmgRemoteConnection;
unsigned int kmgxmitbufno;
unsigned int kmgrecvbufno;
char showdebug;
char commdebug;
char MemDebug;
int serialconsole;
TABLEOBJECT *CurDbf;
char TableWizardMode ;
KINT64 Curbegin;
KINT64 Curend;
char *DelimitedRecordString;
//char DateSetting;//=USDATE;
KINT64 UserSlotMutex;
FILE *logfp;
int window_console;
int clientaddrlen;
unsigned long nonblocking;
int SocketErrorStatus;
int serror;
KINT64  UnixSocketHandle;



#ifndef SUNUNIX
struct hostent *UnixHostEntry;
in_addr ip;
struct sockaddr clientaddr,serveraddr;
struct hostent *WinHostEntry;

struct sockaddr client_addr;
WORD SockLibVersion; //MAKEWORD(1,1)
WSADATA  SocketData;
SOCKET s;
SOCKADDR_IN addr;
LINGER ling;
SOCKADDR_IN WinServerAddr;
SOCKADDR_IN WinClientAddr;
SOCKADDR_IN ParallelWinServerAddr;
SOCKADDR_IN ParallelWinClientAddr;
SOCKADDR_IN DistributedWinServerAddr;
SOCKADDR_IN DistributedWinClientAddr;
SOCKADDR_IN MutexWinServerAddr;
SOCKADDR_IN MutexWinClientAddr;
#else   //FOR SUNUNIX
#define SOCKADDR_IN  struct sockaddr_in
struct hostent *UnixHostEntry;
struct hostent *WinHostEntry;
struct sockaddr client_addr;
SOCKADDR_IN WinServerAddr;
SOCKADDR_IN WinClientAddr;
SOCKADDR_IN ParallelWinServerAddr;
SOCKADDR_IN ParallelWinClientAddr;
SOCKADDR_IN DistributedWinServerAddr;
SOCKADDR_IN DistributedWinClientAddr;
SOCKADDR_IN MutexWinServerAddr;
SOCKADDR_IN MutexWinClientAddr;
SOCKADDR_IN addr;
linger ling;
in_addr ip;
struct sockaddr serveraddr;
#endif //SUNUNIX


long  DisplayQueueId;
struct CallQueue *CallArray;


#define SOCKADDR_IN  struct sockaddr_in


char alldelundel;
int autoindexing;
char auto_indexing_add_del_operation;
class internetsqlobject *CURRENTOBJECT;
class internetsqlobject *objects;
void *mallocheaphead;
void *persistentmallocheaphead;

}USERSLOT , *INTERNET_SQL_INSTANCE;
#endif
/////////////////////////////////////////
#include "../h/mem.h"


#define COMMAND_DATA_SIZE  400
typedef struct command_struct
{
	int command_type;
	int packet_serial_no;
	int bank_id;
	int last_packet;
	int extra1;
	int extra2;
	int compressed;
	char signature[64];
	int data_count;
	char data[COMMAND_DATA_SIZE];
}COMMAND_FORMAT;


#define COMMAND_INVALID                 0x00
#define COMMAND_CLIENT_COMMAND          0x01
#define COMMAND_SERVER_REPLY            0x02
typedef struct connectq
{
	int selfindex;
	int socketid;
	int service_req;
	int busy;
	int endthread;
	int mutex;
	int ThreadId;
	char *data;
	COMMAND_FORMAT TxPkt;
	COMMAND_FORMAT RxPkt;

	struct userslot *slot;
} CONNECT_QUEUE;

#define MAX_CONNECT_Q 1
int PlaceRequestInTheConnectQ(int clientsocket,struct userslot *slot);
int InitThreads(struct userslot *slot);
void IsqlServerProcessThread(void *parameter);

typedef struct objectlocalmallocchunks
{
  void *p;
  long objectid;
  long reserved;
  struct objectlocalmallocchunks *next;
} OBJECT_MALLOC_HEAP;


typedef struct objectallocchaintrack
{
  void *p;
  long objectid;
  long reserved;
  struct objectallocchaintrack *next;
} OBJECT_MALLOC_TRACK;


typedef struct object_mem_pools
{
 long objectid;
 long reserved;
 OBJECT_MALLOC_HEAP    *objectmallocheap;  
 OBJECT_MALLOC_TRACK   *MallocTrack;
 OBJECT_MALLOC_TRACK   *FreeTrack;
 struct object_mem_pools *next;
} OBJECT_MEM_POOL;

typedef struct userslot
{
 MEMORY_HEAP *mallocheaphead;
// char *SlotMemoryPoolBuf;
 KAM_TEMP_FILENAME_POOL *UsedFilePool;
 KAM_TEMP_FILENAME_POOL *FreeFilePool;
 struct userslot *displayslot;
 char CursorMode;
 char server_monitor_mode;
 char personal;
 int txtimeout;
 int connect_q_enque_wait;
 int rxtimeout; //in minutes
 char usecallq;
 char distributed;
 struct CallQueue *Call;
 char serverdisplay;
 char DisableMessages;
 char shelllogenabled;
 char LocalClientMode;
 char ServerMode;
 int SlotErrorCode;
 char SlotErrorString[256];
 int tempfilecount;
 long (*QryRetrieveFunc)(class internetsqlobject *);
 long (*QrySelectItemFunc)(class internetsqlobject *);
 long (*QryUserFunc)(class internetsqlobject *);


 SYSVARS SYSVARROOT;

 char server_monitor_output;
 DATABASE TABLESCOPE;
 char   errorshow;


 char PadBuf[MAX_EXTENDED_RECORDLEN];
 CONNECT_QUEUE slot_connect_q[MAX_CONNECT_Q];

char HostName[256];
char ServerName[256];
char KmgMonitorUser[256];
char KmgMonitorDb[256];

char SlotRemoteKmgDisConnectUser[256];
char SlotRemoteKmgDisConnectPassword[PWD_BUF_LENGTH];

char SlotRemoteKmgCurrentUser[256];
char SlotRemoteKmgCurrentPassword[PWD_BUF_LENGTH];
     
char SlotRemoteKmgManager[256];
char SlotRemoteKmgManagerPassword[PWD_BUF_LENGTH];

char SlotKmgDisConnectUser[256];
char SlotKmgDisConnectPassword[PWD_BUF_LENGTH];

char SlotKmgCurrentUser[256];
char SlotKmgCurrentPassword[PWD_BUF_LENGTH];
char SlotKmgGroupName[256];
char SlotKmgManager[256];
char SlotKmgManagerPassword[PWD_BUF_LENGTH];
char SlotDatabaseName[NAME_BUF_SIZE];
char SlotCurrentDataBase[256];
char SlotDatabaseHome[256];
char SlotKmgUserPwr;
long SlotKmgUserNo;
char SlotKmgMgrName[32];
char SlotKmgUserDbName[256];


char KmgResourceLocked;
//char RemoteClientHomeDir[260]={0};
char ProgramStartDir[260];

char CurrentDirectoryName[260];
char LastDirectoryName[256];
char KmgDebugUserName[256];
char KmgDebugUserPwd[PWD_BUF_LENGTH];

char KmgRemoteServer;
char KmgAutoSystemLocking;
char KmgGrantRevokeChecking;
char KmgCommitRollBacking;
long KmgTryCount;

char encryptionkey[KEY_LENGTH];

char ServerIpString[NAME_BUF_SIZE];
char ServerPortString[NAME_BUF_SIZE];
char LogServerIpString[NAME_BUF_SIZE];
char LogServerPortString[NAME_BUF_SIZE];

char ParallelServerPortString[NAME_BUF_SIZE];
char MutexServerPortString[NAME_BUF_SIZE];
char ClientPortString[NAME_BUF_SIZE];
KINT64 parallel_serverport;
KINT64 mutex_serverport;
int clientport;
int serverport;
KINT64 serverip;
char SlotKmgSuperUserName[256];
char SlotKmgSuperUserPwd[PWD_BUF_LENGTH];
char SlotDatabaseDirectoryPath[1024];
int  unixdebug;
int dlldebug;
char KamrangaSqlStarted;
char usesqlindex;
int current_command_object;
char server_compress_mode;
char server_encryption_mode;
char KmgRdbmsDisabled;
char master_server_mode;
char mutex_server_mode;
char thread_server_mode;
int parallel_server_count;
char DebugMode;



char DateSetting;
KAM_INT32 LockRequestQ;
KAM_INT32 LockRequestReplyQ;
KAM_INT32 LockRequestReplyAckQ;
char  SysResourceLockFlag;
char KmgUseDynamicLibrary;
KMGCLIENTENTRY KmgClientRegistration;							  
KMGCLIENTENTRY KmgRegInfo;	     
KAM_INT32 KmgClientRequestQ;						  
KAM_INT32 KmgServerReplyQ;						  
char KmgServerRunning;

 char RunScriptBuffer[CMDLINE_BUFFER_SIZE+1];
 char RunScriptCommand[CMDLINE_BUFFER_SIZE+1];
 KINT64 RunScriptCount;
 int (*RunScriptOutputFunction)(struct userslot *slot,char *msg);
 int (*RunScriptUserFunction)(class internetsqlobject *obj);
 FILE *scriptlogfp;

 char StopRunScript;
 char QuitRunScript;
 char SqlScriptSingleStepMode;


KINT64 KmgPacketCount;
int sqlclientsocket;
int sqlserversocket;
int serversocket;
char servername[32];
int server_stopflag;
char MessageRelay;


char extended_table_mode;
int MutexServerPortNoFromMaster; 
char mutex_debug;

int mutexsocket;
char quitserver;
char sqlcommfailed;

int waitsocket;
KAM_INT32 RequestQ;
KAM_INT32 ReplyQ;
KINT64 StartTime;
//struct _commpacket_  *ClientMsg,*ParallelMsg;  
int ParallelServerPortNoFromMaster; 
KINT64 TransmitSeq;
KINT64 ServerIp;
KINT64 ServerPort;
char timeout;
struct parallel_server_info *ParallelServer;

struct CallQueue *RequesterQueue;
char KmgRemoteConnection;
unsigned int kmgxmitbufno;
unsigned int kmgrecvbufno;
char showdebug;
char commdebug;
char MemDebug;
int serialconsole;
char TableWizardMode ;

//char DateSetting;//=USDATE;
KINT64 UserSlotMutex;
FILE *logfp;
int window_console;
int clientaddrlen;
unsigned long nonblocking;
int SocketErrorStatus;
int serror;
KINT64  UnixSocketHandle;



#ifndef SUNUNIX
struct hostent *UnixHostEntry;
in_addr ip;
struct sockaddr clientaddr,serveraddr;
struct hostent *WinHostEntry;

struct sockaddr client_addr;
WORD SockLibVersion; //MAKEWORD(1,1)
WSADATA  SocketData;
SOCKET s;
SOCKADDR_IN addr;
LINGER ling;
SOCKADDR_IN WinServerAddr;
SOCKADDR_IN WinClientAddr;
SOCKADDR_IN ParallelWinServerAddr;
SOCKADDR_IN ParallelWinClientAddr;
SOCKADDR_IN DistributedWinServerAddr;
SOCKADDR_IN DistributedWinClientAddr;
SOCKADDR_IN MutexWinServerAddr;
SOCKADDR_IN MutexWinClientAddr;
#else   //FOR SUNUNIX
#define SOCKADDR_IN  struct sockaddr_in
struct hostent *UnixHostEntry;
struct hostent *WinHostEntry;
struct sockaddr client_addr;
SOCKADDR_IN WinServerAddr;
SOCKADDR_IN WinClientAddr;
SOCKADDR_IN ParallelWinServerAddr;
SOCKADDR_IN ParallelWinClientAddr;
SOCKADDR_IN DistributedWinServerAddr;
SOCKADDR_IN DistributedWinClientAddr;
SOCKADDR_IN MutexWinServerAddr;
SOCKADDR_IN MutexWinClientAddr;
SOCKADDR_IN addr;
linger ling;
in_addr ip;
struct sockaddr serveraddr;
#endif //SUNUNIX


long  DisplayQueueId;
struct CallQueue *CallArray;


#define SOCKADDR_IN  struct sockaddr_in


char alldelundel;
int autoindexing;
char auto_indexing_add_del_operation;
class internetsqlobject *objects;
long server_logfilesize;
TRANSACTIONTABLE * _TRANSACTIONHEADER_;
KINT64 objectmem_mutex;
OBJECT_MEM_POOL *object_mem_pool;
int file_open_count;
int file_close_count;
char shelllogfilename[256];
FILE *shelllogfp;
struct userslot *next,*prev;
}USERSLOT , *INTERNET_SQL_INSTANCE;

void  ClearObjectMemPool(USERSLOT *slot);






typedef struct objectlocals
{
 //int  ErrorCode;
 int QueryRetrieveCount;
 char ConnectDbError;
 MAINSELECT *MAINSELECTROOT;
 TABLE QRYOUTPUTTABLE;
 KINT64 CURRENTCOUNT;
 KDOUBLE CURRENTSUM;
 KDOUBLE CURRENTAVG;
 KDOUBLE CURRENTMIN;
 KDOUBLE CURRENTMAX;
 TABLE CURRENTTABLE;
 INDEX CURRENTINDEX;
 LISTINFO CURRENTLIST;
 char SqlIdentifier[256];
 char SqlDotIdentifier[256];
 char SqlDotIdentifierDotIdentifier[256];
 char KmgDateBuffer[16];
 char KmgDateChar[64];
 KINT64 PeCountBuf[MAX_PARTIAL_MATCH_COUNT];
 KINT64 NotPeCountBuf[MAX_PARTIAL_MATCH_COUNT];
 char command[MAX_EXTENDED_RECORDLEN];
 MAINSELECT *CURRENTQUERY;
 int Token;
 int SqlCommandCode;
 char logout;
 char *bufferp;
 char *parse_string;
 int PeCountBufIndex;
 int NotPeCountBufIndex;
 int like_token_found;
 char WordBuffer[MAX_EXTENDED_RECORDLEN];
 int SqlErrorCode;
 int insertno;
 int autoincvalue;
 int TokenColumn;
 char *DelimitedRecordString;

 char GenBuf[MAX_EXTENDED_RECORDLEN];
 int current_command;
 int commandlen;
 char ScratchPad[MAX_EXTENDED_RECORDLEN];
 //char SqlError[65000];
 //char SqlQryStat[65000];
 KINT64 KamrangaCursorId;
 SELECTEDITEM *CURSELITEM;
 SUBSELECT *CURRENTSUBSELECT;
 char aggregate;
 char qryabort;
 char *spacep;
 char _chr;
 char SpaceBuffer[65536];
 char num_buffer[256];
 char *wordp;
 char *nump;
 double *TableTop;
 char FunctionNameBuffer[256];
 KINT64 line_number;   //line being read
 char SourceBuffer[SRC_BUF_SZ];
 char pathbuf[256];
 char pathbuf2[256];
 FIELDOBJECT *FF;
 KINT64 totalkey;
 KINT64 leafcount;
 KINT64 ReadIndexBegin;
 KINT64 ReadIndexEnd;
 char Rb[256];
 char Wb[256];
 KINT64 Buffer1Begin;
 KINT64 Buffer1End;
 KINT64 Buffer2Begin;
 KINT64 Buffer2End;
 char Buffer1Changed;
 char Buffer2Changed;
 KINT64 BufferPerBlock;
 KINT64 RecordCount;
char _OrgBuf[ORGBUFSIZE];
char _ReadBuf[INDEX_BUF_SIZE];
char _WriteBuf[INDEX_BUF_SIZE];
char _SqlWriteBuf[INDEX_BUF_SIZE];
char TemporaryField[MAX_EXTENDED_RECORDLEN];
char KmgTmpBuf[MAX_EXTENDED_RECORDLEN];
KINT64 QryOutPutCount;
char KAM_SqlCommandBuffer[COMMAND_BUFFER_SIZE];
char DownLoadBuffer[MAX_DOWNLOAD_SIZE];
TABLEOBJECT *CurDbf;
KINT64 Curbegin;
KINT64 Curend;
char *MemoryPoolBuf;
KMGMEMORYBLOCK MemBlocks[KMGMEMORYBLOCKSIZE];
int  MemBlockIndex;
char *CurrentMemBlockPtr;
struct _commpacket_  *ClientMsg,*ParallelMsg;  

//void *mallocheaphead;
//void *persistentmallocheaphead;
int ReturnCode;
int CommandType;

char KmgCurrentUser[256];
char KmgCurrentPassword[PWD_BUF_LENGTH];
char KmgGroupName[256];
char KmgManager[256];
char KmgManagerPassword[PWD_BUF_LENGTH];
char DatabaseName[NAME_BUF_SIZE];
char CurrentDataBase[256];
char KmgUserPwr;
long KmgUserNo;
char KmgMgrName[32];
char DatabaseHome[256];
char KmgUserDbName[256];

char RemoteKmgDisConnectUser[256];
char RemoteKmgDisConnectPassword[PWD_BUF_LENGTH];

char RemoteKmgCurrentUser[256];
char RemoteKmgCurrentPassword[PWD_BUF_LENGTH];
     
char RemoteKmgManager[256];
char RemoteKmgManagerPassword[PWD_BUF_LENGTH];

char KmgDisConnectUser[256];
char KmgDisConnectPassword[PWD_BUF_LENGTH];

char KmgSuperUserName[256];
char KmgSuperUserPwd[PWD_BUF_LENGTH];
char DatabaseDirectoryPath[1024];

}OBJECT_LOCALS;



void *GetMem(class internetsqlobject *, long size);
#define MAX_USER_SLOT 256
void InitSlotMemPoolBuffer(USERSLOT *slot);
USERSLOT *AllocUserSlot(void);
void FreeUserSlot(USERSLOT *slot);

typedef class internetsqlobject 
{
  public:
  USERSLOT *slot; 
  OBJECT_LOCALS locals;
  MAINSELECT  *queryobject;
  int Exec(char *);
  int object_busy;
  int ObjectNotBusy(void);
  char GetUserPrivilege(void);
  char * GetUserLoginName(char *namebuf);
  char * GetPwd(char *namebuf);

  KINT64 Count(void);
  KINT64 RowLength(void);
  KINT64 RowNo(void);
  QUERYITEMSLIST  Next(void);
  QUERYITEMSLIST  Prev(void);
  QUERYITEMSLIST  Bottom(void);
  QUERYITEMSLIST  Top(void);
  char *Data(char *fieldname);
  KINT64 IntData(char *fieldname);
  int CopyField(char *fieldname,char *databufer);
  QUERYITEMSLIST  Row(KINT64 rowno);
  double DoubleData(char *fieldname);
  char * DataByFno(long fieldno);
  char * FieldName(long fieldno);
  int FieldCount(void);
  char *FieldType(char *fieldname);
  int MaxBytesUsed(char *fieldname);
  int FieldLength(char *fieldname);
  char *Status(void);
  char statusbuf[256];
  int RetCode;
  KINT64  InsertRowId(void);
  KINT64 selfpointer;
  class internetsqlobject *next;
  class internetsqlobject *prev;
  struct _commpacket_ *KmgMsg;
  CONNECT_QUEUE *connect_q;
  COMMAND_FORMAT RxPkt;
  COMMAND_FORMAT TxPkt;
  int CommandType;
  int error_code;
  char firstpacketseen;
  char lastpacketseen;
  long QryOutPutCount;
  void CloseQryOutPut(void);
  char qryabort;
  char CursorMode;
  int compress_mode;
  MEMORY_HEAP *mallocheaphead;
  MEMORY_HEAP *persistentmallocheaphead;
  //KINT64  IncrementValue(void);  
}INTERNET_SQL_OBJECT;

INTERNET_SQL_OBJECT *NewInternetSqlObject(KINT64 slotid);
void FreeInternetSqlObject(INTERNET_SQL_OBJECT *object);


  

RECORDLIST GetCursorRowFromServer(QUERYRESULT qry,KINT64 i);
void SetCursorMgmtInfo(MAINSELECT *qryobject);
int  IndexUsableWhere(INTERNET_SQL_OBJECT *obj,POSTFIXLINK Where,  FROMTABLE *ft, char *IndexFileName);
int  FindMatchingIndex(INTERNET_SQL_OBJECT *obj,char *TableName,char *fieldname, char *IndexFileName);
int  RemoteFindMatchingIndex(INTERNET_SQL_OBJECT *obj,char *TableName,char *hostname,char *fieldname, char *IndexFileName);
FIELD_NAME_LIST * InsertFieldNameIntoList(INTERNET_SQL_OBJECT *obj,FIELD_NAME_LIST **flist,char *fiedname);
void DeleteFieldNameList(FIELD_NAME_LIST **flist);



//------------------------------------------------
//client will work as follows with server:
//1. At start time client will register with the
//   server and get the client registration time
//   server start time and the client number
//2. Before sending a new command to the server from the
//   client client must read the system seconds to check 
//   if 24 hr is over since the registration is done. If so
//   client must reregister and start sending commands to the server
//3. If client peeks a message whose client no matches but the client 
//   start time or server start time does not matches will re register
//   resend it msg to the server
//4. Client will retrieve the msg only if client time server time and
//   client no properly matches          
//5. After receiving the reply msg from the server client must check 
//   its msg no and other staff to make sure that this pkt beKINT64s to
//   him if it does not it will throw  it away and resend the command
//   with the same msg no.
//   If answer to the msg takes a KINT64 time client will resend msg with the
//   same msg no to the server. Any msg received with duplicate msg no or 
//   older msg no will be discarded.   

//Server will work as follows:
//1. It will always assign a new number starting from 0 
//   to a client when a registration request will be received
//2. when registration will reach 0xFFFFFFFF it will restart from 0.
//3. It will process msg request from the request q and place the answer
//   in the reply Q. If the reply Q is not cleared within 15 seconds it will
//   clear the q and process new msg from the request Q.


typedef struct _kmgcomfielddefn_
{
 char FieldName[256];
 char FieldType;
 char  DecimalPos;
 char notnull;
 char keytype;
 char autoinc;
 char unique;
 char reserved[2];
 long max_field_byte_used;
 long FieldLength;
 KINT64 incval;
}KMG_COMM_FIELDDEFN;



							  
typedef struct kmgcommheader
{
   char PacketType;
   char LastPacket;
   char interleavehop;
   char extra1;
   char Reserved[4];
   char Signature[8];
   short int TotalSelectItem;
   short int SelectItemCount;
   short int SelectItemRemain;
   short int splitsize;
   long SendersPortNumber;
   long ReturnCode;
   long ErrorCode;
   long ErrorNo;
   long CommandType;
   long ServerInstruction;
   long DataLength;
   long reserved2;
   KINT64  insertno;
   KINT64 PacketNo;
   KINT64 TransmitSeq;
   KINT64 TransmitAck;
   KINT64 TransactionReqId;
   KINT64 TransactionReplyId;
   KINT64 SendersIp;
   KINT64 RetrieveRowNumber;
   KINT64 CursorId;
   KINT64 CursorPointer;
   KINT64 QryOutPutCount;
   KINT64 CursorTime;
   APPLICATION_CONTEXT context;
} KMGCOMMHEADER;

typedef struct
{
	char commflag;
 	char serverid;
	char message;
	char msgparam;
	char reserved[4];
	char servername[32];
	int sqlclientsocket;
    struct CallQueue *sqlclientcall;
	int extra;
} COMM_PREHEAD;

#define COMM_DONE_TRY_COUNT 3

#define COMM_FLAG_COMPRESSED       0x01
#define COMM_FLAG_ENCRYPTED        0x02
#define COMM_FLAG_DATA_INTERLEAVED 0x04

#define COMM_STATUS_RESYNC     0x01
#define COMM_STATUS_RETRANSMIT 0x02
#define COMM_STATUS_DONE       0x04
#define COMM_STATUS_ACK        0x08
#define COMM_STATUS_SYNCACK    0x10

 

typedef struct _commpacket_
{	
  
   COMM_PREHEAD preheader;
   KMGCLIENTENTRY Registration;
   KMGCOMMHEADER  Header;
   char Data[COMMDATABUFLEN];
} KAMRANGA_COMM_PACKET; 




#define MUTEX_WAIT_COUNT   2000

#define SERVER_ID_PARALLEL      0x01
#define SERVER_ID_MUTEX      0x02
#define SERVER_ID_MASTER     0x03
#define SERVER_ID_CLIENT     0x04

#define PARALLEL_SERVER_NOT_BUSY 0x01
#define PARALLEL_SERVER_COMMAND  0x02
#define SERVICE_SQL_COMMAND   0x03
#define PARALLEL_SERVER_BUSY     0x00

#define GET_PARALLEL_SERVER_PORT_NO 0x05
#define SET_PARALLEL_SERVER_PORT_NO 0x06
#define GET_MUTEX_SERVER_PORT_NO 0x07
#define SET_MUTEX_SERVER_PORT_NO 0x08
#define SERVICE_SQL_COMMAND_REPLY 0x04
#define SERVICE_SQL_COMMAND_REPLY_DONE 0x09

#define MUTEX_SYS_TABLE_READ    10
#define MUTEX_SYS_TABLE_WRITE   11
#define MUTEX_KMGACCSS_READ     12
#define MUTEX_KMGACCSS_WRITE    13
#define MUTEX_KMGLOCK_READ      14
#define MUTEX_KMGLOCK_WRITE     15
#define MUTEX_KMGINDEX_READ     16
#define MUTEX_KMGINDEX_WRITE    17
#define MUTEX_KMGGRP_READ       18
#define MUTEX_KMGGRP_WRITE      19
#define MUTEX_TABLE_READ        20
#define MUTEX_TABLE_WRITE       21
#define MUTEX_DBLIST_READ       22
#define MUTEX_DBLIST_WRITE      23
#define MUTEX_USER_RIGHT_READ   24
#define MUTEX_USER_RIGHT_WRITE  25
#define FREE_MUTEX              26
#define MUTEX_REQUEST_SUCCESS   27
#define MUTEX_REQUEST_FAILED    28
#define FREE_MUTEX_DONE         29
#define REGISTER_PARALLEL_SERVER   30
#define REGISTER_PARALLEL_SERVER_CONFIRMED   31
#define REGISTER_PARALLEL_SERVER_DENIED   32
#define MUTEX_HOSTLIST_READ       33
#define MUTEX_HOSTLIST_WRITE      34
#define MUTEX_USER_TRANS_READ   35
#define MUTEX_USER_TRANS_WRITE  36


#define ETHER_PACKET_LEN 1400
#define COMM_MAGIC_1 'K'
#define COMM_MAGIC_2 'M'
typedef struct _kmgbuftransmithdr_
{
	char magic1;
	char magic2;
	char flags;
	char status;
	char lastpacket;
	char reserved1[3];
	long uncompressedsize;
	long compressedsize;
	KINT64 reserved2;
	KINT64 bufno;
	KINT64 transmitno;
	KINT64 totalpkt;
    KINT64 datalen;
	KINT64 receiveid;
	KINT64 sendid;
	 
}KMGTRANSMITBUFFERHDR; 

#define KMG_MAX_TRANSMIT_BUFLEN (ETHER_PACKET_LEN - sizeof(KMGTRANSMITBUFFERHDR))

typedef struct _kmgbuftransmit_
{
 KMGTRANSMITBUFFERHDR hdr;	
 char data[KMG_MAX_TRANSMIT_BUFLEN];
}KMGTRANSMITBUFFER;

int GetKmgXmitBufSize(KMGTRANSMITBUFFER *xmitbuf);

#define KMG_PKTTYPE_KEEPALIVE 0x01
#define KMG_PKTTYPE_GET_CURSOR_ROW 0x02
#define KMG_PKTTYPE_DELETE_CURSOR 0x03
#define KMG_PKTTYPE_SQLCOMMAND 0x00

#define COMMPACKETLEN sizeof(struct _commpacket_)
KINT64 GetKmgMsgSize(KAMRANGA_COMM_PACKET *pkt);
KINT64 ReRegisterClient(KMGCLIENTENTRY *Entry);
KINT64 CompareClientRegistry(KMGCLIENTENTRY *,KMGCLIENTENTRY *);
KINT64 TransmitKmgLocalMsg(char *sqlcommand);
KINT64 ValidClientCommand(INTERNET_SQL_OBJECT *obj);
KINT64 TransmitKmgRemoteMsg(INTERNET_SQL_OBJECT *obj);
int KamrangaRemoteClientCommand(INTERNET_SQL_OBJECT *obj, char *command);
KINT64 StartKamrangaEngine(void);
void StopKamrangaEngine(void);
void SetKamrangaLocalClientMode(USERSLOT *slot);
void SetKamrangaRemoteClientMode(USERSLOT *slot);
int InitNetworkLink(USERSLOT *slot,KINT64 serveripnumber,int serverportnumber);
int InitNetwork(USERSLOT *slot);
void SetServerIP(USERSLOT *slot,KINT64 ipaddr);
void SetServerPort(USERSLOT *slot,int port);
KINT64 GetServerIP(USERSLOT *slot);
KINT64 GetServerPort(USERSLOT *slot);
char * GetHomeDir(USERSLOT *slot);
int  SetHomeDir(USERSLOT *slot,char *buf);

int ErrorInPacket(KAMRANGA_COMM_PACKET *pkt);


typedef struct transmit_parameters
{
 int transmitno;
 char all_ack_received;
 char  retransmit;
 int transmitcount;
 int pktlen;
 char *p;
 char resync;
 int t;
 char  compressed;
 char  more_to_transmit;
 char lastresponsetime[20];
 char currenttime[20];
 long sendcount;
 long recvcount;
 int error;
 char ack;
 long uncompressedsize;
 long compressedsize;
 int farendid;
 long totalpkt;
 long remains;
 int debugno;

} TRANSMIT_PARAMETERS;
typedef struct CallQueue
{
	int socket;
	char starttime[12];
	int trycount;
	char used;
	char last_response_time[16];
	char connect_time[16];
	char keep_alive_sent;
	long total_expected_packet;
	long total_received_packet;
    char receiveslot[1000];
    char transmitslot[1000];
	char *data;
	char *compressbuf;
	char compressed;
    char excess_buf[1500];
	int excess_data_count;
	int callindex;
    TRANSMIT_PARAMETERS TxVars;
    KMGTRANSMITBUFFER kmgrcvbuf;
    KMGTRANSMITBUFFER kmgxmitbuf;
    KMGTRANSMITBUFFERHDR kmgtxackbuf;
	KMGTRANSMITBUFFERHDR kmgrxackbuf;
#ifndef SUNUNIX
    struct sockaddr client_addr;
#else
    struct sockaddr client_addr;
#endif
    int kmgrcvbuf_count;
    USERSLOT *slot;
    struct CallQueue *next;
    struct CallQueue *prev;
} CLIENT_CALL_QUEUE;

#define MAX_CALL 1000
//CLIENT_CALL_QUEUE *ScanClientCall(CLIENT_CALL_QUEUE **head,  char *ClientMsg);
int ShowClientCalls(USERSLOT *slot,CLIENT_CALL_QUEUE *head);
CLIENT_CALL_QUEUE *ScanClientCall(USERSLOT *slot,CLIENT_CALL_QUEUE **head);
CLIENT_CALL_QUEUE *CreateClientCall(USERSLOT *slot,int socket,struct sockaddr *client_addr);
CLIENT_CALL_QUEUE *DequeueClientCall(USERSLOT *slot,CLIENT_CALL_QUEUE **head);
CLIENT_CALL_QUEUE *EnqueueClientCall(USERSLOT *slot,CLIENT_CALL_QUEUE **head,CLIENT_CALL_QUEUE *);
CLIENT_CALL_QUEUE *CreateClientCallQueue(USERSLOT *slot,CLIENT_CALL_QUEUE **head);
int DeleteClientCallQueue(USERSLOT *slot,CLIENT_CALL_QUEUE **head);
int DeleteClientCall(USERSLOT *slot,CLIENT_CALL_QUEUE **call);
typedef struct parallel_server_info
{
	char name[HOST_NAME_SIZE];
	int socket;
	int clientsocket;
    CLIENT_CALL_QUEUE *Call;    
    CLIENT_CALL_QUEUE *ClientCall;  
	char busy;
} PARALLEL_SERVER;



typedef struct 
  {
   KAM_INT32 prev;  
   KAM_INT32 next;
   KAM_INT32 msgsize;  //current msg size
   char *msgptr;    //msg buffer
   BYTE taskpriority;
   KAM_INT32 TaskId;
  } INTERMODULEMSGINFO; 

typedef struct 
 {
   KAM_INT32 msgcapacity;
   KAM_INT32 msgcount;
   KAM_INT32 msghead;
   KAM_INT32 msgbuflen;
   KAM_INT32 msgtail;
   char *MsgBuffer;
   INTERMODULEMSGINFO *InfoArray;
   char accessflag;
 }INTERMODULEMSGHEAD;

#define WAIT_FOREVER 0xFFFFFFFF
#define MAX_CLIENT_WAIT 0x0000FFFF

#define MSG_URGENT          0x02 //post the msg at head of the q immediately
#define MSG_SEMIURGENT      0x01 //post the msg right before current msg in progress
#define MSG_WAIT_UNTIL_PROCESSED  0x04 //send msg function do not return until this msg is processed
#define MSG_NOTURGENT       0x00 //post the msg at the end of the q
#define MSG_NORMAL          0x00 //post the msg at the end of the q
#define MSG_NOTPROCESSED    0x80 //msg not processed yet
#define MSG_PRIORITYENFORCE 0x40 //enforce priority privilages while pushing the msg
typedef struct _KamrangaMsg_
{
 KINT64  a; //reserve bytes for future
 KINT64  b; //reserve bytes for future
 KINT64  c; //reserve bytes for future
 KINT64  d; //reserve bytes for future
 UKINT64 RegNo; //registration number  
 unsigned short int e;//reserve bytes for future
 char  username[32];
 char  lockgranted;
}KMGMSGQ;  //32 bytes




//---------------------------------------
int InsertDatabaseName(INTERNET_SQL_OBJECT *obj,char *databasename,char *ipstring,char *portstring,char storagetype='N',char *containersize=(char *)"0",char autoextend='F'); /* task #70: container storage */
void SetServerMode(USERSLOT *slot);
void SetClientMode(USERSLOT *slot);
int InClientMode(USERSLOT *slot);


typedef struct 
{
  short int  day;
  short int  month;
  short int year;
  short  dayofweek;
  short int century;
}KAM_DATE_STRUCT;
 
typedef struct 
{
  short int  hour;
  short int  min;
  short int sec;
  short  int hundreth;
}KAM_TIME_STRUCT;
int  KAM_GetTime(KAM_TIME_STRUCT *ts);
char *TimeToChar(char *timenumber, char *timeout);
char  *CharToTime(char *timestring,char *cleantime);
int CompareTime(char *timea,char timeb);
int MinuteDiff(KAM_TIME_STRUCT *a,KAM_TIME_STRUCT *b);
int GetHourDiff(KAM_TIME_STRUCT *a,KAM_TIME_STRUCT *b);
int GetSecDiff(KAM_TIME_STRUCT *a,KAM_TIME_STRUCT *b);
char *GetSystemTime(char *string);
int ExecTimeOK(char *lastdate,char *lasttime, char *curdate,char *time,int timeoutval,char *timeunit);





typedef struct diskstruct
 {
  KINT64  avail_clusters;
  KINT64  total_clusters;
  KINT64  sectors_per_cluster;
  KINT64  bytes_per_sector;
 }KAM_DISK_STRUCT;

typedef struct file_transfer
{
	char srcpath[256];
	char destpath[256];
	char tablename[256];
	char data[512];
	KINT64 offset;
	KINT64 size;
} FILE_TRANSFER;
typedef struct path_list
{
  FIELD_NAME_LIST *path;
  struct path_list *next;
  struct path_list *prev;
} PATH_LIST ;
PATH_LIST *AddPathList(PATH_LIST **pathlist, FIELD_NAME_LIST *path);
void FreePathList(PATH_LIST **);

typedef struct
{
  char name[64];
  char execinterval[64];
  char command[65536];
  char auto_id[32];
  char username[64];
  char password[PWD_BUF_LENGTH];
  char databasename[256];
  char userpwr[64];
  char KmgUserNo[64];
  char KmgMgrName[64];
  char KmgGroupName[64];
  char KmgUserDbName[64];
  char DebugMode[64];
  char CursorMode[64];
  char startdate[64];
  char expiredate[64];
  char starttime [64]; 
  char expiretime[64];
  char execintervalunit[64];
  char enabled[64];
  char locked[64];
  char lockedby[64];
  char transmitoutputflag[64];
  char transmitip[64];
  char transmitport[64];
  char allaccess[32];
  char groupaccess[32];
}
BACKGROUND_CMD;
#endif
int     WaitForLockPermit(UKINT64 wait);
void LoadSuperUserInfo(INTERNET_SQL_OBJECT *obj);
void  ClearLockPermit(void);
void  CloseQueryTables(MAINSELECT *ms);
void  CloseQueryBuffers(MAINSELECT *ms);
KAM_INT32 CreateModuleMsgQ(KAM_INT32 msgsize,INT16 elementcount);
INT16 GetModuleMsgQSize(KAM_INT32 qid);
KAM_INT32 TransmitMsg(KAM_INT32 qid,char *msg,KAM_INT32 msglen,char priority,UKINT64 timeout);
KAM_INT32 ReceiveMsg(KAM_INT32 qid,char *msg,KAM_INT32 msgbufsize,UKINT64 timeout);
KAM_INT32 DeleteModuleMsgQ(KAM_INT32 qid);
KAM_INT32 LookForMsg(KAM_INT32 qid, KMGCLIENTENTRY *cliententry);
KINT64  SetServerStartTime(KAM_INT32*,KAM_INT32 *, KINT64 *);
int   WaitForFlag(char *flag,UKINT64 timeout);
int   LoadDynamicLibrary(void);
int   UnLoadDynamicLibrary(void);
int   RegisterClient(KMGCLIENTENTRY *cliententry);
void ClearAllQueryObjects(INTERNET_SQL_OBJECT *obj);
void FreeAllQueryObjects(INTERNET_SQL_OBJECT *obj);

QUERYRESULTOBJECT GetLastQryObject(INTERNET_SQL_OBJECT *obj);


KINT64 CurrentQueryRowCount(INTERNET_SQL_OBJECT *obj);
QUERYITEMSLIST  GetRunTimeQueryItems(INTERNET_SQL_OBJECT *obj);
KINT64 GetRunTimeQueryCount(INTERNET_SQL_OBJECT *obj);
KINT64 GetRunTimeQueryRowLength(INTERNET_SQL_OBJECT *obj);
KINT64 GetQueryItemsCount(QUERYITEMSLIST itemlist);
void CloseAllFromTables(MAINSELECT *ms);

QUERYRESULTOBJECT GetQueryResultObject(INTERNET_SQL_OBJECT *obj);

CURSOR GetQueryCursor(INTERNET_SQL_OBJECT *obj);
void ReleaseCursor(CURSOR *cursor);
KINT64 GetCursorRowCount(CURSOR cursor);
KINT64 GetCursorRowLength(CURSOR cursor);
CURSORROW  GetCursorRow(CURSOR cursor,KINT64 rowno);
int GetCursorField(CURSORROW cursor_row,char *fieldname,char *value);
int SetCursorField(CURSORROW cursor_row,char *fieldname,char *value);
int  UpdateCursorRow(CURSOR cursor,CURSORROW cursor_row,KINT64 rowno);
int  CursorRowSetMark(CURSOR cursor,KINT64 rowno, int mark);
int  CursorRowClearMark(CURSOR cursor,KINT64 rowno, int mark);
void ReleaseCursor(void);
char GetCursorFieldType(CURSORROW cursor_row,char *fieldname);
KINT64 GetCursorFieldLength(CURSORROW cursor_row,char *fieldname);
KINT64 GetCursorFieldDecPos(CURSORROW cursor_row,char *fieldname);
KINT64 GetCursorFieldNumber(CURSORROW cursor_row,char *fieldname);

int TestMark(int value, int mark);

QUERYITEMSLIST  GetQueryRow(QUERYRESULTOBJECT qry,KINT64 rowno);
QUERYITEMSLIST  GetQueryItems(QUERYRESULTOBJECT qry);
QUERYITEMSLIST  GetCursorRow(QUERYRESULTOBJECT qry,KINT64 rowno);
QUERYITEMSLIST  GetCursorItems(QUERYRESULTOBJECT qry);
int MoveRow(QUERYRESULTOBJECT qry,KINT64 from,KINT64 to);
int SwapRow(QUERYRESULTOBJECT qry,KINT64 first,KINT64 second);


KINT64 GetQueryResultCount(QUERYRESULTOBJECT qry);
KINT64 GetQueryResultRowLength(QUERYRESULTOBJECT qry);
QUERYITEMSLIST  GetQueryResultRow(QUERYRESULTOBJECT qry,KINT64 rowno);
QUERYITEMSLIST  GetQueryResultItems(QUERYRESULTOBJECT);
int UnLockDatabase(INTERNET_SQL_OBJECT *obj,char *databasename);
int LockDatabase(INTERNET_SQL_OBJECT *obj,char *databasename);
int  SendDeleteCursorMessageToServer(QUERYRESULTOBJECT qryobject);
void FreeQueryResultObject(INTERNET_SQL_OBJECT *obj,QUERYRESULTOBJECT *qryobject);
void FreeCurrentQueryResultObject(INTERNET_SQL_OBJECT *obj);

char   CopyItemString(QUERYITEMSLIST qitemlist,char * fieldname,char *buffer);
char   GetItem(QUERYITEMSLIST qitemlist,char *fieldname,char *buffer);
char   *GetItemString(QUERYITEMSLIST qitemlist,char *fieldname);
KINT64   GetItemInt(QUERYITEMSLIST qitemlist,char *fieldname);
KDOUBLE GetItemDouble(QUERYITEMSLIST qitemlist,char *fieldname);

char  CopyItemString(QUERYITEMSLIST qitemlist,int fieldno,char *buffer);
char   GetItem(QUERYITEMSLIST qitemlist,int fieldno,char *buffer);
char   *GetItemString(QUERYITEMSLIST qitemlist,int fieldno);
KINT64   GetItemInt(QUERYITEMSLIST qitemlist,int fieldno);
KDOUBLE GetItemDouble(QUERYITEMSLIST qitemlist,int fieldno);

KINT64 GetQueryItemsCount(QUERYITEMSLIST rec);
char *GetItemName(int itemno);
char  GetItemType(int itemno);
char  GetItemNotNull(int itemno);
char  GetItemKeyType(int itemno);
char  GetItemAutoInc(int itemno);
char  GetItemUnique(int itemno);

KINT64  GetItemLength(int itemno);
KINT64  GetItemDecPos(int itemno);

char  GetItemType(char *fieldname);
char  GetItemNotNull(char *fieldname);
char  GetItemKeyType(char *fieldname);
char  GetItemAutoInc(char *fieldname);
char  GetItemUnique(char *fieldname);
KINT64  GetItemLength(char *fieldname);
KINT64  GetItemDecPos(char *fieldname);
KINT64  GetItemNo(char *fieldname);


char *GetItemName(QUERYITEMSLIST rec,int itemno);
char  GetItemType(QUERYITEMSLIST rec,int itemno);
char  GetItemNotNull(QUERYITEMSLIST rec,int itemno);
char  GetItemAutoInc(QUERYITEMSLIST rec,int itemno);
char  GetItemUnique(QUERYITEMSLIST rec,int itemno);
char  GetItemKeyType(QUERYITEMSLIST rec,int itemno);
int  GetItemMaxBytesUsed(QUERYITEMSLIST rec,int itemno);

KINT64  GetItemLength(QUERYITEMSLIST rec,int itemno);
KINT64  GetItemDecPos(QUERYITEMSLIST rec,int itemno);

char  GetItemType(QUERYITEMSLIST rec,char *fieldname);
char  GetItemNotNull(QUERYITEMSLIST rec,char *fieldname);
char  GetItemKeyType(QUERYITEMSLIST rec,char *fieldname);
char  GetItemAutoInc(QUERYITEMSLIST rec,char *fieldname);
char  GetItemUnique(QUERYITEMSLIST rec,char *fieldname);
long GetItemMaxBytesUsed(QUERYITEMSLIST rec,char *fieldname);
KINT64  GetItemLength(QUERYITEMSLIST rec,char *fieldname);
KINT64  GetItemDecPos(QUERYITEMSLIST rec,char *fieldname);
KINT64  GetItemNo(QUERYITEMSLIST rec,char *fieldname);



int KamrangaRdbmsCommand(INTERNET_SQL_OBJECT *obj, char *command);
int KamrangaDbmsCommand(char *command);
KINT64 CreateDatabase(char *dbnane,char *password,KDOUBLE sizeinmb);
TRANSACTIONTABLE *CreateTransTable(INTERNET_SQL_OBJECT *obj,char *table,KINT64 systablerecno,char makeentry);
TRANSACTIONTABLE *FindTransTable(INTERNET_SQL_OBJECT *obj,char *tablename);
KINT64 InsertTransTableName(INTERNET_SQL_OBJECT *obj,char *tablename,KINT64 systablerecno);
KINT64 DeleteTransTable(INTERNET_SQL_OBJECT *obj,TRANSACTIONTABLE *tt);
KINT64 FindTransRecNo(INTERNET_SQL_OBJECT *obj,TRANSACTIONTABLE *tt,KINT64 recno);
KINT64 AddToTansTable(INTERNET_SQL_OBJECT *obj,TRANSACTIONTABLE *tt,KINT64 recno);
int  SQLListCommand(INTERNET_SQL_OBJECT *obj);
int  SQLGetCommand(INTERNET_SQL_OBJECT *obj);
char SQLSelect(INTERNET_SQL_OBJECT *obj);
char SQLRecognize(INTERNET_SQL_OBJECT *obj);
char SQLVector(INTERNET_SQL_OBJECT *obj);
char SQLVectorInsert(INTERNET_SQL_OBJECT *obj);
char SQLRecoverTable(INTERNET_SQL_OBJECT *obj);
char SQLDropview(INTERNET_SQL_OBJECT *obj);
char SQLDropTable(INTERNET_SQL_OBJECT *obj);
char SQLindex(INTERNET_SQL_OBJECT *obj);
char SQLAlterTable(INTERNET_SQL_OBJECT *obj);
char SQLInsert(INTERNET_SQL_OBJECT *obj);
char SQLZap(INTERNET_SQL_OBJECT *obj);
char SQLWriteStorage(INTERNET_SQL_OBJECT *obj);
char SQLReadStorage(INTERNET_SQL_OBJECT *obj);
char SQLUpload(INTERNET_SQL_OBJECT *obj);
char SQLDownload(INTERNET_SQL_OBJECT *obj);
char SQLExport(INTERNET_SQL_OBJECT *obj);
char SQLImport(INTERNET_SQL_OBJECT *obj);
int  ListDatabase(INTERNET_SQL_OBJECT *obj);
KINT64 GetRecordFieldsCount(RECORDLIST rec);
int  ListLocks(INTERNET_SQL_OBJECT *obj,char *tablename,char *locktype);
int ListIndexKey(INTERNET_SQL_OBJECT *obj,char *indexname);
int ListIndexInfo(INTERNET_SQL_OBJECT *obj,char *indexname);
void KmgUserTempFileName(INTERNET_SQL_OBJECT *obj,char *filename,char *tmpfilename);
char  RemoveLockForThisTable(INTERNET_SQL_OBJECT *obj,char *tablename);
int  ListPrivileges(INTERNET_SQL_OBJECT *obj,char *username);
KINT64 GroupNameExist(INTERNET_SQL_OBJECT *obj,char *grpname);
int  ListIndex(INTERNET_SQL_OBJECT *obj,char *tablename,char *indexname);
int  ShowAllUsers(INTERNET_SQL_OBJECT *obj);
int  ShowUserInfo(INTERNET_SQL_OBJECT *obj,char *username);
int SQLUnLockGroup(INTERNET_SQL_OBJECT *obj);
int SQLLockGroup(INTERNET_SQL_OBJECT *obj);
int UnLockGroup(INTERNET_SQL_OBJECT *obj,char *groupname);
int LockGroup(INTERNET_SQL_OBJECT *obj,char *groupname);
void RemoveKeyFromIndexTable(TABLE tbl,KEYLIST kl);
char SQLLogin(INTERNET_SQL_OBJECT *obj);
char SQLLogout(INTERNET_SQL_OBJECT *obj);
char SQLRemoteCommand(INTERNET_SQL_OBJECT *obj);
char SQLGrant(INTERNET_SQL_OBJECT *obj);
char SQLRevoke(INTERNET_SQL_OBJECT *obj);
char SQLExpandDatabase(INTERNET_SQL_OBJECT *obj);
char SQLLock(INTERNET_SQL_OBJECT *obj);
char SQLUnLock(INTERNET_SQL_OBJECT *obj);
char SQLChangeUserStat(INTERNET_SQL_OBJECT *obj);
char SQLConnect(INTERNET_SQL_OBJECT *obj);
char SQLDisConnect(INTERNET_SQL_OBJECT *obj);
char SQLAddUser(INTERNET_SQL_OBJECT *obj);
char SQLCreateSuperUser(INTERNET_SQL_OBJECT *obj);
char SQLDropUser(INTERNET_SQL_OBJECT *obj);
char SQLRollBack(INTERNET_SQL_OBJECT *obj);
char SQLCommit(INTERNET_SQL_OBJECT *obj);
char SQLRecoverView(INTERNET_SQL_OBJECT *obj);
char SQLCreateTable(INTERNET_SQL_OBJECT *obj);
/* #72 module 3.6b: VLR SQL handlers (vlrsql.cpp), short-circuited from the stock
 * handlers when GlobalCfg.VlrEnabled and the statement/table is VLR. */
char SQLCreateVlrTable(INTERNET_SQL_OBJECT *obj);
int  VlrClauseInCommand(const char *cmd);
int  IsqlTableIsVlr(INTERNET_SQL_OBJECT *obj, const char *relpath);
char SQLCreateDatabase(INTERNET_SQL_OBJECT *obj);
char SQLAlter(INTERNET_SQL_OBJECT *obj);
char SQLUpdate(INTERNET_SQL_OBJECT *obj);
char SQLCreateIndex(INTERNET_SQL_OBJECT *obj);
char SQLview(INTERNET_SQL_OBJECT *obj);
char SQLCreateCursor(INTERNET_SQL_OBJECT *obj);
char SQLDelete(INTERNET_SQL_OBJECT *obj);
char SQLUndelete(INTERNET_SQL_OBJECT *obj);
char SQLDeleteTable(INTERNET_SQL_OBJECT *obj);
char SQLDeleteView(INTERNET_SQL_OBJECT *obj);
char SQLDeleteIndex(INTERNET_SQL_OBJECT *obj);
char SQLReindex(INTERNET_SQL_OBJECT *obj);
char SQLDropIndex(INTERNET_SQL_OBJECT *obj);
char SQLRecoverIndex(INTERNET_SQL_OBJECT *obj);
char SQLUndelete(INTERNET_SQL_OBJECT *obj);
char SQLInclude(INTERNET_SQL_OBJECT *obj);
char SQLPack(INTERNET_SQL_OBJECT *obj);
char SQLDescribe(INTERNET_SQL_OBJECT *obj);
char SQLLockDatabase(INTERNET_SQL_OBJECT *obj);
char SQLUnLockDatabase(INTERNET_SQL_OBJECT *obj);
char SQLShow(INTERNET_SQL_OBJECT *obj);
char SQLShowUserAccountSummary(INTERNET_SQL_OBJECT *obj);
char SQLSetCommand(INTERNET_SQL_OBJECT *obj); 
int SQLHelp(INTERNET_SQL_OBJECT *obj);


void ClearQuery(INTERNET_SQL_OBJECT *obj,MAINSELECT **ms);
void SetSlotQryError(USERSLOT *slot,int errorcode,char *error);
void SetQryError(INTERNET_SQL_OBJECT *obj,int errorcode,char *error);

char SuperUserExists(INTERNET_SQL_OBJECT *obj);
char AddKmgSuperUser(INTERNET_SQL_OBJECT *obj,char *username,char *password);


void CloseQryOutPut(INTERNET_SQL_OBJECT *obj);
long GetSqlError(INTERNET_SQL_OBJECT *obj);
char *GetSqlQueryStat(INTERNET_SQL_OBJECT *obj);
char *GetInstanceStat(USERSLOT *slot);
void InstallQryFunc(USERSLOT *slot,long(*)(void));
void InstallQryItemFunc(USERSLOT *slot,long(*)(void));
void InstallQueryFunction(USERSLOT *slot,long (*)(void));
TABLE CreateGroupByOutPutTable(RECORDLIST,char *);
KINT64 IndexTableRevoked(INTERNET_SQL_OBJECT *obj);
KINT64 CreateTableRevoked(INTERNET_SQL_OBJECT *obj);
KINT64 AlterTableRevoked(INTERNET_SQL_OBJECT *obj,char *tablename);
KINT64 CreateViewRevoked(INTERNET_SQL_OBJECT *obj);
KINT64 KmgTableLocked(LOCKINFO*);
KINT64 KmgTableLocked(FROMTABLE*);
KINT64 KmgRecordLocked(FROMTABLE*,KINT64 recno);
KINT64 KmgRecordLocked(LOCKINFO*,KINT64 recno);
KINT64 SelectionRevoked(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms);
KINT64 SubSelectionRevoked(INTERNET_SQL_OBJECT *obj,SUBSELECT *ss);
KINT64 UnDeleteFromRevoked(INTERNET_SQL_OBJECT *obj,char *table,RECORDRANGE *rr);
KINT64 DeleteFromRevoked(INTERNET_SQL_OBJECT *obj,char *table,RECORDRANGE *rr);

KINT64 PrepareLockInfo(MAINSELECT *ms);
KINT64 CreateLockInfo(INTERNET_SQL_OBJECT *obj,char *table,LOCKINFO **lock);
KINT64 DeleteLockInfo(LOCKINFO **);
KINT64 TableDeleteRevoked(void);
KINT64 TableUpdateRevoked(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms,RECORDRANGE *rr);
KINT64 TableDeleteFromDiskRevoked(INTERNET_SQL_OBJECT *obj,char *table);
KINT64 ViewDeleteRevoked(INTERNET_SQL_OBJECT *obj,char *viewname);
KINT64 DropIndexRevoked(INTERNET_SQL_OBJECT *obj,char *indexname);
KINT64 DeleteIndexRevoked(INTERNET_SQL_OBJECT *obj,char *indexname);
KINT64 ReIndexRevoked(INTERNET_SQL_OBJECT *obj);
KINT64 DropViewRevoked(INTERNET_SQL_OBJECT *obj,char *viewname);
KINT64 DropTableRevoked(INTERNET_SQL_OBJECT *obj,char *tablename);
KINT64 RecoverTableRevoked(INTERNET_SQL_OBJECT *obj,char *tablename);
KINT64 RecoverViewRevoked(INTERNET_SQL_OBJECT *obj,char *viewname);
KINT64 CreateDatabaseRevoked(INTERNET_SQL_OBJECT *obj);
KINT64 InsertRevoked(INTERNET_SQL_OBJECT *obj,char *tablename);
KINT64 IncludeRevoked(INTERNET_SQL_OBJECT *obj);
KINT64 PackRevoked(INTERNET_SQL_OBJECT *obj);
KINT64 LockRightRevoked(INTERNET_SQL_OBJECT *obj,char *tablename);
KINT64 SelectRevoked(INTERNET_SQL_OBJECT *obj);
KINT64 UserDidThisLock(LOCKINFO *linfo,int locktype ,KINT64 from,KINT64 to);
KINT64 GrantRevoked(INTERNET_SQL_OBJECT *obj);
KINT64 RevokeRevoked(INTERNET_SQL_OBJECT *obj);
KINT64 OpenUserRightsTable(INTERNET_SQL_OBJECT *obj,char *username,char pwr);
int CheckSuperUserInDefault(INTERNET_SQL_OBJECT *obj,char *username,char *password,char *pwr,int *useridfound);
char KmgLogout(INTERNET_SQL_OBJECT *obj);
KINT64 KmgNewRecAddLocked(LOCKINFO *linfo);
char LockKmgTable(INTERNET_SQL_OBJECT *obj,LOCKINFO **linfo,char *tablename,KINT64 from , KINT64 to,char *locktype,char *lockedbysystemengine);
TABLE LoadTableReadLockInfo(INTERNET_SQL_OBJECT *obj,char *table,LOCKINFO **lock);
char ClearLockKmgTable(INTERNET_SQL_OBJECT *obj,
					   LOCKINFO *,
                       char *tablename,
                       KINT64 from , 
                       KINT64 to,
                       char *locktype,
                       char *lockedbysystemengine);
char UnLockKmgTable(INTERNET_SQL_OBJECT *obj,
					LOCKINFO *linfo,
                       char *tablename
                       ); //it is the system lock not the user lock
KINT64 KmgLockDelay(void);
LOCKINFO * SetInsertLock(INTERNET_SQL_OBJECT *obj,char *tablename);
LOCKINFO * SetUpdateLock(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms,RECORDRANGE *rr);
LOCKINFO * SetDeleteLock(INTERNET_SQL_OBJECT *obj,char *tablename);
LOCKINFO * SetUnDeleteLock(INTERNET_SQL_OBJECT *obj,char *tablename);
LOCKINFO * SetSelectLock(INTERNET_SQL_OBJECT *obj,char *tablename);
LOCKINFO * SetPackLock(INTERNET_SQL_OBJECT *obj,char *tablename);
KINT64 LockSystemAccessControl(INTERNET_SQL_OBJECT *obj);
KINT64 UnLockSystemAccessControl(INTERNET_SQL_OBJECT *obj);
KINT64 UnLockSystemLocks(INTERNET_SQL_OBJECT *obj);
KINT64 UnLockUserLocks(INTERNET_SQL_OBJECT *obj);
char KmgCommit(INTERNET_SQL_OBJECT *obj);
KINT64 RunKamrangaNetworkAgent(void);
KINT64 StopKamrangaNetworkAgent(void);
KINT64 StartKamrangaSqlEngine(USERSLOT *,char *dbhomedir,char *serverip,char * serverport);
KINT64 StartInternetSql(USERSLOT *,char *dbhomedir,char *serverip,char * serverport);
KINT64 StopKamrangaSqlEngine(KINT64 startid);
KINT64 StopInternetSql(KINT64 startid);
int SendSqlClientCommPacket(USERSLOT *slot,CLIENT_CALL_QUEUE *remotecall,char *buffer, int bufsize);
int SendSqlClientCommPacketWithWait(USERSLOT *slot,int socket,char *buffer, int bufsize,int waitcount);
int ReceiveSqlClientCommPacket(USERSLOT *slot,CLIENT_CALL_QUEUE *remotecall, char * buffer, int bufsize); 
int ReceiveSqlClientCommPacketWithWait(USERSLOT *slot,int socket, char * buffer, int bufsize,int waitcount); 

int SendSqlServerCommPacket(USERSLOT *slot,CLIENT_CALL_QUEUE *remotecall,char *buffer, int bufsize);
int ReceiveSqlServerCommPacket(USERSLOT *slot,CLIENT_CALL_QUEUE *remotecall, char * buffer, int bufsize); 
int ReceiveSqlServerCommPacketNoWait(USERSLOT *slot,CLIENT_CALL_QUEUE *remotecall, char * buffer, int bufsize); 

TABLE OpenUserTransTbl(char *username);
KINT64 ClearInsertLock(INTERNET_SQL_OBJECT *obj,LOCKINFO * linfo, char *tablename);
KINT64 ClearUpdateLock(INTERNET_SQL_OBJECT *obj,LOCKINFO *linfo, MAINSELECT *ms,RECORDRANGE *RecordRange);
char MarkRevokedField(FIELD_NAME_LIST *flist,char *fieldname);
KINT64  CommitUser(INTERNET_SQL_OBJECT *obj,char *username);
KINT64  RemoveUserDir(INTERNET_SQL_OBJECT *obj,char *username);
//---------------------------------------------
KINT64 UnLockKmgLock(INTERNET_SQL_OBJECT *obj);
KINT64 LockKmgLock(void);
LOCKINFO * FindReUsableLockRecord(LOCKINFO *);
//-------------------------------------------------------------------------------
char RevokeChangePower(INTERNET_SQL_OBJECT *obj,char *username);
char RevokeReindexPower(INTERNET_SQL_OBJECT *obj,char *username);
char RevokeRecoverTablePower(INTERNET_SQL_OBJECT *obj,char *username,char *tablename);
char RevokeRecoverViewPower(INTERNET_SQL_OBJECT *obj,char * user ,char *viewname);
char RevokeInsertPower(INTERNET_SQL_OBJECT *obj,char *username,char *tablename);
char RevokeIncludePower(INTERNET_SQL_OBJECT *obj,char *username);
char RevokePackPower(INTERNET_SQL_OBJECT *obj,char *user);
char RevokeDeleteFromPower(INTERNET_SQL_OBJECT *obj,char *username,char *tablename,KINT64 from ,KINT64 to);
char RevokeTableDeletePower(INTERNET_SQL_OBJECT *obj,char *user,char *table);
char RevokeTableDeleteFromDiskPower(INTERNET_SQL_OBJECT *obj,char *tablename);
char RevokeViewDeletePower(INTERNET_SQL_OBJECT *obj,char *username,char *viewname);
char RevokeDeleteIndexPower(INTERNET_SQL_OBJECT *obj,char *user,char *indexname);
char RevokeUnDeleteFromPower(INTERNET_SQL_OBJECT *obj,char *user,char *tablename,KINT64 from,KINT64 to);
char RevokeTableUpdatePower(INTERNET_SQL_OBJECT *obj,char *username,char allfields,char *tablename,KINT64 from,KINT64 to, FIELD_NAME_LIST *flist);
char RevokeAddUserPower(INTERNET_SQL_OBJECT *obj,char *username);
char RevokeSelectPower(INTERNET_SQL_OBJECT *obj,char *user,int token,FIELD_NAME_LIST * ,char *tablename);
char RevokeDropViewPower(INTERNET_SQL_OBJECT *obj,char *username,char *viewname);
char RevokeDropTablePower(INTERNET_SQL_OBJECT *obj,char *username,char *table);
char RevokeDropIndexPower(INTERNET_SQL_OBJECT *obj,char *index,char *indexname);
char RevokeAlterTablePower(INTERNET_SQL_OBJECT *obj,char *user,char *tablename);
char RevokeLockPower(INTERNET_SQL_OBJECT *obj,char *user,char *tablename);
char RevokeUnLockPower(INTERNET_SQL_OBJECT *obj,char *user,char *tablename);
char RevokeCreateTablePower(INTERNET_SQL_OBJECT *obj,char *user);
char RevokeCreateViewPower(INTERNET_SQL_OBJECT *obj,char *user);
char RevokeCreateDatabasePower(INTERNET_SQL_OBJECT *obj,char *user);
char RevokeCreateIndexPower(INTERNET_SQL_OBJECT *obj,char *user);
char RevokeGrantPower(INTERNET_SQL_OBJECT *obj,char *user);
char RevokeRevokePower(INTERNET_SQL_OBJECT *obj,char *user);
char RevokeLoginPower(INTERNET_SQL_OBJECT *obj,char *user);
char RevokeExpandDatabasePower(INTERNET_SQL_OBJECT *obj,char *user);
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
char GrantAll(INTERNET_SQL_OBJECT *obj,char *username);
char GrantChangePower(INTERNET_SQL_OBJECT *obj,char *username);
char GrantReindexPower(INTERNET_SQL_OBJECT *obj,char *username);
char GrantRecoverTablePower(INTERNET_SQL_OBJECT *obj,char *username,char *tablename);
char GrantRecoverViewPower(INTERNET_SQL_OBJECT *obj,char * user ,char *viewname);
char GrantInsertPower(INTERNET_SQL_OBJECT *obj,char *username,char *tablename);
char GrantIncludePower(INTERNET_SQL_OBJECT *obj,char *username);
char GrantPackPower(INTERNET_SQL_OBJECT *obj,char *user);
char GrantDeleteFromPower(INTERNET_SQL_OBJECT *obj,char *username,char *tablename,KINT64 from ,KINT64 to);
char GrantTableDeletePower(INTERNET_SQL_OBJECT *obj,char *user,char *table);
char GrantTableDeleteFromDiskPower(INTERNET_SQL_OBJECT *obj,char *tablename);
char GrantViewDeletePower(INTERNET_SQL_OBJECT *obj,char *username,char *viewname);
char GrantDeleteIndexPower(INTERNET_SQL_OBJECT *obj,char *user,char *indexname);
char GrantUnDeleteFromPower(INTERNET_SQL_OBJECT *obj,char *user,char *tablename,KINT64 from,KINT64 to);
char GrantTableUpdatePower(INTERNET_SQL_OBJECT *obj,char *user,char allfields,char *table,KINT64 from,KINT64 to, FIELD_NAME_LIST *);
char GrantAddUserPower(INTERNET_SQL_OBJECT *obj,char *username);
char GrantSelectPower(INTERNET_SQL_OBJECT *obj,char *user,int token,FIELD_NAME_LIST *,char *tablename);
char GrantDropViewPower(INTERNET_SQL_OBJECT *obj,char *username,char *viewname);
char GrantDropTablePower(INTERNET_SQL_OBJECT *obj,char *username,char *table);
char GrantDropIndexPower(INTERNET_SQL_OBJECT *obj,char *index,char *indexname);
char GrantAlterTablePower(INTERNET_SQL_OBJECT *obj,char *user,char *tablename);
char GrantLockPower(INTERNET_SQL_OBJECT *obj,char *user,char *tablename);
char GrantUnLockPower(INTERNET_SQL_OBJECT *obj,char *user,char *tablename);
char GrantCreateTablePower(INTERNET_SQL_OBJECT *obj,char *user);
char GrantCreateViewPower(INTERNET_SQL_OBJECT *obj,char *user);
char GrantCreateDatabasePower(INTERNET_SQL_OBJECT *obj,char *user);
char GrantCreateIndexPower(INTERNET_SQL_OBJECT *obj,char *user);
char GrantGrantPower(INTERNET_SQL_OBJECT *obj,char *user);
char GrantRevokePower(INTERNET_SQL_OBJECT *obj,char *user);
char GrantLoginPower(INTERNET_SQL_OBJECT *obj,char *user);
char GrantExpandDatabasePower(INTERNET_SQL_OBJECT *obj,char *user);
//-------------------------------------------------------------------------------
//--------------------------------------
void SetKmgTryCount(KINT64 count);
void KmgTaskDelay(KINT64 delay);
char EnableUseDynamicLibrary(void);
char DisableUseDynamicLibrary(void);
char DisableRemoteServerOptions(void);
char EnableRemoteServerOptions(void);
char DisableAutoSystemLocking(void);
char EnableAutoSystemLocking(void);
char DisableGrantRevokeChecking(void);
char EnableGrantRevokeChecking(void);
char DisableCommitRollBacking(void);
char EnableCommitRollBacking(void);

KINT64 StartKamrangaServer(void);
//-------------------------------------------------------------------------------
int ChangeGroupName(INTERNET_SQL_OBJECT *obj);
int ChangeGroupManager(INTERNET_SQL_OBJECT *obj);

TABLE CreateGroupTable(INTERNET_SQL_OBJECT *obj);
TABLE CreateLockTable(INTERNET_SQL_OBJECT *obj);
char GoToDatabaseDir(INTERNET_SQL_OBJECT *obj);
char GotoDatabaseHome(INTERNET_SQL_OBJECT *obj,char *dbhomedir,char *serverip,char * serverport);
int VerifySystemTables(INTERNET_SQL_OBJECT *obj);
char VerifyDatabaseList(INTERNET_SQL_OBJECT *obj);
KINT64 VerifyLogin(INTERNET_SQL_OBJECT *obj);
KINT64 OtherUserLockedThisRange(char *tablename,KINT64 from,KINT64 to);
KINT64 UserLockedThisTable(char *tablename);
KINT64 LockRightRevoked(char *tablename);
KINT64 GetSysTableUseCount(char *tablename);
KINT64 IncSysTableUseCount(char *tablename);
KINT64 DecSysTableUseCount(char *tablename);
KINT64 LockSysTableUse(INTERNET_SQL_OBJECT *obj);
KINT64 UnLockSysTableUse(INTERNET_SQL_OBJECT *obj);
KINT64 LockSysTableUse(INTERNET_SQL_OBJECT *obj,char *tablename);
KINT64 UnLockSysTableUse(INTERNET_SQL_OBJECT *obj,char *tablename);
KINT64 SysTableUseLocked(INTERNET_SQL_OBJECT *obj);
KINT64 SysTableUseLocked(INTERNET_SQL_OBJECT *obj,char * tablename);
void  DeleteObject(TABLEOBJECT *mem);
void  DeleteObject(FIELDOBJECT *mem);
void  DeleteObject(RECORDOBJECT *mem);
void  DeleteObject(LOGOBJECT *mem);
void  DeleteObject(INDEXOBJECT *mem);
void DeleteObject(KEYOBJECT *mem);
void DeleteObject(__postfixlink__ *mem);
void DeleteObject(LISTOBJECT *mem);
void DeleteObject(__sysvartable__ *mem);
char MapGroupByRecordData(RECORDLIST GroupByRecList,RECORDLIST NormalRecList);
char CopySqlQryGroupByRecordData(RECORDLIST GroupByRecList,RECORDLIST NormalRecList);
char MakeGroupByKeyList(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms);
char MakeOrderByKeyList(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms);
char MakeDistinctKeyList(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms);
KEYLIST CreateGroupByKeyList(INTERNET_SQL_OBJECT *obj,GROUPITEM *gi);
KEYLIST CreateOrderByKeyList(INTERNET_SQL_OBJECT *obj,ORDERITEM *gi);
KEYLIST CreateSelectItemKeyList(INTERNET_SQL_OBJECT *obj,RECORDLIST rl);
char FindFieldNames(INTERNET_SQL_OBJECT *obj,TABLE t ,FIELD_NAME_LIST *fieldlist);
int GetFieldNameLength(TABLEOBJECT *tbl);
TABLEOBJECT *CreateTableObject(INTERNET_SQL_OBJECT *obj);    
TABLEOBJECT *CreateTableFromDefn(INTERNET_SQL_OBJECT *obj,char *defnfile);
TABLEOBJECT *CreateExtendedNewTable(INTERNET_SQL_OBJECT *obj,char *FileName);
TABLEOBJECT *CreateExtendedTableObject(INTERNET_SQL_OBJECT *obj);
int SizeOfExtendedFieldHeader(void);    

char FixFieldPos(FIELDLIST flist);
char FixFieldPos(RECORDLIST rec);
TABLE CurrentTable(void);
RECORDLIST CurrentRecordList(void);
INDEX CurrentIndex(void);
LISTINFO CurrentListInfo(void);

//---------------------------------------
KINT64 StartKamrangaEngine(void);
int KamrangaClientCommand(INTERNET_SQL_OBJECT *obj,char *command);
char SQLClientDisConnect(INTERNET_SQL_OBJECT *obj);
int SQLClientCommand(INTERNET_SQL_OBJECT *obj);
//---------------------------------------
char ExecMainSelectQryUseIndex(INTERNET_SQL_OBJECT *obj, MAINSELECT *ms,FROMTABLE *fromtable, FROMTABLE *headtable,POSTFIXLINK where,TABLE result);


TABLEOBJECT *CreateNewTable(INTERNET_SQL_OBJECT *obj,char *FileName);         //creates database  file
TABLEOBJECT *CreateTransactionTable(INTERNET_SQL_OBJECT *obj,char *username,char *FileName) ;   
TABLEOBJECT *CreateTableFromFile(INTERNET_SQL_OBJECT *obj,char *FileNameFrom,
                                  char *FileNameTo);  //creates database  file
                                                      //from other file
char ClearRollBackFlag(RECORDLIST rec);
char SetRollBackFlag(RECORDLIST rec);
TABLEOBJECT *CreateTableFromObject(TABLEOBJECT *dbf,char *FileName);     //creates database  file
                                                      //from already class
TABLE CreateSqlQryTable(RECORDLIST,char *tablename);
//----------------------------------------------------------------------
char CompareTables(char *table1,char *table2);
char CompareTables(TABLE tbl1,TABLE tbl2)  ;
char CompareFieldList(FIELDLIST f1,FIELDLIST f2);

char CompareFieldLengths(TABLE tbl1,TABLE tbl2);
char CompareFieldLengths(FIELDLIST f1,FIELDLIST f2);
char CompareFieldLengths(char *table1,char *table2);

char *StripPathGetFileName(char *FileName);
char CompareFieldNames(FIELDLIST f1,FIELDLIST f2);
char CompareFieldNames(TABLE tbl1,TABLE tbl2);
char CompareFieldNames(char *table1,char *table2);

char CompareFieldTypes(TABLE tbl1,TABLE tbl2);
char CompareFieldTypes(FIELDLIST f1,FIELDLIST f2);
char CompareFieldTypes(char *table1,char *table2);

char CompareFieldCount(TABLE tbl1,TABLE tbl2);
char CompareFieldCount(char *table1,char *table2);
char CompareFieldCount(FIELDLIST f1,FIELDLIST f2);

char TableSubset(TABLE tbl1,TABLE tbl2);
char TableSubset(char *table1,char *table2);
char FieldSubset(FIELDLIST f1,FIELDLIST f2);

TABLEOBJECT *OpenDbfEx(INTERNET_SQL_OBJECT *obj,char *FileName) ;   //opens database  file
 TABLEOBJECT *OpenDbf(INTERNET_SQL_OBJECT *obj,char *FileName);   //opens database  file
TABLEOBJECT *OpenTableEx(INTERNET_SQL_OBJECT *obj,char *FileName) ;   //opens database  file
 TABLEOBJECT *OpenTable(INTERNET_SQL_OBJECT *obj,char *FileName,KINT64 id);   //opens database  file
 TABLEOBJECT *OpenTable(INTERNET_SQL_OBJECT *obj,char *FileName);   //opens database  file
 TABLEOBJECT *OpenDbfShared(INTERNET_SQL_OBJECT *obj,char *FileName);   //opens database  file
 TABLEOBJECT *OpenDbfMultiUser(INTERNET_SQL_OBJECT *obj,char *FileName, KINT64 id);   //opens database  file

 TABLEOBJECT *CreateTableCommand(INTERNET_SQL_OBJECT *obj,char *command);
char AddNewFieldCommand(INTERNET_SQL_OBJECT *obj,char *command);
char RemoveFieldCommand(INTERNET_SQL_OBJECT *obj,char *command);
char CountCommand(INTERNET_SQL_OBJECT *obj,char *command);
char ReplaceCommand(INTERNET_SQL_OBJECT *obj,char *command);
char SetCommand(INTERNET_SQL_OBJECT *obj,char *command);
char SortCommand(INTERNET_SQL_OBJECT *obj,char *command);
char DeleteCommand(INTERNET_SQL_OBJECT *obj,char *command);
char UndeleteCommand(INTERNET_SQL_OBJECT *obj,char *command);
char UseCommand(INTERNET_SQL_OBJECT *obj,char *command);
TABLEOBJECT *OpenRemoteTableEx(char *ip,char *port,char *FileName) ;   //opens database  file
TABLEOBJECT *OpenRemoteTable(char *ip,char *port,char *FileName);   //opens database  file
                                     
void GetSqlCmdToken(INTERNET_SQL_OBJECT *obj);
void GetSqlToken(INTERNET_SQL_OBJECT *obj);
void GetSimpleToken(INTERNET_SQL_OBJECT *obj);
void GetToken(INTERNET_SQL_OBJECT *obj);
void GetToken2(INTERNET_SQL_OBJECT *obj);
void GetUserIdPwdToken(INTERNET_SQL_OBJECT *obj);

char * GetKeyFromFile(INTERNET_SQL_OBJECT *obj,KINT64 handle,KINT64 keyno,KINT64 sumlen,KINT64 keyperbuffer,KINT64 reccnt);

//  char  SetField(RECORDLIST rl,int fieldno,char *value);
//  int  SetRecordField(RECORDLIST rl,int fieldno,char *value);
  int  GetRecordField(RECORDLIST rl,int fieldno,char *value);
 void ShowRecordList(RECORDOBJECT *rec);            //shows field names
char CloseTable(INTERNET_SQL_OBJECT *obj,char *FileName);
 char ClearRecord(RECORDOBJECT *Recinfo);   //clears all
                                     //field values
                                          //in the record   
 char SetRecordField(RECORDOBJECT *Recinfo,     //sets value
              char *FieldName,         //to the record
              char *value              //field
             );

 char SetRecordFieldNoTrim(RECORDOBJECT *Recinfo,     //sets value
              char *FieldName,         //to the record
              char *value              //field
             );

char *GetRecordField(RECORDOBJECT *Recinfo,   //returns record
               char *FieldName       //field values
              );



 char SetRecordField(RECORDOBJECT *Recinfo,     //sets value
              int fieldno,         //to the record
              char *value              //field
             );

char *GetRecordField(RECORDOBJECT *Recinfo,   //returns record
               int fieldno       //field values
              );

KINT64 FillExportString(RECORDLIST rec,char *string,KINT64 buffersize,char selectedonly,char UseNewPosWidth);
KINT64 FillExportString(RECORDLIST rec,char *string,KINT64 buffersize,char selectedonly,char UseNewPosWidth,char sep,char useseparator);
KINT64 GetExportLength(RECORDLIST rec,char selectedonly,char useseparator);
KINT64 GetExportLength(RECORDLIST rec,char selectedonly);

char DeleteRecordList(RECORDOBJECT **Recinfo);
char SelectRecordListAll(RECORDOBJECT *rec);
char SelectRecordField(RECORDOBJECT *rec,char *field);
char DeSelectRecordList(RECORDOBJECT *rec,char *field);
char ClearDeleteFlag(RECORDLIST);
char SetDeleteFlag(RECORDLIST);

char CopyRecordBuffer(RECORDLIST To,char *data,char *ptr);
char CopyRecordBuffer(TABLE,char *data,char *ptr);
char MapRecordList(TABLE,TABLE,char typechk);
char MapRecordList(RECORDLIST MapFrom,RECORDLIST Mapto,char typechk);
char MapRecordList(RECORDLIST MapFromList,
                   char *mapfromfield,
                   RECORDLIST MapTo,
                   char *maptofiled,
                   char typechk);
char MapRecordList(TABLE,
                   char *mapfromfield,
                   TABLE,
                   char *maptofiled,
                   char typechk);
char MapField(TABLE from,
                   char *mapfromfield,
                   TABLE to,
                   char *maptofiled,
                   char typechk);

char CopyMappedData(RECORDLIST rec);
char CopyMappedData(TABLE);
//int DropIndex(char *indexname);
char  DropIndexForThisTable(INTERNET_SQL_OBJECT *obj,char *tablename);
char ClearMap(RECORDLIST );
char ClearMap(TABLE);
char *GetMappedData(RECORDLIST,char *fieldname );
char *GetMappedData(TABLE,char *fieldname );

char NoFieldMapped(TABLE);
void GetTableDirectory(TABLE tbl);
void GetIndexDirectory(INDEX ndx);
KINT64 ExecList(INTERNET_SQL_OBJECT *obj,MAINSELECT **ms,TABLE tbl,FIELD_NAME_LIST *matchlist,FIELD_NAME_LIST *excludefieldlist,int listtype);

RECORDOBJECT * CreateSelectedRecordList(RECORDOBJECT *rec);
TABLEOBJECT *CreateTableFromRecordList(RECORDOBJECT *rec,char *FileName);   
TABLEOBJECT *CreateTableFromFieldList(FIELDLIST Fields,char *FileName)  ;
TABLEOBJECT *CreateTableFromSelectedRecordList(RECORDOBJECT *rec,char *FileName);   
char CopyRecordListCheckData(RECORDLIST From,RECORDLIST To);
//-------------------------------------------------
//pick data after every separator lenth
//in the input string and make a record
//-------------------------------------------------
char MakeRecordWithSeperator(RECORDOBJECT *rec,  //fill up this list
                             char  sepchar,    //seperator between fields
                             char *data,       //raw data read from file
                             UINT16 length, //length of data
                             char selflg       //prepare data for selected fields only
                             );

//-------------------------------------------------
//pick data after every separator lenth
//in the input string and make a record
//-------------------------------------------------
char MakeRecordWithSeperator(RECORDOBJECT *rec,  //fill up this list
                             int  seperatorlen,    //seperator between fields
                             char *data,       //raw data read from file
                             UINT16 length, //length of data
                             char selflg       //prepare data for selected fields only
                             );

//-------------------------------------------------
//pick data from given position in the input string
//and make a record
//-------------------------------------------------
char MakeRecordWithPosition(RECORDOBJECT *rec,  //fill up this list 
                             char *data,       //raw data read from file
                             long length, //length of data
                             char selflg       //prepare data for selected fields only
                             );
RECORDOBJECT *FindField(RECORDLIST rec,char *field);
int FindFieldNameInOtherTable(FROMTABLE *FromTables,FROMTABLE *curtable,char *Fieldname);
RECORDLIST  CreateRecordList(INTERNET_SQL_OBJECT *obj,RECORDLIST *rec,
									int fieldnamelen,
                            char *fieldname,
                            char fieldtype,
                            KINT64 fieldlen,
                            short int decimalpos,
							char notnull,
							char keytype,
							char autoinc,
							char unique
                           );
RECORDOBJECT *FindField(RECORDLIST rec,int fieldno);
long GetRecordLength(RECORDLIST rec);
RECORDOBJECT *FindFieldAndPrefix(RECORDLIST rec,char *field,char *prefix);
void UpDateMaxBytesUsed(FIELDLIST Fields,RECORDLIST Rec);
char DeSelectRecordListAll(RECORDOBJECT *rec);
int TruncFile(KINT64 *handle,char *filename);
 KINT64 GetFreeDiskSpace(void);
char CopyRecordListData(RECORDLIST From,RECORDLIST To);
char CopySqlQryRecordListData(RECORDLIST From,RECORDLIST To);
char GetBackUpFileName(char *FileName,char *bak);
//char CreateBackUp(char *filename,KINT64 *handle);
char GetDelimitedFields(RECORDLIST rec,char *delimiters);

FIELDLIST CreateFieldListFromRecordList(RECORDLIST rec);
char RestoreDbfFromBackup(char *filename,char *bakfile,KINT64 *handle);
//-----------------------------
//see if conditions are fullfilled
//-----------------------------
//-----------------------------
//see if conditions are set for
//any field
//-----------------------------
char SetFileExt(char *FileName,char *ext);
char SelectionMade(RECORDLIST rec);
char FieldSelected(RECORDLIST rec,char *fieldname);
char FieldConditionSet(RECORDLIST rec,char *fieldname);
int GetMaximumSelectSequence(RECORDLIST rec);
RECORDLIST GetSelectedField(RECORDLIST rec,int seq);
int GetMaximumSelectSequence(FIELDLIST);
FIELDLIST GetSelectedField(FIELDLIST ,int );
//char DeAllocHandle(HANDLE *handle );
char DeleteFieldList(FIELDOBJECT **field);
char BlankField(char *field);
char BlankField(RECORDLIST rec,char *field);
char *Rtrim(char *field);
char *Ltrim(char *field);
char *AllTrim(char *field);
char SetNewFieldSize(RECORDLIST,char *,int );
char SetNewFieldPos(RECORDLIST,char *,KINT64 );
char CopySelectedRecordList(RECORDOBJECT *from,RECORDOBJECT *to);
char CopyRecordList(RECORDOBJECT *from,RECORDOBJECT *to);

RECORDOBJECT *FindConditionalField(RECORDOBJECT *rec,char *key);

//     char ShowIndexOperation(unsigned KINT64 i,HDC hdc,char *str);
char CreateTableFromTextFileAdd( 
					INTERNET_SQL_OBJECT *obj,	
                    char *dbffile,
                    char *defnfile,
                    char *textfile
                   );
TABLEOBJECT * CreateTableFromTextDefn( 
				    INTERNET_SQL_OBJECT *obj,	
                    char *dbffile,
                    char *defnfile
                   );


char *AddPath(char *pathname,char *FileName);
char *GetPath(void);
int SQLRecoverDatabase(INTERNET_SQL_OBJECT *obj);
int SQLRecoverHost(INTERNET_SQL_OBJECT *obj);
                
int DeleteDatabaseFromHostTable(INTERNET_SQL_OBJECT *obj,char *databasename);

int FindDatabase(INTERNET_SQL_OBJECT *obj,char *databasename,char *ipstring,char *portstring, char *dropped, char *deleted);
int FindHost(INTERNET_SQL_OBJECT *obj,char *hostname,char *ipstring,char *portstring, char *dropped);
int DropDatabaseFromHostTableEntry(INTERNET_SQL_OBJECT *obj,char *databasename);
int DeleteHost(INTERNET_SQL_OBJECT *obj,KINT64 recno);
int SQLAddHost(INTERNET_SQL_OBJECT *obj);
int SQLDeleteHost(INTERNET_SQL_OBJECT *obj);
char CheckNumber(char *number);
RECORDLIST GetRecordObject(RECORDOBJECT *rec,KINT64 fieldno);
char *DateToCharUS(char *datenumber,char *datestring);
char *CharToDateUS(char *datestring,char *datenumber);
int MonthToNumber(char *monthname);
char *DateToCharEnglish(char *datenumber,char *datestring);
char *CharToDateEnglish(char *datestring,char *datenumber);
int UpdateUnInserted(INTERNET_SQL_OBJECT *obj,RECORDLIST rec,FIELD_NAME_LIST *insertnames);
int ValidDoubleString(int token,char *WordBuffer);
int ValidDateString(int token,char *WordBuffer);
int ValidTimeString(int token,char *WordBuffer);

int ValidNumberString(int token,char *WordBuffer);
FIELDLIST InsertField(INTERNET_SQL_OBJECT *obj,
					  FIELDLIST *Fields,
                           char *fieldname,
                           int fieldlength,
                           char fieldtype,
                           char decimalpoint,
						   int fieldnamelen,
						   char notnull,
						   char keytype,
						   char autoinc,
						   char unique
                          );
TABLEOBJECT * CreateTableFromExtDefn(
                    INTERNET_SQL_OBJECT *obj,										 
                    char *dbffile,
                    char *defnfile
                   );
TABLEOBJECT * CreateTableFromTextDefn( 
                    INTERNET_SQL_OBJECT *obj,	
                    TABLE *dbf,
                    char *defnfile
                   );
FIELDLIST SearchDefn(FIELDLIST Fields,char *name,int fieldnamelen);
char CloseEveryThing(void);
char *CopyRecordField(char *src,char *fieldname,RECORDOBJECT *rec);
char ReleaseTable(TABLEOBJECT **dbf);
char ReleaseRecordList(RECORDOBJECT **rec);
char *ReadBuffered(TABLEOBJECT *dbf,KINT64 recno);
char WriteBuffered(TABLEOBJECT *dbf,KINT64 from,KINT64 to);
char MarkBufferDelete(TABLEOBJECT *dbf,KINT64 recno);
char MarkBufferUnDelete(TABLEOBJECT *dbf,KINT64 recno);
char ReplaceBuffer(TABLEOBJECT *dbf,KINT64 recno,RECORDLIST rec,char *fieldvalue);
char CloseAndReleaseTable(TABLEOBJECT **dbf);
char CloseAndDeleteTable(TABLEOBJECT **dbf);
char *GetFieldBuffer(RECORDOBJECT *rec,char *field);
char ClearRecordField(RECORDOBJECT *recinfo,char *field);
char SetFieldBlank(RECORDOBJECT *recinfo,char *field);
char SetRecordBlank(RECORDOBJECT *recinfo);

char RecordListCmpData(RECORDLIST,RECORDLIST);
RECORDLIST  InsertFieldInfo(INTERNET_SQL_OBJECT *obj,RECORDLIST *rec,int fieldnamelen,char *,char ,KINT64,short int,char notnull,char keytype,char autoinc,char unique);
RECORDLIST  InsertFieldInfoForQry(INTERNET_SQL_OBJECT *obj,RECORDLIST *rec,int fieldnamelen,char *,char ,KINT64,short int,char notnull,char keytype,char autoinc,char unique,long max_field_byte_used);

RECORDLIST  OverWriteFieldDefn(RECORDLIST rec,char *fieldname,char fieldtype,KINT64 fieldlen,short int decimalpos,char notnull,char keytype,char autoinc,char unique);
long        MakeRecord(RECORDLIST , char *);
TABLEOBJECT *AddTable(TABLEOBJECT *dbf);
TABLEOBJECT *FindTable(INTERNET_SQL_OBJECT *obj,char *dbfname);
char RemoveDbf(TABLEOBJECT **dbf);
char CloseAllTables(INTERNET_SQL_OBJECT *obj);
char CloseAllSlotTables(USERSLOT *slot);

char CloseAllTables(KINT64 id);
char ShowRecordField(RECORDOBJECT *Recinfo,char *field);
char MemoFieldType(RECORDOBJECT *rec);
char ErrorOn(USERSLOT *slot);
char ErrorOff(USERSLOT *slot);
POSTFIXLINK CreateEvalStack(INTERNET_SQL_OBJECT *obj,KINT64 stacksize);

DATABASE  FindTable(DATABASE);
void  ShowFieldList(FIELDLIST);
char RemoveField(FIELDLIST *, char *name,int fieldnamelen);
char KmgSuperUser(INTERNET_SQL_OBJECT *obj);
char CheckUnLockAuthority(INTERNET_SQL_OBJECT *obj,LOCKINFO *lockinfo);
char CheckLockAuthority(INTERNET_SQL_OBJECT *obj,LOCKINFO *linfo,char *lockstr, KINT64 from,KINT64 to);
char *ExtractFilename(char *FileName);
void SetTableWizardMode(void);
void ClearTableWizardMode(void);
int IsExtendedTableMode(INTERNET_SQL_OBJECT *obj);
int IsUserAdmin(INTERNET_SQL_OBJECT *obj);
int IsUserSuperuser(INTERNET_SQL_OBJECT *obj);
int IsUserManager(INTERNET_SQL_OBJECT *obj);
char *GetDatabaseName(void);
int SetDatabaseName(char *buf);



//----------------------
int DateCmp(char *,char *);
int ThisYear(void);
int ThisCentury(void);
int ThisMonth(void);
int Today(void);
int ThisMonthName(char *month);
int TodayName(char *day);

int GetYear(char *date);
int GetMonth(char *date);
int Getday(char *date);
int Hour(void);
int Minutes(void);
int Seconds(void) ;
int WeekDay(void);
char *TimeString(char *timestring);
char *LeftJustify(char *data);
char *RightJustify(char *data);
char *GetRecordFieldBuffer(RECORDOBJECT *rec,KINT64 fieldno);
KINT64  GetRecordFieldSerial(RECORDOBJECT *rec,char *field);
char CloseDbf(TABLEOBJECT **dbf);
char ShowOpenTableNames(void);
RECORDOBJECT *Query(void);
char CreateView(char *viewname);
char ZapRevoked(void);
char ResetQuery(void);
char SetQuery(char *querystring);
SYSVARS MakeVar(char *varname,char *vartype,char *address);
SYSVARS FindVar(INTERNET_SQL_OBJECT *obj,char *varname);
int EvalPostLink(INTERNET_SQL_OBJECT *obj,POSTFIXLINK postlnk,char typecheck);
int SQLCommand(INTERNET_SQL_OBJECT *obj);
RECORDOBJECT *PickFromSelection(void);
int NonSqlCommand(class internetsqlobject *obj,char *command);
RECORDOBJECT * CreateSelectedFieldList(RECORDOBJECT *rec);
char DeleteSelectedFieldList(RECORDOBJECT  **recinfo);
char DeleteVar(INTERNET_SQL_OBJECT *obj);
FIELDLIST FindField(FIELDLIST , char *fieldname);
FIELDLIST CreateSelectedFieldList(FIELDLIST);
int SelectFieldFromList(FIELDLIST, char *fieldname);
char SelectionMade(FIELDLIST flist);
KEYLIST CreateKeyList(FIELDLIST flist);
char  DeleteKeyList(KEYLIST *);
KINT64 MakeRecordString(RECORDLIST rec,char *data);
KINT64 MakeSqlInsertString(RECORDLIST rec,char *data);

KINT64 MakeSqlUpdateString(RECORDLIST rec,char *data);
RECORDOBJECT *CreateRecordListFromDefn(char *defnfile);
KINT64 MakeSqlCreateTableString(RECORDLIST rec,char *buf);
KINT64 MakeSqlCreateTableStringFromFieldList(FIELDLIST *ff,char *buf);
char ShowKeyList(KEYLIST kl);
KINT64 ModifySwapBlockCount(KINT64 count);
POSTFIXLINK CreatePostfixLink(INTERNET_SQL_OBJECT *obj,RECORDLIST ri,char *pstring);
char DeleteLink(POSTFIXLINK *);
char ShowPostLink(POSTFIXLINK postlnk);
char PrepareForListAndIndex(
                            DATABASE dbf,
                            KEYLIST  kl,
                            int      *keycnt,
                            KINT64     start,
                            KINT64     end,
                            KINT64     *keylentotal,
                            int      *keyperbuffer,
                            KINT64     *totalkeybuffer,
                            char     forindex
                           );
char LoadAll(DATABASE dbf,
             KINT64 start, 
             KINT64 end,
             KEYLIST kl,
             POSTFIXLINK pl,
             char *forstring, 
             char notdeleted,
             int keyperbuffer,
             int keylentotal); 
KINT64 LoadAndSwap(DATABASE dbf,
                 KINT64 start,
                 KINT64 end,
                 KEYLIST kl,
                 POSTFIXLINK pl,
                 char notdeleted,
                 int keylentotal, 
                 int *keyperbuffer,
                 KINT64 *keyperblock,
                 char *forstring,
                 int *handle1,
                 int *handle2,
                 char *firstfile,
                 char *secondfile);
void RemoveIndexFile(DATABASE dbf,
                            INDEX index,
                            int handle1,
                            int handle2,
                            char *firstfile,
                            char *secondfile,
                            char *Filename);
void CloseIndexFile(DATABASE dbf,
                           INDEX index,
                           int handle1,
                           int handle2,
                           char *firstfile,
                           char *secondfile);
void  Qsort1(char *buf, KINT64 first,KINT64 last,FIELDLIST ff);
 void  Split1(char *buf, 
                     KINT64 first,
                     KINT64 last, 
                     KINT64 *split1,
                     KINT64 *split2,
                     FIELDLIST ff);
char InsertionSort1(char *buf,KINT64 start,KINT64 end,FIELDLIST ff);
char KeyLess(char *key1,char *buf,KINT64 keyno,FIELDLIST ff);
char EqualKey(KEYPOINTER key1,KEYPOINTER key2,KEYLIST kl);
char LessThan(KEYPOINTER key1,KEYPOINTER key2,KEYLIST kl);
char GreaterThan(KEYPOINTER key1,KEYPOINTER key2,KEYLIST kl);
char InsertionSort2(KEYPOINTER buf,
                           int reserved,
                           KEYLIST kl,
                           int keyperbuffer,
                           int sumlen,
                           KINT64 start,
                          KINT64 end);
void  Qsort2(KEYPOINTER buf,
                    int reserved, 
                    KINT64 first,
                    KINT64 last,
                    int keyperbuffer,
                    KEYLIST kl,
                    KINT64 sumlen);
void  Split2(KEYPOINTER buf, 
                    int reserved,
                    KINT64 first,
                    KINT64 last, 
                    KINT64 *split1,
                    KINT64 *split2,
                    int keyperbuffer,
                    KEYLIST kl,
                    KINT64 sumlen);

KINT64 ReadIndexBuffered(INTERNET_SQL_OBJECT *obj,KINT64 handle,KINT64 nodeoffset,INDEXNODE *indx);
KINT64 ReadIndexHugeBuffered(KINT64 handle,KINT64 ptr,INDEXNODE *indx);

char *Str(char *buf, KINT64 ptr);
 KINT64 GetRunCount(KINT64 handle);
char PrintBuf(  INDEX index,
                         KINT64 handle,
                         int BufferLimit,
                         int KeyWidth
               );
char PrintQsortAllBuffered(  
                         INDEX index,
                         KEYPOINTER kp,
                         int KeyPerBuffer);

char  WriteDirectoryBuffered(INDEX index);
char PrintTwoBuffers(INDEX index,
                     KINT64 inputhandle,
                     int keyperbuffer,
                     KINT64 keyperblock
                     );
 KINT64 Assemble3(
           int *input,
           int *output,
           KEYLIST kl,
           int keyperbuffer,
           int sumlen,
           KINT64 keyperblock
          );
 KINT64 Assemble2(
           int *input,
           int *output
          );
char WriteIndexNode(
                        INDEX index,
                        KINT64 handle,
                        int  BufCount,
                        char Type);
char  WriteDirectory(      INDEX index,
                                    KINT64 handle,
                                    int keywidth,
                                    char *keyname,
                                    int BufferLimit);
char  WriteDirectoryHugeBuffered(INDEX index);
char  CreateEmptyIndex(INDEX index);
char  UpdateIndexLeaf(char * buf,
                           KINT64 leafno,
                           INDEX index,
                           int BufCount,
                           char finalleaf);
char ReleaseGlobalBuffers(void);
char PrintQsortAll(
                   INDEX index,
                   KEYPOINTER kp,
                   int KeyPerBuffer
               );
char SelectFieldListAll(FIELDLIST fl);
char DeSelectFieldListAll(FIELDLIST fl);
char AutoReindexOffAll(void);
char AutoReindexOnAll(void)  ;
char AutoIndexUpdateOffAll(void);
char AutoIndexUpdateOnAll(void) ;
//char ScratchPad[];
char *ToLower(char *field);
char *ToUpper(char *field);
int CopyFieldString(RECORDLIST tmp,char *str,int buffersize,int copypoint,char UseNewPosWidth);
void SetDateUS(USERSLOT *slot);
void SetDateEnglish(USERSLOT *slot);
void EnableCursorMode(USERSLOT *slot);
void DisableCursorMode(USERSLOT *slot);
char SetExtendedTableMode(USERSLOT *slot);
char ClearExtendedTableMode(USERSLOT *slot);
int  ThisDay(void);
int ThisWeek(void);
int ExecSql(INTERNET_SQL_OBJECT *obj,char *buf);
int ExecSqlDownload(char *tablename, 
				  char *fieldname, 
				  KINT64 recordnumber, 
				  KINT64 offset, 
				  int downloadsize,
				  char *buffer
				  
				  );
int ExecSqlUpload(char *tablename, 
				  char *fieldname, 
				  KINT64 recordnumber, 
				  char *data, 
				  int uploadsize,
				  int sequence
				  );
 
void DebugOn(void);
void DebugOff(void);
char ConnectToDataBase(INTERNET_SQL_OBJECT *obj,char *databasename);
int FindDecimalPos(char *);
TABLE CreateSysTable(INTERNET_SQL_OBJECT *obj);
KINT64 KAM_OpenFile(char *filename,KINT64 flags,KINT64 permissions);
int KAM_CloseFile(KINT64 handle);
int KAM_ReadFile(KINT64 handle,char *data,int size);
int KAM_WriteFile(KINT64 handle,char *data,int size);
KINT64 KAM_SeekFile(KINT64 handle,KINT64 pos,int origin);
KINT64 KAM_TellFile(KINT64 handle);
KINT64 KAM_CreateFile(char *filename,int flag);

void *KAM_AllocMem(INTERNET_SQL_OBJECT *obj,int clearflag,KINT64 size);
void KAM_FreeMem(INTERNET_SQL_OBJECT *obj,void *);

void *KAM_AllocMemPersistent(INTERNET_SQL_OBJECT *obj,int clearflag,KINT64 size, int persistenttype);
void KAM_FreeMemPersistent(INTERNET_SQL_OBJECT *obj,void *);

void *KAM_AllocSlotMem(USERSLOT *slot,int clearflag,KINT64 size);
void KAM_FreeSlotMem(USERSLOT *slot,void *);

void *KAM_AllocSlotMemPersistent(USERSLOT *slot,int clearflag,KINT64 size, int persistenttype);
void KAM_FreeSlotMemPersistent(USERSLOT *slot,void *);


void *KAM_AllocObject(INTERNET_SQL_OBJECT *obj,int clearflag,KINT64 size);
void KAM_FreeObject(INTERNET_SQL_OBJECT *obj,void *);
void ClearObjectTemporaryStuff(INTERNET_SQL_OBJECT *obj);
void ClearObjectTemporaryStuffAll(INTERNET_SQL_OBJECT *obj); //essentially free all astray mallocs
void ClearObjectAllocNoLifeTimeNoTransaction(INTERNET_SQL_OBJECT *obj); 


KINT64 KAM_GetCurrentDiskDriveFreeSpace(void);
int EscapeSingleQuote(char *in,char *out);
int  KAM_GetDate(KAM_DATE_STRUCT *);
char *GetSystemDateUS(char *string);
char *GetSystemDate(char *string);
char *CharToDate(char *date,char *cleandate);
char *GetSystemDateEnglish(char *string);

int UserSlot_MessageBox(USERSLOT *slot,void *hwnd ,  char *body, char *caption,int icontype);
int KAM_MessageBox(INTERNET_SQL_OBJECT *obj,void *hwnd ,  char *body, char *caption,int icontype);
char *KAM_getcwd(char *, int len);
int KAM_chsize(KINT64 handle,KINT64);
int KAM_chdir(INTERNET_SQL_OBJECT *obj,char *path);
int KAM_mkdir(char *);
int KAM_locking(int FileHandle,KINT64 flags,KINT64 timeout); 
int KAM_chdrive(int);
int KAM_stricmp( char *buf1, char *buf2);
int KAM_strcmp( char *buf1, char *buf2);
int KAM_strnicmp( char *buf1, char *buf2,int len);
KINT64 KAM_Locking(int FileHandle,int locktype,KINT64 bytecount);
int KAM_remove(char *filename);
int KAM_rename(char *oldfilename,char *newfilename);
char RevokeAll(INTERNET_SQL_OBJECT *obj,char *username);
int DatabaseExist(INTERNET_SQL_OBJECT *obj,char *databasename);
int RecoverDatabase(INTERNET_SQL_OBJECT *obj,KINT64 recno);
int DropDatabase(INTERNET_SQL_OBJECT *obj,KINT64 recno);
int DeleteDatabase(INTERNET_SQL_OBJECT *obj,KINT64 recno);


int IndexExist(char *name);

extern int KAM_MB_ICONSTOP;
extern int KAM_IDNO; 
extern int KAM_MB_YESNO ; 
extern int KAM_O_BINARY;

extern int KAM_OF_SHARE_DENY_NONE;

extern int KAM_OF_READWRITE;    
extern int KAM_S_IWRITE;      
extern int KAM_O_CREAT;
extern int KAM_O_TRUNC; 
extern int KAM_O_RDWR; 
extern int KAM_MB_OK ;  
extern int KAM_O_RDONLY;
extern int KAM_LK_NBLCK;
extern int KAM_LK_UNLCK;
extern int KAM_LK_LOCK;



KINT64 StartKamrangaNetworkAgent(long startid,char *srvrname);
KINT64 IpStringToNumber(INTERNET_SQL_OBJECT *obj,char *str);
char CloseNetworkLink(USERSLOT *slot);
int KAM_InitServerNetwork(USERSLOT *slot);
int KAM_CloseClientByServer(USERSLOT *slot,int clientsocket);
int KAM_AcceptClient(int serversocket );
int KAM_AcceptClientNoWait(USERSLOT *slot,int socket , struct sockaddr *client_addr);
void NoNetworkMode(USERSLOT *slot);
void NetworkMode(USERSLOT *slot);
void DisableMessage(USERSLOT *slot);
void EnableMessage(USERSLOT *slot);

int KAM_WSAGetLastError(USERSLOT *slot); 
char ParseNotNull(INTERNET_SQL_OBJECT *obj);
int ValidKamrangaFieldType(char *WordBuffer);
char ParseKeyType(INTERNET_SQL_OBJECT *obj,char *unique);
char ParseAutoInc(INTERNET_SQL_OBJECT *obj,KINT64 *initialvalue,char *autoinc);
int ValidUserInfo(char *);
int GetUserInfo(INTERNET_SQL_OBJECT *obj,char *username,USERINFO *uinfo);
int SetUserInfo(INTERNET_SQL_OBJECT *obj,USERINFO *uinfo);
int UpdateUserInfo(USERINFO *, char *infoname, char *infoval);

int KAM_CloseSocket(USERSLOT *slot,int socket);
int KAM_Send(USERSLOT *slot,int socket,char *buf,int size,int waitflag);
int KAM_Recv(USERSLOT *slot,int socket,char *buf,int size,int waitflag);
int KAM_Connect(USERSLOT *slot,int socket);
int KAM_SocketTcp(USERSLOT *slot);
int KAM_LoadSystemFiles(INTERNET_SQL_OBJECT *obj);
int KAM_UnloadSystemFiles(INTERNET_SQL_OBJECT *obj);
int KAM_CreateUserDumpDir(USERSLOT *slot,char *KmgCurrentUser,int createuserdir);
int KAM_CreateDumpDir(USERSLOT *slot);
int CreateDumpTableNames(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms);

 KINT64 KAM_GetTickCount(void);
int KAM_toupper( int);
int KAM_tolower( int);
KINT64 GetClientIp(void);
KINT64 GetClientPort(void);
int KAM_InitNetworkLink(USERSLOT *slot,KINT64 serveripnumber,int serverportnumber );
int PatternHasNoWildCard(char *pattern);
int EvalLikeExpression(char *buf,char *pattern);
int LoadSqlScript(INTERNET_SQL_OBJECT *object,
				  char *scriptfilename,
				 char *logfilename ,
				 int stopinerror,
				 int stoplog,
				 int stopdisplay,
				 void *displayfunc,
				 void *userfunc);
void EnableSingleStepSqlScript(USERSLOT *slot);
void DisableSingleStepSqlScript(USERSLOT *slot);
void StartSqlScript(USERSLOT *slot);
void StopSqlScript(USERSLOT *slot);
void QuitSqlScript(USERSLOT *slot);
int KmgSystemFiles(INTERNET_SQL_OBJECT *obj,char *tablename);
int SQLDropGroup(INTERNET_SQL_OBJECT *obj);
int SQLAddGroup(INTERNET_SQL_OBJECT *obj);
int SQLAddDatabase(INTERNET_SQL_OBJECT *obj);
int SQLDropDatabase(INTERNET_SQL_OBJECT *obj);
int SQLRecoverDatabase(INTERNET_SQL_OBJECT *obj);
int AddKmgGroup(INTERNET_SQL_OBJECT *obj,char *grpname,char *mgrname);

int GroupPermissionOk(INTERNET_SQL_OBJECT *obj,int operationtype,char *grpname,char *mgrname,char *owner,char *lock,char *lockedby,char *allowadmin);
int FindKmgGroupEntry(INTERNET_SQL_OBJECT *obj,char *grpname,char *mgrname,char *owner,char *lock,char *lockedby,char *allowadmin);
int SetGroupInfo(INTERNET_SQL_OBJECT *obj,char *grpname,char *newmgrname,char *owner,char *lock,char *lockedby, char *allowadmin,KINT64 recno);
int DropKmgGroup(INTERNET_SQL_OBJECT *obj,char *grpname,KINT64 recno);
char   RecordListSubset(RECORDLIST f1,RECORDLIST f2);
char   CompareRecordList(RECORDLIST f1,RECORDLIST f2);
char   CompareRecordListFieldCount(RECORDLIST f1,RECORDLIST f2);
char NoFieldMapped(RECORDLIST reclist);
int  ListGroup(INTERNET_SQL_OBJECT *obj,int groupfilter,char *filtervalue);
int  GetManagersGroupName(INTERNET_SQL_OBJECT *obj,char *manager,char *groupname);
int SQLLockTopLevel(INTERNET_SQL_OBJECT *obj);
int SQLUnLockTopLevel(INTERNET_SQL_OBJECT *obj);
int SystemLocked(INTERNET_SQL_OBJECT *obj);
int DatabaseLockedForThisUser(INTERNET_SQL_OBJECT *obj);
int SetTopLevelLock(INTERNET_SQL_OBJECT *obj);
int ClearTopLevelLock(INTERNET_SQL_OBJECT *obj);
void StackTopError(void);
int KAM_rmdir(char *dirname);
int RemoveDatabase(INTERNET_SQL_OBJECT *obj,char *databasename);
KINT64 FindTableNameInSysTable(INTERNET_SQL_OBJECT *obj,char *tablename,TABLE_INFO *tblinfo);
TABLE FindTableName(char *databasename,char *tablename,char * hostname,char remote,FROMTABLE *FromTables);
int TableDropped(TABLE_INFO *tblinfo);
KINT64 RecoverIndexName(INTERNET_SQL_OBJECT *obj,KINT64 recno);
int TablePermissionsOk(INTERNET_SQL_OBJECT *obj,int token,TABLE_INFO *tblinfo);
int  GetGroupManager(INTERNET_SQL_OBJECT *obj,char *groupname,char *manager);
void CopyPassword(char *buf,int buflen);
void CopyUserId(char *buf,int buflen);


int CreateServerOutputWindow(void);
int CloseServerOutputWindow(void);
void ProcessClientRequest(INTERNET_SQL_OBJECT *obj,CLIENT_CALL_QUEUE *,KAMRANGA_COMM_PACKET *ClientMsg);
KINT64 SendSelectedData(INTERNET_SQL_OBJECT *obj);
KINT64 SendSelectItems(INTERNET_SQL_OBJECT *obj) ;
int CopyEnumValuesToString(char *to ,ENUM_LIST *enumvalues,int useseperator, char *seperator);
int CopyEnumValuesFromString(INTERNET_SQL_OBJECT *obj,ENUM_LIST **enumvalues,char *from, int count);


KINT64 ExecArray(INTERNET_SQL_OBJECT *obj,MAINSELECT **ms, int count,char *arrayname,char *strarray[],int max_string_len,int type);
int KAM_InitParallelServerNetwork(USERSLOT *slot);
int DispatchToParallelServer(INTERNET_SQL_OBJECT *obj,int parallel_serversocket,int clientsocket,KAMRANGA_COMM_PACKET *ClientMsg);
int FindParallelServer(int socket);
void ServiceParallelServerMessages(USERSLOT *slot,int socket);
int InterpretParallelServerMessage(USERSLOT *slot,CLIENT_CALL_QUEUE *,KAMRANGA_COMM_PACKET *ClientMsg);
int StartParallelServers(void);
int StopParallelServers(void);
int KAM_AcceptParallelServer(USERSLOT *slot,int socket );
void SetServerMasterMode(USERSLOT *slot);
int ParallelServerMessage(KAMRANGA_COMM_PACKET *ParallelServerMsg);
int  ProcessMutexRequest(CLIENT_CALL_QUEUE *,KAMRANGA_COMM_PACKET *ClientMsg);
int FindParallelServerName(USERSLOT *slot,char *name);
KINT64 GetParallelServerPortNoFromMaster(char *);
int KAM_InitParallelNetworkLink(KINT64 serveripnumber,int serverportnumber );
int KAM_InitMutexNetworkLink(USERSLOT *slot,KINT64 serveripnumber,int serverportnumber );


int KAM_ParallelConnect(int socket);

int KAM_Exec(char *prgname);
KINT64 TransmitToParallelServerPort(INTERNET_SQL_OBJECT *obj,char *);
KINT64 WaitForMutexRequest(INTERNET_SQL_OBJECT *obj,char *);
int KAM_LoadMutexServer(void);
int ParallelServerRegistered(char *name);
void ServiceMutexMessages(USERSLOT *slot,int socket);
void   KAM_SetSocketNonBlocking(USERSLOT *slot,int socket);
void CancellParallelRegistration(USERSLOT *slot,int i);
void SetMutexMasterMode(void);  
void CancelMutexParallelRegistration(int clientsocket);
KINT64 GetTimeStamp(void);
int RelayKamrangaRemoteClientCommand(INTERNET_SQL_OBJECT *,char *ipaddress,char *portno);
#ifndef SUNUNIX
int InitDistributedServerNetWorkLink(USERSLOT *slot,
									 KINT64 ipnumber,
									 KINT64 portnumber,
									 SOCKADDR_IN *DistributedWinClientAddr,
									 SOCKADDR_IN *DistributedWinServerAddr);
int KAM_DistributedConnect(int socket,SOCKADDR_IN *);
#else
int InitDistributedServerNetWorkLink(INTERNET_SQL_OBJECT *obj,
									 KINT64 ipnumber,
									 KINT64 portnumber,
									 struct  sockaddr_in *DistributedClientAddr,
									 struct  sockaddr_in *DistributedServerAddr);
int KAM_DistributedConnect(int socket,struct  sockaddr_in *);
#endif


int SetDatabaseInfo(INTERNET_SQL_OBJECT *obj,char *databasename,char *infoname,char *infoval);
int  ListHost(INTERNET_SQL_OBJECT *obj);

int FindFreeParallelServerSlot(USERSLOT *slot);
void InitHelp(void);
TABLEOBJECT *CreateTableObjectFromRecordList(RECORDLIST rec);
RECORDLIST CreateRecordListFromQueryObject(QUERYRESULTOBJECT qResult);
RECORDLIST CreateRecordListFromDescribeQuery(QUERYRESULTOBJECT qResult);
int ExecSqlDistributed(char *ipstr,char *portstr, MAINSELECT *ms,char *sqlcommand);
TABLE FindTableForWhereItem(MAINSELECT *ms,char *databasename,char *tablename,char *hostname,char remote,FROMTABLE *ft,POSTFIXLINK pl);
TABLE FindTableFromSubSel(SUBSELECT *ss,char *databasename,char *tablename,char *hostname,char remote);
TABLEOBJECT *RemoteOpenTableEx(char *ip,char *port,char *FileName); 
FROMTABLE * AddTableToMainFrom(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms,char *tblname,char *hostname,char remote);
FROMTABLE * AddTableToSubFrom(INTERNET_SQL_OBJECT *obj,SUBSELECT *ss,char *tblname,char *hostname,char remote);
MAINSELECT *CreateCurrentQuery(INTERNET_SQL_OBJECT *obj);
int FindOrOperator(POSTFIXLINK pl); 
int RowIdPresent(POSTFIXLINK pl);
POSTFIXLINK FindRowIdRange(POSTFIXLINK pl);
int ExecSubSelectQryUseIndex(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms,SUBSELECT *ss,KINT64 *rowcount);
int ExecSubSelectQry(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms,SUBSELECT *ss,KINT64 *rowcount);
int SQLDeleteCursor(INTERNET_SQL_OBJECT *obj);
int CursorExist(INTERNET_SQL_OBJECT *obj,char *cursorname);
int DeleteCursor(INTERNET_SQL_OBJECT *obj,char *cursorname);
int SQLOpenCursor(INTERNET_SQL_OBJECT *obj);

int FindDatabaseInHostTable(INTERNET_SQL_OBJECT *obj,char *databasename,char *hostname,char *ipstring,char *portstring, char *dropped);
int SQLCloseCursor(INTERNET_SQL_OBJECT *obj);

int InsertDatabaseInHostTable(INTERNET_SQL_OBJECT *obj,char *databasename,char *hostname,char *ipstring,char *portstring);
int KAM_CreateCursorDir(INTERNET_SQL_OBJECT *obj,char *username);
int CheckSysCursor(INTERNET_SQL_OBJECT *obj,char *username);
int MakeIndexEntry(INTERNET_SQL_OBJECT *obj,TABLE tbl,KEYLIST kl);
int SetShellExecFunction(USERSLOT *slot,void *proc);
void SetShellMode(USERSLOT *slot);
void ShowShellPrompt(USERSLOT *slot);
void ClearShellMode(USERSLOT *slot);
int SetShellPrompt(USERSLOT *slot,char *prompt);
int PackDatabase(INTERNET_SQL_OBJECT *obj,char *databasename);
int PackDatabaseAll(INTERNET_SQL_OBJECT *obj);

int DisplayWindowPresent(USERSLOT *slot);
int ListTable(INTERNET_SQL_OBJECT *obj);
char  WriteDirectoryBufferedAuto(INDEX index);
int RecoverDatabaseFromHostTableEntry(INTERNET_SQL_OBJECT *obj,char *databasename);
int RecoverHost(INTERNET_SQL_OBJECT *obj,KINT64 recno);

int SQLAddBackground(INTERNET_SQL_OBJECT *obj);
int SQLSetBackground(INTERNET_SQL_OBJECT *obj);
int SQLDropBackground(INTERNET_SQL_OBJECT *obj);
int SQLDeleteDatabase(INTERNET_SQL_OBJECT *obj);
int ListBackground(INTERNET_SQL_OBJECT *obj);
int SQLDeleteBackground(INTERNET_SQL_OBJECT *obj);
void ClearCurrentQuery(INTERNET_SQL_OBJECT *obj);
int ExecBackgroundJob(INTERNET_SQL_OBJECT *obj,void *);
void     DecrementAutoIncs(INTERNET_SQL_OBJECT *obj,FIELDLIST );
void     IncrementAutoIncs(INTERNET_SQL_OBJECT *obj,FIELDLIST );
void     DecrementAutoIncs(INTERNET_SQL_OBJECT *obj,RECORDLIST );
void     IncrementAutoIncs(INTERNET_SQL_OBJECT *obj,RECORDLIST );

KINT64 GetAutoIncFieldCount(TABLE ,int selectflag);
FIELD_NAME_LIST * FindFieldName(FIELD_NAME_LIST *flist,char *fieldname);
int SetBackgroundAttribute(INTERNET_SQL_OBJECT *obj,BACKGROUND_CMD *BackCmd,char *attribute,char *value);
int  ReadBackgroundCommand(char *commandname,BACKGROUND_CMD *);
int  UpdateBackgroundAttribute(BACKGROUND_CMD *BackCmd);
int  DeleteBackGround(char *name);
int  IsAdmin(char *username,char *databasename);
int  IsManager(char *databasename,char *username,char *groupname);
int  IsGroupMember(char *databasename,char *username,char *usergroupnamem,char *targetgroupnam);
int   LoadAllAutoIndexFiles(INTERNET_SQL_OBJECT *obj,TABLE tbl);
int AddNewLeafNode(INDEX index,char *keyval,INDEXNODE **newnode, KINT64 leftoffset);
int  ReadIndexNodeHeader(INDEX index,KINT64 offset,INDEXNODEHEADER *);
int  WriteIndexNodeHeader(INDEX index,KINT64 offset,INDEXNODEHEADER *hdr);
int  AddNewDirNode(INDEX index,char *keyval,INDEXNODE **newnode, KINT64 leftoffset);
int  UpdateParentNodes(INDEX index,INDEXNODE *curnode,INDEXNODE **newnode,char *keyval,int *done);
int  UpdateAutoIndexFiles(TABLE );
int  FindExactPosForDirUpdate(INDEX index,INDEXNODE *node,char *keyvalue, int *greater, int *position);
int  AddNewRootNode(INDEX index,INDEXNODE **newnode);
char * GetKeyFromNode(INDEX index,INDEXNODE *node,char *buf,int count);
int SizeofExtendedTableHeader(void);
KINT64 FindKmgUserEntry(INTERNET_SQL_OBJECT *obj,char *username,char *pwr, char *pwd, char *mgr,char *grpname,USERINFO *uinfo);
KINT64 SetKmgUser(INTERNET_SQL_OBJECT *obj,char *username,char *password,char *pwr, char *mgr,char *grpname,KINT64 usernumber,USERINFO *uinfo);
int ListLoggedUsers(INTERNET_SQL_OBJECT *obj);
int SetLoginTime(INTERNET_SQL_OBJECT *obj,KINT64 recno);
int  SetLogoutTime(INTERNET_SQL_OBJECT *obj,KINT64 recno);
char *  GetIsqlFieldType( RECORDLIST rec,char *fieldname);
MAINSELECT *  Execute(INTERNET_SQL_OBJECT *obj,char *str);
int GetDefaultValue(INTERNET_SQL_OBJECT *obj,char *type ,char *defaultvalue,int maxtypelen);
TABLE FindOpenCursor(INTERNET_SQL_OBJECT *obj,char *cursorname);
int SQLGet(INTERNET_SQL_OBJECT *obj);
int SQLGetCursorRow(INTERNET_SQL_OBJECT *obj);
int SQLGetCursorCount(INTERNET_SQL_OBJECT *obj);
void UnixDebug(char *msg,void *value,int numvalue);
char *  GetIsqlFieldType(char type);
char SQLUseCommand(INTERNET_SQL_OBJECT *obj);
long DayDiff(char *date1, char *date2);
char * AddDay(char  *datein, long daycount,char *dateout);
char * SubDay(char  *datein, long daycount,char *dateout);
KINT64 KAM_Delay(KINT64 millisec);
void InvertEndianLong(char *longno);
void InvertEndianShort(char *shortno);
long KAM_compress(char *dest, unsigned long destbuflen, char *source, unsigned long sourcebuflen);
long KAM_uncompress(char *dest, unsigned long destbuflen, char *source, unsigned long sourcebuflen);

extern "C"
{
int PwdEncrypt(char *pwd,char *encrypted);
int DeleteDir(char *dirname);
long compress(char *dest, unsigned long *destlen, char *source, unsigned long sourcelen);
long uncompress(char *dest, unsigned long *destlen, char *source, unsigned long sourcelen);
int LoadSrcFromBuffer(long,char *buffer);  
int CompileBufferScript(long,int bufno);
int CompileBufferFile(long,int bufno);
long CreateCompileSlot(void);
int CloseSrcFile(long,char *filename);
int OpenSrcFile(long,char *filename);
void FreeCompileSlot(long compslot);
void SetCompileSlotExtraPointer(long compslot,long ptr);
void SetCompilerIsplMode(long compslot);
void TuwaFreeMallocHeaps(void *heap_head);
MEMORY_HEAP *InitTuwaMemSys(long heapsize /* in megabytes */);
int ReturnFreedBlocksToHeap(MEMORY_HEAP *heaphead);

void  TuwaFsFree(void *heap_ptr,void *inptr);
void ClearAllHeaps(void *heap_head);
int GetChainSize(ALLOC_STRUCT *p);
int GetAdjacentChainSize(ALLOC_STRUCT *p);
int GetBlockCount(ALLOC_STRUCT *p);
int GetChainCount(ALLOC_STRUCT *p);

int ReturnedSomeFreedMem(MEMORY_HEAP *heap);

}
int  SerialInit(int channel);
KINT64 GetAutoIncFieldCount(FIELDLIST Fields,int selectflag);
int ReceivePacket(INTERNET_SQL_OBJECT *obj,int socket,char *kmgrcvbuf,int size,int TimeoutTick,long *recvcount, int *error);
int SendPacket(INTERNET_SQL_OBJECT *obj,int socket,char *kmgrcvbuf,int size,int TimeoutTick,long *count, int *error);
int MinuteDiff(char *time1, char *time2);
int EvalFormula(INTERNET_SQL_OBJECT *obj,RECORDLIST r,RECORDLIST rec,char *retstring, int typecheck);
int ReceiveSync(int socket);
int TransmitSync(int socket);
char FormulaAndExpression(INTERNET_SQL_OBJECT *obj,POSTFIXLINK *pf);
char FormulaExpression(INTERNET_SQL_OBJECT *obj,POSTFIXLINK *pf);
char FormulaSimpleExpression(INTERNET_SQL_OBJECT *obj,POSTFIXLINK *pf);
char FormulaTerm(INTERNET_SQL_OBJECT *obj,POSTFIXLINK *pf);
char FormulaFactor(INTERNET_SQL_OBJECT *obj,POSTFIXLINK *pf);
void GetFormulaToken(INTERNET_SQL_OBJECT *obj);
int EvalFormulaExpression(INTERNET_SQL_OBJECT *obj,RECORDLIST rec,POSTFIXLINK postlink,char *ReturnString, int typecheck);
int CheckFormulaSyntax(INTERNET_SQL_OBJECT *obj,FIELDLIST flist);
RECORDLIST CreateRecordListFromFieldList(FIELDLIST);
int CreateSystemDirs(INTERNET_SQL_OBJECT *obj);
int HasLineContinuator(char *buf);
int RunStoredProcedure(INTERNET_SQL_OBJECT *obj,char *buffer);
int RunSrcFile(INTERNET_SQL_OBJECT *obj,char *filename);
int IncludeDatabase(INTERNET_SQL_OBJECT *obj);
int ValidDatabase(INTERNET_SQL_OBJECT *obj,char *databasename);
void ShowOpenTables(void);
int CreateTableAs(INTERNET_SQL_OBJECT *obj,FIELD_NAME_LIST ** fieldnames,char *tablename);
int GetDirName(INTERNET_SQL_OBJECT *obj,char *dirname);
int VerifyFileSystem(TABLE );
int CreateFileSystem(INTERNET_SQL_OBJECT *obj,char *tablename);
int CheckParentDirs(FIELDLIST fl);
int SQLRun(INTERNET_SQL_OBJECT *obj);
int SQLServer(INTERNET_SQL_OBJECT *obj);
int IsLocalCommand(INTERNET_SQL_OBJECT *obj,char *sqlcommand);
int SQLFetch(INTERNET_SQL_OBJECT *obj);
int UploadFile(INTERNET_SQL_OBJECT *obj);
int DownloadFile(INTERNET_SQL_OBJECT *obj);
int ExecUpLoad(FILE_TRANSFER *ft);
int ExecDownLoad(FILE_TRANSFER *ft);
int ExecLocalUpload(PATH_LIST *PathList);
int CreateUpLoadSourcePath(PATH_LIST *PathList,char *SourcePath);
int CreateUpLoadDestinationPath(PATH_LIST *PathList,char *DestPath);
int ExecRemoteUpLoad(INTERNET_SQL_OBJECT *obj);
int ExecRemoteDownLoad(INTERNET_SQL_OBJECT *obj);
int RemoteUpLoad(char *tablename,char *src,char *dest);
int UploadProc(void);
int DownLoadProc(void);
TABLE  CreateProcTable(INTERNET_SQL_OBJECT *obj);
TABLE CreateRelationsTable(INTERNET_SQL_OBJECT *obj);

char *  GetIsqlKeyType(char type);
char AddToKmgSysTable(INTERNET_SQL_OBJECT *obj,char *table);
long ReceiveExpectedPacketSizeNoWait(USERSLOT *slot,int socket,char *kmgrcvbuf,int size,long *retcount);

int SendPacketNoWait(USERSLOT *slot,int socket,char * data,int size);
int DefaultValueIsAFunction(char *defaultvalue,char *retstring);
int ReceiveFullRequest(USERSLOT *slot,CLIENT_CALL_QUEUE *remotecall,char *buffer,int buffersize, int waitminutes);
int KAM_SocketPoll(int socket);

unsigned long  KAM_htonl(unsigned long no);
unsigned short int KAM_htons(unsigned short int no);
int SendFullRequest(USERSLOT *slot,CLIENT_CALL_QUEUE *remotecall, char * buffer, int bufsize, int waitminutes);
int GetAckPacket(USERSLOT *slot,CLIENT_CALL_QUEUE *remotecall, KMGTRANSMITBUFFERHDR *ack);
int PrintConsole(char *buf);
int StartLog(void);
int StoptLog(void);
int DeleteLog(void);
char DeleteFromKmgSysTable(INTERNET_SQL_OBJECT *obj,char *table);
char  RemoveIndexForThisTable(INTERNET_SQL_OBJECT *obj,char *tablename);
char DeleteFromKmgIndexTable(INTERNET_SQL_OBJECT *obj,char *index);
int CreateViewDefinitionTable(INTERNET_SQL_OBJECT *obj,char *viewname,char *selectptr);
int ExecCreateView(INTERNET_SQL_OBJECT *obj,MAINSELECT *ParentMs,FROMTABLE *ft);
int ExecViewAndSelect(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms);
FROMTABLE * ParseFromTypeSelect(INTERNET_SQL_OBJECT *obj,MAINSELECT *parentms);

int ParseJoins(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms,char *joinname);
int ExecFromSelect(FROMTABLE *ft);
char TableAliasFound(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms,char *alias);
int ParseSelectSelect(INTERNET_SQL_OBJECT *obj,MAINSELECT *parentms,POSTFIXLINK *parentpf,SELECTEDITEM *parentsi);
GROUPBY *CreateGroupBy(MAINSELECT *ms);
char  ParseHaving(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms );
char ExecMainJoinQry( INTERNET_SQL_OBJECT *obj,MAINSELECT *ms,FROMTABLE *fromtable, FROMTABLE *headtable,POSTFIXLINK where,TABLE result);
int ParseUnionInterSectMinusSelect(INTERNET_SQL_OBJECT *obj,MAINSELECT *parentms);
int MatchRecordList(RECORDLIST first,RECORDLIST second);
ORDERBY *CreateOrderBy(MAINSELECT *ms);
KINT64  KAM_CreateMutex(int owner,char *name);
int MiscInit(void);
int KAM_WaitForMutex(USERSLOT *slot,KINT64 handle);
int KAM_ReleaseMutex(USERSLOT *slot,KINT64 handle);

void 	PrintSocketInfo(USERSLOT *slot,int socket,struct sockaddr *client_addr);
int DisplayMessage(USERSLOT *slot,char *message);

char SpaceError(INTERNET_SQL_OBJECT *);
char ParseSelect(INTERNET_SQL_OBJECT *,SUBSELECT *);

char ParseFrom(INTERNET_SQL_OBJECT *,SUBSELECT *ss);

char ParseWhere(INTERNET_SQL_OBJECT *,SUBSELECT *ss);


SUBSELECT *CreateSubSelect(INTERNET_SQL_OBJECT *obj);
SELECTEDITEM *CreateSelectItem(INTERNET_SQL_OBJECT *,MAINSELECT *);
char ParseLengthFunc(INTERNET_SQL_OBJECT *,POSTFIXLINK *pf);
char ParseCharToDate(INTERNET_SQL_OBJECT *,POSTFIXLINK *pf);
char ParseDateToChar(INTERNET_SQL_OBJECT *,POSTFIXLINK *pf);
char ParseLengthFactor(INTERNET_SQL_OBJECT *,POSTFIXLINK *pf);
char ParseCountFunc(INTERNET_SQL_OBJECT *,POSTFIXLINK *pf);
char ParseCountFactor(INTERNET_SQL_OBJECT *,POSTFIXLINK *pf);

int ParseColumnFactor(INTERNET_SQL_OBJECT *,POSTFIXLINK *pf);
int ParseColumnTerm(INTERNET_SQL_OBJECT *,POSTFIXLINK *pf);
char ParseColumnFunc(INTERNET_SQL_OBJECT *,POSTFIXLINK *pf);

int ReserveColumnFunc(INTERNET_SQL_OBJECT *,char *funcname);

char WhereFactor(INTERNET_SQL_OBJECT *,POSTFIXLINK *pf);
char WhereTerm(INTERNET_SQL_OBJECT *,POSTFIXLINK *pf);
char WhereSimpleExpression(INTERNET_SQL_OBJECT *,POSTFIXLINK *pf);
char WhereExpression(INTERNET_SQL_OBJECT *,POSTFIXLINK *pf);
char WhereAndExpression(INTERNET_SQL_OBJECT *,POSTFIXLINK *pf);
char WhereStatement(INTERNET_SQL_OBJECT *,POSTFIXLINK *pf);
char ParseInNotInSet(INTERNET_SQL_OBJECT *,POSTFIXLINK pf);
char ParseWithinNotWithinSet(INTERNET_SQL_OBJECT *,POSTFIXLINK pf);
char ParseBetweenNotBetweenSet(INTERNET_SQL_OBJECT *,POSTFIXLINK pf);
char SubSelectFactor(INTERNET_SQL_OBJECT *,POSTFIXLINK *pf);
char SubSelectTerm(INTERNET_SQL_OBJECT *,POSTFIXLINK *pf);
char SubSelect(INTERNET_SQL_OBJECT *,POSTFIXLINK *);
void GetWhereToken(INTERNET_SQL_OBJECT *);
int SpaceBetweenTokens(INTERNET_SQL_OBJECT *);

char EvalSelItem(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms,POSTFIXLINK postlnk,FROMTABLE *ft,int typecheck,int donteval,KINT64 count);
char EvalSelItemSemantic(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms,SELECTEDITEM *si, FROMTABLE *);
char DoMainSelectSematicAnalysis(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms);
void GetSelectToken(INTERNET_SQL_OBJECT *obj);
char AddViewToKmgSysTable(INTERNET_SQL_OBJECT *obj,char *viewname);
char ExecSqlDelete(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms,RECORDRANGE *,TRANSACTIONTABLE *);
char ExecSqlUpdate(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms,RECORDRANGE *,TRANSACTIONTABLE *);
char UpdateSqlTable(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms,RECORDRANGE *range,TRANSACTIONTABLE *tt);
char ParseSelect(INTERNET_SQL_OBJECT *obj,SUBSELECT *);
char ParseMainSelect(INTERNET_SQL_OBJECT *obj,MAINSELECT **ms);
char ParseFrom(INTERNET_SQL_OBJECT *obj,SUBSELECT *ss);
char ParseMainFrom(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms);
char ParseWhere(INTERNET_SQL_OBJECT *obj,SUBSELECT *ss);
char ParseMainWhere(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms);
KINT64 DropTableName(INTERNET_SQL_OBJECT *obj,char *tablename);
KINT64 DropViewName(INTERNET_SQL_OBJECT *obj,char *tablename);
KINT64 DropIndexName(INTERNET_SQL_OBJECT *obj,char *tablename);
char LoadAndSwap(INTERNET_SQL_OBJECT *obj, MAINSELECT *ms,char type/* for group by ,for order by or uinque*/);
void DeleteTempFiles(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms);
char PrepareSortFile(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms);
int ValidUpdateValue(INTERNET_SQL_OBJECT *obj,TABLE tbl,RECORDLIST ri);



char CreatePrimarySortFile(INTERNET_SQL_OBJECT *obj,KEYLIST kl,
                           KINT64 recordno,
                           KINT64 *tempcount,
                           KINT64 keyperbuffer,
                           KINT64 keylentotal,
                           KINT64 handle
                           );
char  GroupByFileSort(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms);
char  OrderByFileSort(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms);
char  DistinctFileSort(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms);
char  WriteGroupByTable(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms);
char  CloseGroupSortFile(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms);
char  SortDistinctGroupByTable(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms);
char  SortOrderByGroupByTable(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms);
char  SortDistinctSelectDumpTable(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms);
char  SortOrderByDistinctTable(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms);
char  SortOrderBySelectDumpTable(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms);
char PrepareGroupBySortFile(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms);
char PrepareOrderBySortFile(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms);
char PrepareDistinctSortFile(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms);
char GetSortStatistics(INTERNET_SQL_OBJECT *obj,KEYLIST kl,
                       KINT64 *keylentotal,
                       KINT64 *keyperbuffer,
                       KINT64 *keycnt);
extern GLOBAL_CONFIG GlobalCfg;
char AddKmgUser(INTERNET_SQL_OBJECT *obj,char *managername,char *managerpwd,char *username, char *password,char *stat);
KINT64 ExecDescribe(INTERNET_SQL_OBJECT *obj,MAINSELECT **ms,TABLE intbl);
//---------------------------------------------------------
USERSLOT *CreateInternetSqlInstance(void);
void DeleteInternetSqlInstance(USERSLOT *slot);
int IsSelectedIntoTable(INTERNET_SQL_OBJECT *obj);
long RunScriptQueryFunc(INTERNET_SQL_OBJECT *obj);  
char SQLClientConnect(char *sqlcommand);
char ShowEvalStack(INTERNET_SQL_OBJECT *obj,POSTFIXLINK postlnk,int Top);
char *MakeForString(INTERNET_SQL_OBJECT *obj,char *dest,POSTFIXLINK postlnk);
KINT64 ChangeUserStat(INTERNET_SQL_OBJECT *obj,char *managername,char *managerpwd,char *username,char *newstat);
KINT64 CheckSuperUser(INTERNET_SQL_OBJECT *obj,char *username,char *password);
TABLE CreateIndexTable(INTERNET_SQL_OBJECT *obj);
TABLE CreateAccessTable(INTERNET_SQL_OBJECT *obj);
TABLE CreateLockTable(INTERNET_SQL_OBJECT *obj);
KINT64 FindIndexName(INTERNET_SQL_OBJECT *obj,char *indexname,char *dropped);
//------------------------------------------------

//------------------------------------------------
char  RepairDirectory(INDEX index);
char   UpdateIndexDir(char * buf,
                           KINT64 leafno,
                           INDEX index,
                           int  BufCount,
                           char finalleaf);

           

char  GetPivot(INTERNET_SQL_OBJECT *obj,KINT64 handle,char *buf,KINT64 middle,int sumlen);


void    FlushBuffer1(INTERNET_SQL_OBJECT *obj,KINT64 handle,int sumlen);
void    FlushBuffer2(INTERNET_SQL_OBJECT *obj,KINT64 handle,int sumlen);
void MarkBufferChanged(INTERNET_SQL_OBJECT *obj,KINT64 bufferno);
KEYPOINTER GetKeyFromBuffer1( INTERNET_SQL_OBJECT *obj,
									KINT64 keyno,
                              int keyperbuffer,
                              int sumlen,
                              KINT64 handle,
                              KINT64 reccnt
                             );
KEYPOINTER GetKeyFromBuffer2(INTERNET_SQL_OBJECT *obj,
									KINT64 keyno,
                              int keyperbuffer,
                              int sumlen,
                              KINT64 handle
                             );
char InsertKeyIntoIndex(INDEX index ,char *key);
char DeleteKeyFromIndex(INDEX index);
int AddToLastLeaf(INDEX index,char *key,int pos,char greatest);
int MakeFirstLeaf(INDEX index,char *,int ,char );
KINT64  LoadAndSwapUseSingleFile(
                             DATABASE dbf,
                             INDEX index,
                             KINT64 start,
                             KINT64 end,
                             KEYLIST kl,
                             POSTFIXLINK pl,
                             char delstatus,
                             int keylentotal,
                             int *keyperbuffer,
                             char *forstring
                            );
char WriteNodes(KINT64 handle,INDEX index,int KeyPerBuffer);

void InitConfig(void);
char GetListFileName(char *FileName,char *listfile);
char EqualKey(KEYPOINTER key1,KEYPOINTER key2,KEYLIST kl);
char LessThan(KEYPOINTER key1,KEYPOINTER key2,KEYLIST kl);
char GreaterThan(KEYPOINTER key1,KEYPOINTER key2,KEYLIST kl);
void  FileSort(INTERNET_SQL_OBJECT *obj,
			   KINT64 first,
                      KINT64 last,
                      int keyperbuffer,
                      KINT64 sumlen,
                      KEYLIST kl,
                      KINT64 handle,
                      KINT64 reccnt
                           );
 int ListUseSingleFile(
                             TABLE dbf,
                             LISTINFO ListInfo,
                             KINT64 start,
                             KINT64 end,
                             KEYLIST kl,
                             POSTFIXLINK pl,
               		     char delflag,
                             int keylentotal,
                             int keyperbuffer,
                             char *forstring,
                             char *tmpfile
                             );

char DumpListToTable(DATABASE,
                        KEYLIST kl,
                        char *   filename,
                        char   unique,
                        int   keylentotal,
                        int   keyperbuffer,
                        KINT64 handle,
                        LISTINFO lst);

char DumpListToBuffer(DATABASE,
                        KEYLIST kl,
                        char *   filename,
                        char   unique,
                        int   keylentotal,
                        int   keyperbuffer,
                        KINT64 handle,
                        LISTINFO lst);
extern MAINSELECT dummyqueryobject;
void  FileSplit(INTERNET_SQL_OBJECT *obj,
					   KINT64 first,
                KINT64 last, 
                KINT64 *split1, 
                KINT64 *split2,
                int keyperbuffer,
                KINT64 sumlen,
                KEYLIST kl,
                KINT64 handle,
                 KINT64 reccnt);

int ReserveWord(INTERNET_SQL_OBJECT *obj);
int SqlReserveWord(INTERNET_SQL_OBJECT *obj);
int SqlCmdReserveWord(INTERNET_SQL_OBJECT *obj);
char ExecMainSqlSelect(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms, long *rowcount);
int SqlSelectItem(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms,SELECTEDITEM *si);
int SqlSelectTerm(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms,POSTFIXLINK *pf,SELECTEDITEM *si);
int SqlSelectFactor(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms,POSTFIXLINK *pf,SELECTEDITEM *si);
char GetAfterNotToken(INTERNET_SQL_OBJECT *obj);
char ExecWhere(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms,POSTFIXLINK where,FROMTABLE *table);
char EvalColFunc(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms,POSTFIXLINK postlnk,FROMTABLE *FromTables,char typecheck,int eval);
char EvalLengthFunc(INTERNET_SQL_OBJECT *obj,POSTFIXLINK postlnk,FROMTABLE* FromTables,char typecheck);
char EvalCharToDate(INTERNET_SQL_OBJECT *obj,POSTFIXLINK postlnk,FROMTABLE* FromTables,char typecheck);
char EvalDateToChar(INTERNET_SQL_OBJECT *obj,POSTFIXLINK postlnk,FROMTABLE* FromTables,char typecheck);
char *ToChar(INTERNET_SQL_OBJECT *obj,KINT64 date,char *format);
char *ToChar(INTERNET_SQL_OBJECT *obj,char *datebuf,char *format);
KINT64 ToDate(INTERNET_SQL_OBJECT *obj,char *string);
char AddToKmgIndexTable(INTERNET_SQL_OBJECT *obj,TABLE tbl,INDEX ndx);
char CheckOrderByList(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms);
char CheckGroupByList(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms);
char ExecSqlUndelete(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms,RECORDRANGE *range,TRANSACTIONTABLE *tt);
char ParseWithNotWithRecordRange(INTERNET_SQL_OBJECT *obj,RECORDRANGE **rr,int token) ;
char ParseBetNotBetRecordRange(INTERNET_SQL_OBJECT *obj,RECORDRANGE **rr,int token) ;
char ParseInNotInRecordRange(INTERNET_SQL_OBJECT *obj,RECORDRANGE **rr,int token);
char ParseEqRecordRange(INTERNET_SQL_OBJECT *obj,RECORDRANGE **rr,int token); 
KINT64 ParseMainTableName(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms);
int EvalSetItems(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms,POSTFIXLINK pf,int settype, int typecheck);
int RemoveTRANSTBL(INTERNET_SQL_OBJECT *obj,char *username);
char RemoveTransactionTable(INTERNET_SQL_OBJECT *obj,char *username,char *tablename);
char CreateAllTransTable(INTERNET_SQL_OBJECT *obj);
char KmgLogin(INTERNET_SQL_OBJECT *obj,char *username,char *password);
KINT64 FindKmgUser(INTERNET_SQL_OBJECT *obj,char *username,char *password,char *pwr,int *its_a_superuserid);
char CreateUserTempDir(INTERNET_SQL_OBJECT *obj,char *username,char *password,char *groupname);
KINT64 CheckKmgUser(INTERNET_SQL_OBJECT *obj,char *username,char *password,char *pwr,char *mgrname,char *grpname,char *dbname, int *its_a_superuserid);
int CheckUserRightFileAndPasswordFile(INTERNET_SQL_OBJECT *obj,char *username,char *password,char *group,char *dbname);
TABLE OpenUserRightsFile(INTERNET_SQL_OBJECT *obj,char *username);
char CheckElligibility(INTERNET_SQL_OBJECT *obj,char *username);
char FormulaStatement(INTERNET_SQL_OBJECT *obj,POSTFIXLINK *pf);
int ServerStarted(USERSLOT *);
int StartServer(USERSLOT *);
int StopServer(USERSLOT *);;
int ServerStopped(USERSLOT *);
int ServerDisplayOn(USERSLOT *);
int ServerDisplayOff(USERSLOT *);
int CloseServerWindow(USERSLOT *);
void ShowShellPrompt(USERSLOT *);
#ifndef SUNUNIX
int CreateShellWindow(USERSLOT *,HWND hwnd, UINT message,UINT wParam,LONG lParam);
int  CreateServerDisplayWindow(USERSLOT *,HWND hwnd, UINT message,UINT wParam,LONG lParam);
int  ProcessServerDisplayWindowMessage(HWND hwnd, UINT message,UINT wParam,LONG lParam);
#endif   
int GetBuflenSkipEolCr(char *buf);
int IsLocalClientMode(USERSLOT *);
int KAM_DeleteMutex(USERSLOT *slot,KINT64 handle);
int KAM_WaitForMutexWithoutSlot(KINT64 handle, int time);
int KAM_ReleaseMutexWithoutSlot(KINT64 handle);

extern KINT64 GlobalInitalizeMutex;

long KAM_CreateServerThread(void *param);
void ServerThread (void *serverparams);
INDEXOBJECT *new_INDEXOBJECT(INTERNET_SQL_OBJECT *obj);
INDEX_HOPS *new_INDEX_HOPS(INTERNET_SQL_OBJECT *obj) ;
INDEXNODE *new_INDEXNODE(INTERNET_SQL_OBJECT *obj);
TABLEOBJECT *new_TABLEOBJECT(INTERNET_SQL_OBJECT *obj);
RECORDOBJECT *new_RECORDOBJECT(INTERNET_SQL_OBJECT *obj);
FIELDOBJECT *new_FIELDOBJECT(INTERNET_SQL_OBJECT *obj);
KEYOBJECT * new_KEYOBJECT(INTERNET_SQL_OBJECT *obj);
LISTOBJECT  *new_LISTOBJECT(INTERNET_SQL_OBJECT *obj);
__postfixlink__ *new___postfixlink__(INTERNET_SQL_OBJECT *obj);
__sysvartable__ * new___sysvartable__(INTERNET_SQL_OBJECT *obj);
MAINSELECT* new_MAINSELECT(INTERNET_SQL_OBJECT *obj);
SELECTEDITEM *new_SELECTEDITEM(INTERNET_SQL_OBJECT *obj) ;
SUBSELECT* new_SUBSELECT(INTERNET_SQL_OBJECT *obj);
GROUPBY *new_GROUPBY(INTERNET_SQL_OBJECT *obj);
GROUPITEM *new_GROUPITEM(INTERNET_SQL_OBJECT *obj);
ORDERBY *new_ORDERBY(INTERNET_SQL_OBJECT *obj);
ORDERITEM *new_ORDERITEM(INTERNET_SQL_OBJECT *obj);
UNIQUESORT *new_UNIQUESORT(INTERNET_SQL_OBJECT *obj);
FROMTABLE  *new_FROMTABLE(INTERNET_SQL_OBJECT *obj);
RECORDRANGE* new_RECORDRANGE(INTERNET_SQL_OBJECT *obj);
LOCKINFO *new_LOCKINFO(INTERNET_SQL_OBJECT *obj);
TRANSACTIONTABLE*  new_TRANSACTIONTABLE(INTERNET_SQL_OBJECT *obj);
MODIFIEDRECORDS *new_MODIFIEDRECORDS(INTERNET_SQL_OBJECT *obj);
POSTFIXLINK GetNewLink(INTERNET_SQL_OBJECT *obj,POSTFIXLINK *postlnk);
void   InitIndexNode(INDEXNODE *vp);
INDEX_HOPS *AdjustParentIfFirstKeyModifiedInTheNode(INDEX index);
INDEX_HOPS *RemoveKeyFromParentIfKeyCountIsZeroInTheNode(INDEX index);
int RemoveIndexNodeFromNodeChain(INDEX index, INDEXNODEHEADER *h);
int  AddToFreeNodeList(INDEX index, INDEXNODEHEADER *h);
INDEXNODEHEADER *FindFreeNode(INDEX index);
int FindKeyValue(INTERNET_SQL_OBJECT *obj,TABLE tbl,RECORDLIST ri,char *value);
int UpdateTableFormulaField(INTERNET_SQL_OBJECT *obj,RECORDLIST rec);
RECORDLIST  AddSI(MAINSELECT *ms,RECORDLIST *qryfld, SELECTEDITEM *si);
char EvalSubSelect(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms,SUBSELECT **ss,char typecheck,KINT64 *rowcount);
int FindLongestNameLen(ENUM_LIST *el);
char blankline(char *buf);
TABLE OpenUserTransTable(INTERNET_SQL_OBJECT *obj,char *username);
int ExecSelectPortion(INTERNET_SQL_OBJECT *obj,MAINSELECT **ms, int forview);
int ParseSelectPortion(INTERNET_SQL_OBJECT *obj,MAINSELECT **ms, int forview);
extern int file_open_count;
extern int file_close_count;
int RemoveTableFromChain(INTERNET_SQL_OBJECT *obj,TABLE tbl);
long WaitForTableMutex(TABLE t,KAM_MUTEX *km, int mutextype,long timeout);
long ReleaseTableMutex(TABLE t,KAM_MUTEX *km);
long KAM_QueryFunc(INTERNET_SQL_OBJECT *obj);
void KAM_DrawBorder(INTERNET_SQL_OBJECT *obj);
int GetDumpFileName(INTERNET_SQL_OBJECT *obj,char *namebuf,char *ext);
int SetSubSelect(INTERNET_SQL_OBJECT *obj,POSTFIXLINK *pf);
int EvalAllSet(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms,POSTFIXLINK pf,POSTFIXLINK Oper1,POSTFIXLINK Oper2,int typecheck);
int EvalInSet(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms,POSTFIXLINK pl,POSTFIXLINK Oper1,POSTFIXLINK Oper2,int typecheck);
int EvalBetweenSet(INTERNET_SQL_OBJECT *obj,MAINSELECT *ms,POSTFIXLINK pl,POSTFIXLINK Oper1,POSTFIXLINK Oper2,int typecheck);
int ParseSetStatements(INTERNET_SQL_OBJECT *obj,POSTFIXLINK *pl);
char ParseMatchFunc(INTERNET_SQL_OBJECT *obj,POSTFIXLINK *pf,POSTFIXLINK parent);
char ParseMatchFactor(INTERNET_SQL_OBJECT *obj,POSTFIXLINK *pf);
char EvalMatchExpression(INTERNET_SQL_OBJECT *obj,POSTFIXLINK postlnk,FROMTABLE* FromTables,char typecheck, int match);
long ExecMatch(INTERNET_SQL_OBJECT *obj,char *str1,char *str2);
RECORDLIST FindFieldFromTables(char *field,FROMTABLE *FromTables,int *count);
void BM(char *x, int m, char *y, int n);
char *BoyleMooreSearch( char *pat, char *text,int n, int *skip,int *d,int *f,int maxchar);
void preprocpat( char *pat, int *skip, int *d, int *f, int maxchar );
int SqlInsertFactor(INTERNET_SQL_OBJECT *obj,POSTFIXLINK *pf,INSERTITEM *ii);
int SqlInsertTerm(INTERNET_SQL_OBJECT *obj,POSTFIXLINK *pf,INSERTITEM *ii);
int SqlInsertItem(INTERNET_SQL_OBJECT *obj,INSERTITEM *ii);
int ParseInsertSelect(INTERNET_SQL_OBJECT *obj,POSTFIXLINK *insertpf,INSERTITEM *parentsi);
char EvalInsertItemSemantic(INTERNET_SQL_OBJECT *obj,INSERTITEM *ii,int typecheck);
char EvalInsertItem(INTERNET_SQL_OBJECT *obj,POSTFIXLINK postlnk,int typecheck,int donteval,KINT64 count);
int AdjustDecimalPoint(RECORDLIST ri,char *buf);
extern USERSLOT *slot_head;
int VerifyDatabaseHome(INTERNET_SQL_OBJECT *obj, char *home);
int ParseBetweenStatements(INTERNET_SQL_OBJECT *obj,POSTFIXLINK *pl);
char BetweenStatement(INTERNET_SQL_OBJECT *obj,POSTFIXLINK *pf);
int SetShellLogFileName(USERSLOT *slot,char *logfilename);
int SetShellLogEnable(USERSLOT *slot);
int SetShellLogDisable(USERSLOT *slot);
int SendCommPacket(INTERNET_SQL_OBJECT *obj,int socket, char * buffer, int bufsize, int waitminutes, int commandtype);
int SendSqlServerCommPacketConnectQ(INTERNET_SQL_OBJECT *obj,CONNECT_QUEUE *queue, char * buffer, int bufsize, int commandtype);
int GetRxPkt(INTERNET_SQL_OBJECT *obj, int socket,COMMAND_FORMAT *buf,long wait);
int ReceiveCommPacket(INTERNET_SQL_OBJECT *obj,int socket, char * buffer, int bufsize, int waitminutes, int commandtype);
void ProcessClientRequestUsingConnectQ(INTERNET_SQL_OBJECT *obj,CONNECT_QUEUE *connectq,KAMRANGA_COMM_PACKET *InMsg);
KINT64 StartKamrangaNetworkAgentConnectQ(long startid,char *srvrname);
void EndConnectQThreads(USERSLOT *slot);
KINT64 TransmitRemoteMsg(INTERNET_SQL_OBJECT *obj);
int ConfigValidKey(char *tmpbuf1);
int ReadConfigFile(INTERNET_SQL_OBJECT *obj,char *config_filename);
int ValidateConfig(INTERNET_SQL_OBJECT *obj, int configfileexists);



char GetLastLoggersPrivilege(USERSLOT * slot);
char * GetLastLoginName(USERSLOT * slot,char *namebuf);
char * GetLastPwd(USERSLOT * slot,char *namebuf);

int GetBufferpColumn(INTERNET_SQL_OBJECT *obj);

int ListPrimaryToForeignRelation(INTERNET_SQL_OBJECT *obj,char *tablename);
int ListForeignToPrimaryRelation(INTERNET_SQL_OBJECT *obj,char *tablename);
int ConcatKeyInfo(KEYLIST *kl,KEYLIST *tmpkl);

int ParseReferenceTableFromKeyList(INTERNET_SQL_OBJECT *obj,KEYLIST kl, char *ownertablename,REFTABLE **reftable);

int ParseReferenceTable(INTERNET_SQL_OBJECT *obj,char *fieldname, char *ownertablename,REFTABLE **reftable);
int DeleteReferenceTable(INTERNET_SQL_OBJECT *obj,REFTABLE **reftable);

int ParseCheck(INTERNET_SQL_OBJECT *obj, CHECK_STRING **check); 
int DeleteCheck(INTERNET_SQL_OBJECT *obj, CHECK_STRING **check); 
int MakeRelationEntry(INTERNET_SQL_OBJECT *obj,char *ownertablename,char *fieldname,char *reference_tablename);

int CheckForiegnKeyInsertibility(INTERNET_SQL_OBJECT *obj,TABLE tbl,RECORDLIST r ,char *value);

int DeleteFromForeignTable(INTERNET_SQL_OBJECT *obj, TABLE fromtable);

int AlterForeignKeyFields(INTERNET_SQL_OBJECT *obj, TABLE tbl,FIELDLIST flist,int rename, int add);
TABLE CreateTriggerTable(INTERNET_SQL_OBJECT *obj);
int  ExecDeleteFromForeignTable(INTERNET_SQL_OBJECT *obj);

int CopyObjLoginDatabaseInfo(INTERNET_SQL_OBJECT *toobj,INTERNET_SQL_OBJECT *fromobj);
int CheckFieldDropability(INTERNET_SQL_OBJECT *obj, TABLE tbl,FIELDLIST flist);
int CheckFieldModifyability(INTERNET_SQL_OBJECT *obj, TABLE tbl,FIELDLIST flist);
int CompareType(char type1,char type2);
int FieldNumber(FIELDLIST flist,char *fieldname);
int ExecRenameForeignKey(INTERNET_SQL_OBJECT *obj);
int ParseOnDeleteOnUpdate(INTERNET_SQL_OBJECT *obj ,REFTABLE *head);
int ParseConstraint(INTERNET_SQL_OBJECT *obj ,CHECK_STRING **chk);
int SQLDropTrigger(INTERNET_SQL_OBJECT *obj ); 
int SQLCreateTrigger(INTERNET_SQL_OBJECT *obj ); 
int ParseTriggerString(INTERNET_SQL_OBJECT *obj);
int ExecSqlDownload(INTERNET_SQL_OBJECT *obj,char *tablename, 
				  char *fieldname, 
				  KINT64 recordnumber, 
				  KINT64 offset, 
				  int size,
				  char *buffer,
				  int mode
				  );
int ExecSqlWriteStorage(INTERNET_SQL_OBJECT *obj,char *tablename, 
				  char *fieldname, 
				  char *fieldvalue,
				  KINT64 offset,
				  KINT64  size,
				  char *data, 
				 int mode
				  );


int ValidateStorageFieldValue(TABLE tbl,char *fieldname, char *fieldvalue);

int HasStorageField(TABLE );
int DateHasSeparator(char *buffer);
char *GetIsqlReferenceTableName(char *name);
char *GetIsqlForeignKeyFlag(INTERNET_SQL_OBJECT *obj,int flag);
int ParseInternatioalLanguage(INTERNET_SQL_OBJECT *obj,char *internation_language);

/* #39: per-thread logical cwd + relative-path resolution. MUST be last here so
 * its fopen/remove/rename/chmod macros sit AFTER every system header. Replaces
 * the process-global _chdir; KamGetThreadCwd is normalized to _getcwd's
 * canonical form so read-path comparisons hold. Removes the shared cwd so
 * concurrent connections no longer need the ExecMutex. */
#include "kampath.h"





