[sword-svn] r232 - in trunk/src/SlideBible: . platform platform/win32 platform/wince

kalemas at crosswire.org kalemas at crosswire.org
Fri Apr 9 10:44:01 MST 2010


Author: kalemas
Date: 2010-04-09 10:44:00 -0700 (Fri, 09 Apr 2010)
New Revision: 232

Modified:
   trunk/src/SlideBible/SlideBible.vcproj
   trunk/src/SlideBible/main.cpp
   trunk/src/SlideBible/platform/win32/dirent.cpp
   trunk/src/SlideBible/platform/win32/dirent.h
   trunk/src/SlideBible/platform/wince/time_ce.cpp
   trunk/src/SlideBible/platform/wince/unistd.cpp
   trunk/src/SlideBible/platform/xmlParser.cpp
   trunk/src/SlideBible/platform/xmlParser.h
   trunk/src/SlideBible/sbBase.h
   trunk/src/SlideBible/sbControl.cpp
   trunk/src/SlideBible/sbControl.h
   trunk/src/SlideBible/sbCore.cpp
   trunk/src/SlideBible/sbCore.h
   trunk/src/SlideBible/sbFeatures.cpp
   trunk/src/SlideBible/sbFeatures.h
   trunk/src/SlideBible/sbItem.cpp
   trunk/src/SlideBible/sbItem.h
   trunk/src/SlideBible/sbList.cpp
   trunk/src/SlideBible/sbList.h
   trunk/src/SlideBible/sbTheme.cpp
   trunk/src/SlideBible/sbTheme.h
   trunk/src/SlideBible/todo.txt
Log:
+	interface description format, xml
+	fopen in application dir for wince
+	render tasks
+		stretch mode - render performed on surface with custom size, then StretchBlt on screen
+		cache background on first render
+		render recieve horizontal displacement
+		remove sbCore::SURFACE
+	keypad
+		cursor
+		active control
+		control / list mode
+			method to smooth-delayed-scroll list
+	lists instead menus

Modified: trunk/src/SlideBible/SlideBible.vcproj
===================================================================
--- trunk/src/SlideBible/SlideBible.vcproj	2010-04-09 17:38:27 UTC (rev 231)
+++ trunk/src/SlideBible/SlideBible.vcproj	2010-04-09 17:44:00 UTC (rev 232)
@@ -57,11 +57,14 @@
 				StringPooling="true"
 				MinimalRebuild="false"
 				RuntimeLibrary="1"
+				StructMemberAlignment="3"
 				RuntimeTypeInfo="true"
 				UsePrecompiledHeader="0"
 				BrowseInformation="1"
 				WarningLevel="3"
 				DebugInformationFormat="1"
+				CompileForArchitecture="2"
+				EnableFloatingPointEmulation="true"
 			/>
 			<Tool
 				Name="VCManagedResourceCompilerTool"
@@ -341,6 +344,7 @@
 				PreprocessorDefinitions="NDEBUG;_WIN32_WCE=$(CEVER);UNDER_CE;$(PLATFORMDEFINES);WINCE;_WINDOWS;$(ARCHFAM);$(_ARCHFAM_);_UNICODE;UNICODE"
 				StringPooling="true"
 				RuntimeLibrary="0"
+				StructMemberAlignment="3"
 				UsePrecompiledHeader="0"
 				WarningLevel="3"
 				DebugInformationFormat="3"
@@ -366,7 +370,7 @@
 				DelayLoadDLLs="$(NOINHERIT)"
 				GenerateDebugInformation="true"
 				ProgramDatabaseFile="$(OutDir)/SlideBible.pdb"
-				SubSystem="0"
+				SubSystem="8"
 				StackReserveSize="65536"
 				StackCommitSize="4096"
 				OptimizeReferences="2"
@@ -1950,7 +1954,7 @@
 			</File>
 		</Filter>
 		<Filter
-			Name="utility"
+			Name="platform"
 			>
 			<Filter
 				Name="header"

Modified: trunk/src/SlideBible/main.cpp
===================================================================
--- trunk/src/SlideBible/main.cpp	2010-04-09 17:38:27 UTC (rev 231)
+++ trunk/src/SlideBible/main.cpp	2010-04-09 17:44:00 UTC (rev 232)
@@ -27,8 +27,12 @@
 #include <unistd.cpp>
 #endif
 
+#include <filemgr.h>
 
+using sword::FileDesc;
+using sword::FileMgr;
 
+
 // Globals
 HWND Window = NULL;
 
@@ -37,25 +41,28 @@
 {
 	va_list args;
 
-	static FILE * file = NULL;
+	static FileDesc * file = NULL;
 	
-	file = fopen( "log.txt", file == NULL ? "w" : "a" );
+	file = FileMgr::getSystemFileMgr()->open("log.txt", file == NULL ? FileMgr::WRONLY|FileMgr::CREAT|FileMgr::TRUNC : FileMgr::WRONLY|FileMgr::APPEND );
+	
+	if (file->getFd() <= 0) return;
+	
+	va_start(args, format);
 
-	if (file == NULL) return;
+	char buffer [1024];
+	int l = _vsnprintf(buffer, 1024, format, args);
 
-	va_start(args, format);
-	vfprintf(file, format, args);
-	
-#ifdef _WIN32_WCE
-	vprintf(format, args);
+	file->write(buffer,l == -1 ? 1024 : l);
+
+#ifndef _WIN32_WCE
+	OutputDebugStringA(buffer);
 #else
-	char buffer [1024];
-	vsnprintf(buffer, 1024, format, args);
-	OutputDebugStringA(buffer);
+	printf(buffer);
 #endif
+
 	va_end(args);
 
-	fclose(file);
+	FileMgr::getSystemFileMgr()->close(file);
 }
 
 void sbFillRect ( sbSurface rc, const sbRect * rect, sbColor color )
@@ -69,11 +76,16 @@
 sbFont sbMakeFont ( int size, const TCHAR * face, bool bold, bool italic )
 {
 	LOGFONT lf; memset(&lf, 0, sizeof(LOGFONT));
-	lf.lfHeight = size;			lf.lfWidth = 0;
-	lf.lfEscapement = 0;		lf.lfOrientation = 0;
-	if (bold) lf.lfWeight = 600; else lf.lfWeight = 500;
-	lf.lfItalic = italic;		lf.lfUnderline = FALSE;
-	lf.lfStrikeOut = FALSE;		lf.lfCharSet = DEFAULT_CHARSET;
+	lf.lfHeight = size;
+	lf.lfWidth = 0;
+	lf.lfEscapement = 0;
+	lf.lfOrientation = 0;
+	//if (bold) lf.lfWeight = FW_BOLD; else lf.lfWeight = FW_NORMAL;
+	lf.lfWeight = bold ? FW_SEMIBOLD : FW_NORMAL;
+	lf.lfItalic = italic;
+	lf.lfUnderline = FALSE;
+	lf.lfStrikeOut = FALSE;
+	lf.lfCharSet = DEFAULT_CHARSET;
 	lf.lfOutPrecision = OUT_RASTER_PRECIS;
 	lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
 	lf.lfQuality = CLEARTYPE_QUALITY;
@@ -342,24 +354,36 @@
 	DeleteDC ( (HDC)surface );
 }
 
+void sbDrawLine ( sbSurface rc, sbPoint from, sbPoint to, sbColor color, int thickness )
+{
+	HPEN pen = CreatePen(PS_SOLID, thickness, RGB(color.red,color.green,color.blue) );
+	SelectObject((HDC)rc,pen);
+	MoveToEx((HDC)rc, from.x, from.y, (LPPOINT)NULL);
+	LineTo((HDC)rc, to.x, to.y); 
+}
 
+sbColor sbSelectColor ( sbSurface rc, sbColor color )
+{
+	COLORREF old = SetTextColor((HDC)rc,RGB(color.red,color.green,color.blue));
+	return sbColor(GetRValue(old),GetGValue(old),GetBValue(old));
+}
+
+
 void            sbGetScreenRect        ( sbRect & rect )          { sbAssert (Window==NULL); RECT wr; GetClientRect(Window,&wr); rect.left = wr.left; rect.top = wr.top; rect.right = wr.right; rect.bottom = wr.bottom; }
-int             sbGetLastError         ()                         { return GetLastError(); }
 void            sbDeleteFont           ( sbFont font )            { DeleteObject ((HFONT)font); }
 void            sbDeleteBitmap         ( sbBitmap bitmap )        { DeleteObject ((HBITMAP)bitmap); }
 sbFont          sbSelectFont           ( sbSurface rc, sbFont font ) { return (sbFont)SelectObject((HDC)rc,(HFONT)font); }
-sbColor         sbSelectColor          ( sbSurface rc, sbColor color ) { COLORREF old = SetTextColor((HDC)rc,RGB(color.red,color.green,color.blue)); return sbColor(GetRValue(old),GetGValue(old),GetBValue(old)); }
 void            sbDrawText             ( sbSurface rc, int x, int y, const TCHAR * text, int count ) { ExtTextOut((HDC)rc, x, y, ETO_OPAQUE, NULL, text, count, 0); }
 void            sbSleep                ( int milliseconds )       { Sleep (milliseconds); }
 void            sbSetTimer             ( const int timer, int refreshRate ) { sbAssert(Window==NULL); SetTimer(Window, timer, refreshRate, (TIMERPROC) NULL); }
 void            sbKillTimer            ( const int timer )        { sbAssert(Window==NULL); KillTimer(Window, timer); }
-void            sbBitBlt               ( sbSurface toRc, int left, int top, int width, int height, sbSurface fromRc, int x, int y) { BitBlt((HDC)toRc, left, top, width, height, (HDC)fromRc, x, y, SRCCOPY); }
+void            sbBitBlt               ( sbSurface toRc, sbRect toRect , sbSurface fromRc, sbPoint fromXy ) { BitBlt((HDC)toRc, toRect.left, toRect.top, toRect.width(), toRect.height(), (HDC)fromRc, fromXy.x, fromXy.y, SRCCOPY); }
+void            sbStretchBlt           ( sbSurface toRc, sbRect toRect , sbSurface fromRc, sbRect fromRect ) { StretchBlt((HDC)toRc, toRect.left, toRect.top, toRect.width(), toRect.height(), (HDC)fromRc, fromRect.left, fromRect.top, fromRect.width(), fromRect.height(), SRCCOPY); }
 long            sbGetTickCount         ()                         { return GetTickCount(); }
 void            sbExit                 ( int code )               { PostQuitMessage(code); }
 
 
 
-
 LRESULT CALLBACK wndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
 {
 	switch ( message )
@@ -435,19 +459,21 @@
 	return DefWindowProc(hwnd, message, wParam, lParam);
 }
 
+#include <stdio.h>
+
 int WINAPI _tWinMain ( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )
 {
 	const TCHAR * appClass = L"SlideBible Application";
 	const TCHAR * appTitle = L"SlideBible";
 	
-	int returnValue = 0;
+	int exitCode = 0;
 
 	HWND hwnd = FindWindow ( appClass, appTitle );
 
 	if (hwnd)
 	{
 		SetForegroundWindow(hwnd);
-		returnValue = -1;
+		exitCode = -1;
 	}
 	else
 	{
@@ -478,13 +504,14 @@
 				NULL, NULL, hInstance, NULL );
 #else
 			Window = CreateWindow( appClass, appTitle, WS_VISIBLE,
-				CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
+				//CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
+				CW_USEDEFAULT, CW_USEDEFAULT, 480, 640,
 				NULL, NULL, hInstance, NULL );
 #endif
 
 			if ( Window == NULL )
 			{
-				sbMessage ( "Can not create window becouse of %i error.\n", GetLastError() );
+				sbMessage ( "Can not create window because of %i error.\n", GetLastError() );
 
 				PostQuitMessage ( 1 );
 			}
@@ -508,12 +535,10 @@
 
 				DestroyWindow(Window);
 
-				returnValue = message.wParam;
+				exitCode = message.wParam;
 			}
 		}
 	}
 
-	//dumpLeakReport();
-
-	return returnValue;
+	return exitCode;
 }

Modified: trunk/src/SlideBible/platform/win32/dirent.cpp
===================================================================
--- trunk/src/SlideBible/platform/win32/dirent.cpp	2010-04-09 17:38:27 UTC (rev 231)
+++ trunk/src/SlideBible/platform/win32/dirent.cpp	2010-04-09 17:44:00 UTC (rev 232)
@@ -1,58 +1,131 @@
-#include <dirent.h>
-#include <stdio.h>
-#include <swbuf.h>
-
-//#include <unistd.h>//WIN32
-
-using sword::SWBuf;
-
-DIR* opendir(const char *pSpec)
-{
-	DIR *pDir = new DIR;
-    memset(pDir, 0, sizeof(DIR));
-	pDir->dirPath = new SWBuf();
-    TCHAR buf[MAX_PATH];
-	mbstowcs(buf, pDir->dirPath->c_str(), MAX_PATH);
-	*(pDir->dirPath) = pSpec;//adaptpath(pSpec); //WIN32
-	*(pDir->dirPath) += "\\*";
-	pDir->hFind = FindFirstFile(buf, &(pDir->wfd));
-	return pDir;
-}
-
-void closedir(DIR * pDir)
-{
-    if(pDir->hFind) FindClose( pDir->hFind );
-	delete pDir->dirPath;
-    delete pDir;
-}
-
-struct dirent* readdir(DIR *pDir)
-{
-    char buf[MAX_PATH + 1];
-	if (pDir->hFind)
-	{
-		wcstombs(buf, pDir->wfd.cFileName, MAX_PATH);
-
-		strcpy(pDir->de.d_name, buf);
-        if ( !FindNextFile(pDir->hFind, &(pDir->wfd)) )
-		{
-            FindClose(pDir->hFind);
-			pDir->hFind = NULL;
-        }
-
-		return &pDir->de;
-	}
-
-	return NULL;
-}
-
-void rewinddir(DIR* dir)
-{
-    wchar_t buf[MAX_PATH];
-
-    if(dir->hFind) FindClose(dir->hFind);
-
-	mbstowcs(buf, dir->dirPath->c_str(), MAX_PATH);
-
-	dir->hFind = FindFirstFile(buf, &(dir->wfd));
-}
+/*
+
+    Implementation of POSIX directory browsing functions and types for Win32.
+
+    Kevlin Henney (mailto:kevlin at acm.org), March 1997.
+
+    Copyright Kevlin Henney, 1997. All rights reserved.
+
+    Permission to use, copy, modify, and distribute this software and its
+    documentation for any purpose is hereby granted without fee, provided
+    that this copyright and permissions notice appear in all copies and
+    derivatives, and that no charge may be made for the software and its
+    documentation except to cover cost of distribution.
+    
+    This software is supplied "as is" without express or implied warranty.
+
+    But that said, if there are any problems please get in touch.
+
+*/
+
+#include <dirent.h>
+#include <errno.h>
+#include <io.h>
+#include <stdlib.h>
+#include <string.h>
+
+struct SWDLLEXPORT DIR
+{
+    long                handle; /* -1 for failed rewind */
+    struct _finddata_t  info;
+    struct dirent       result; /* d_name null iff first time */
+    char                *name;  /* NTBS */
+};
+
+SWDLLEXPORT DIR *opendir(const char *name)
+{
+    DIR *dir = 0;
+
+    if(name && name[0])
+    {
+        size_t base_length = strlen(name);
+        const char *all = /* the root directory is a special case... */
+            strchr("/\\", name[base_length - 1]) ? "*" : "/*";
+
+        if((dir = (DIR *) malloc(sizeof *dir)) != 0 &&
+           (dir->name = (char *) malloc(base_length + strlen(all) + 1)) != 0)
+        {
+            strcat(strcpy(dir->name, name), all);
+
+            if((dir->handle = _findfirst(dir->name, &dir->info)) != -1)
+            {
+                dir->result.d_name = 0;
+            }
+            else /* rollback */
+            {
+                free(dir->name);
+                free(dir);
+                dir = 0;
+            }
+        }
+        else /* rollback */
+        {
+            free(dir);
+            dir   = 0;
+            errno = ENOMEM;
+        }
+    }
+    else
+    {
+        errno = EINVAL;
+    }
+
+    return dir;
+}
+
+SWDLLEXPORT int closedir(DIR *dir)
+{
+    int result = -1;
+
+    if(dir)
+    {
+        if(dir->handle != -1)
+        {
+            result = _findclose(dir->handle);
+        }
+
+        free(dir->name);
+        free(dir);
+    }
+
+    if(result == -1) /* map all errors to EBADF */
+    {
+        errno = EBADF;
+    }
+
+    return result;
+}
+
+SWDLLEXPORT struct dirent *readdir(DIR *dir)
+{
+    struct dirent *result = 0;
+
+    if(dir && dir->handle != -1)
+    {
+        if(!dir->result.d_name || _findnext(dir->handle, &dir->info) != -1)
+        {
+            result         = &dir->result;
+            result->d_name = dir->info.name;
+        }
+    }
+    else
+    {
+        errno = EBADF;
+    }
+
+    return result;
+}
+
+SWDLLEXPORT void rewinddir(DIR *dir)
+{
+    if(dir && dir->handle != -1)
+    {
+        _findclose(dir->handle);
+        dir->handle = _findfirst(dir->name, &dir->info);
+        dir->result.d_name = 0;
+    }
+    else
+    {
+        errno = EBADF;
+    }
+}

Modified: trunk/src/SlideBible/platform/win32/dirent.h
===================================================================
--- trunk/src/SlideBible/platform/win32/dirent.h	2010-04-09 17:38:27 UTC (rev 231)
+++ trunk/src/SlideBible/platform/win32/dirent.h	2010-04-09 17:44:00 UTC (rev 232)
@@ -1,23 +1,34 @@
-#include <windows.h>
-#include <string.h>
-#include <swbuf.h>
-
-using sword::SWBuf;
-
-struct dirent
-{
-  char d_name[MAX_PATH];
-};
-
-typedef struct
-{
-  WIN32_FIND_DATA  wfd;
-  HANDLE           hFind;
-  SWBuf           *dirPath;
-  dirent           de;
-} DIR;
-
-DIR    * opendir   ( const char * path );
-dirent * readdir   ( DIR * pDir );
-void     closedir  ( DIR * pDir);
-void     rewinddir ( DIR * dir );
\ No newline at end of file
+/*
+
+    Declaration of POSIX directory browsing functions and types for Win32.
+
+    Kevlin Henney (mailto:kevlin at acm.org), March 1997.
+
+    Copyright Kevlin Henney, 1997. All rights reserved.
+
+    Permission to use, copy, modify, and distribute this software and its
+    documentation for any purpose is hereby granted without fee, provided
+    that this copyright and permissions notice appear in all copies and
+    derivatives, and that no charge may be made for the software and its
+    documentation except to cover cost of distribution.
+    
+*/
+
+#ifndef DIRENT_INCLUDED
+#define DIRENT_INCLUDED
+
+#include <defs.h>
+
+typedef struct DIR DIR;
+
+struct SWDLLEXPORT dirent
+{
+    char *d_name;
+};
+
+SWDLLEXPORT DIR           *opendir(const char *);
+SWDLLEXPORT int           closedir(DIR *);
+SWDLLEXPORT struct dirent *readdir(DIR *);
+SWDLLEXPORT void          rewinddir(DIR *);
+
+#endif

Modified: trunk/src/SlideBible/platform/wince/time_ce.cpp
===================================================================
--- trunk/src/SlideBible/platform/wince/time_ce.cpp	2010-04-09 17:38:27 UTC (rev 231)
+++ trunk/src/SlideBible/platform/wince/time_ce.cpp	2010-04-09 17:44:00 UTC (rev 232)
@@ -260,6 +260,13 @@
 	return localtime_r_ce(timer, &tmbuf);
 }
 
+// KOTIK contribution
+struct tm *localtime(const time_t * timer)
+{
+	time_t_ce timer_ce = *timer;
+	return localtime_ce(&timer_ce);
+}
+
 // time_t represents seconds since midnight January 1, 1970 UTC 
 // (coordinated universal time) in 32-bits Win32 FILETIME structure is 64-bit,
 // which represents the number of 100-nanosecond (hns) intervals since 
@@ -268,17 +275,13 @@
 //
 time_t_ce mktime_ce(struct tm *tptr)
 {
-  SYSTEMTIME st;
-  TmToSystemTime(tptr, &st);
-  SetTz(&st);
+	SYSTEMTIME st;
+	TmToSystemTime(tptr, &st);
+	SetTz(&st);
+	
+	LONG day = 0, year = 0, seconds = 0;
+	LONG overflow, tm_year, yday, month;
 
-  DWORD day = 0;
-	DWORD year = 0;
-	DWORD seconds = 0;
-	DWORD overflow;
-	DWORD tm_year;
-	DWORD yday, month;
-
 	// see if seconds are < 0
 	while(tptr->tm_sec < 0)
 	{
@@ -434,7 +437,13 @@
 	return (time_t_ce) seconds;
 }
 
+// KOTIK contribution
+time_t mktime(struct tm *tptr)
+{
+	return mktime_ce(tptr);
+}
 
+
 // Get the current system time and convert to seconds since
 // 1/1/1970.  Store the seconds value in tloc if not a NULL pointer then
 // return the seconds value.

Modified: trunk/src/SlideBible/platform/wince/unistd.cpp
===================================================================
--- trunk/src/SlideBible/platform/wince/unistd.cpp	2010-04-09 17:38:27 UTC (rev 231)
+++ trunk/src/SlideBible/platform/wince/unistd.cpp	2010-04-09 17:44:00 UTC (rev 232)
@@ -59,13 +59,13 @@
 
   if (*result == INVALID_HANDLE_VALUE)
   {
-	  WCHAR buf[100];
-	  mbstowcs(buf,"file: ",6);
-	  mbstowcs(&buf[6],winPath,100);
-	  wcscpy(&buf[wcslen(buf)],L" error: ");
-	  DWORD errorNr=GetLastError();
-	  _itow(errorNr,&buf[wcslen(buf)],10);
-	  MessageBox(0,buf,L"Unable to open:",MB_OK|MB_ICONERROR);
+	  //WCHAR buf[100];
+	  //mbstowcs(buf,"file: ",6);
+	  //mbstowcs(&buf[6],winPath,100);
+	  //wcscpy(&buf[wcslen(buf)],L" error: ");
+	  //DWORD errorNr=GetLastError();
+	  //_itow(errorNr,&buf[wcslen(buf)],10);
+	  //MessageBox(0,buf,L"Unable to open:",MB_OK|MB_ICONERROR);
 	  delete result;
 	  result = (HANDLE *)-1;
   }

Modified: trunk/src/SlideBible/platform/xmlParser.cpp
===================================================================
--- trunk/src/SlideBible/platform/xmlParser.cpp	2010-04-09 17:38:27 UTC (rev 231)
+++ trunk/src/SlideBible/platform/xmlParser.cpp	2010-04-09 17:44:00 UTC (rev 232)
@@ -1,2887 +1,2935 @@
-/**
- ****************************************************************************
- * <P> XML.c - implementation file for basic XML parser written in ANSI C++
- * for portability. It works by using recursion and a node tree for breaking
- * down the elements of an XML document.  </P>
- *
- * @version     V2.41
- * @author      Frank Vanden Berghen
- *
- * NOTE:
- *
- *   If you add "#define STRICT_PARSING", on the first line of this file
- *   the parser will see the following XML-stream:
- *      <a><b>some text</b><b>other text    </a>
- *   as an error. Otherwise, this tring will be equivalent to:
- *      <a><b>some text</b><b>other text</b></a>
- *
- * NOTE:
- *
- *   If you add "#define APPROXIMATE_PARSING" on the first line of this file
- *   the parser will see the following XML-stream:
- *     <data name="n1">
- *     <data name="n2">
- *     <data name="n3" />
- *   as equivalent to the following XML-stream:
- *     <data name="n1" />
- *     <data name="n2" />
- *     <data name="n3" />
- *   This can be useful for badly-formed XML-streams but prevent the use
- *   of the following XML-stream (problem is: tags at contiguous levels
- *   have the same names):
- *     <data name="n1">
- *        <data name="n2">
- *            <data name="n3" />
- *        </data>
- *     </data>
- *
- * NOTE:
- *
- *   If you add "#define _XMLPARSER_NO_MESSAGEBOX_" on the first line of this file
- *   the "openFileHelper" function will always display error messages inside the
- *   console instead of inside a message-box-window. Message-box-windows are
- *   available on windows 9x/NT/2000/XP/Vista only.
- *
- * Copyright (c) 2002, Business-Insight
- * <a href="http://www.Business-Insight.com">Business-Insight</a>
- * All rights reserved.
- * See the file "AFPL-license.txt" about the licensing terms
- *
- ****************************************************************************
- */
-#ifndef _CRT_SECURE_NO_DEPRECATE
-#define _CRT_SECURE_NO_DEPRECATE
-#endif
-#include "xmlParser.h"
-#ifdef _XMLWINDOWS
-//#ifdef _DEBUG
-//#define _CRTDBG_MAP_ALLOC
-//#include <crtdbg.h>
-//#endif
-#define WIN32_LEAN_AND_MEAN
-#include <Windows.h> // to have IsTextUnicode, MultiByteToWideChar, WideCharToMultiByte to handle unicode files
-                     // to have "MessageBoxA" to display error messages for openFilHelper
-#endif
-
-#include <memory.h>
-#include <assert.h>
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-
-XMLCSTR XMLNode::getVersion() { return _CXML("v2.41"); }
-void freeXMLString(XMLSTR t){if(t)free(t);}
-
-static XMLNode::XMLCharEncoding characterEncoding=XMLNode::char_encoding_UTF8;
-static char guessWideCharChars=1, dropWhiteSpace=1, removeCommentsInMiddleOfText=1;
-
-inline int mmin( const int t1, const int t2 ) { return t1 < t2 ? t1 : t2; }
-
-// You can modify the initialization of the variable "XMLClearTags" below
-// to change the clearTags that are currently recognized by the library.
-// The number on the second columns is the length of the string inside the
-// first column. The "<!DOCTYPE" declaration must be the second in the list.
-// The "<!--" declaration must be the third in the list.
-typedef struct { XMLCSTR lpszOpen; int openTagLen; XMLCSTR lpszClose;} ALLXMLClearTag;
-static ALLXMLClearTag XMLClearTags[] =
-{
-    {    _CXML("<![CDATA["),9,  _CXML("]]>")      },
-    {    _CXML("<!DOCTYPE"),9,  _CXML(">")        },
-    {    _CXML("<!--")     ,4,  _CXML("-->")      },
-    {    _CXML("<PRE>")    ,5,  _CXML("</PRE>")   },
-//  {    _CXML("<Script>") ,8,  _CXML("</Script>")},
-    {    NULL              ,0,  NULL           }
-};
-
-// You can modify the initialization of the variable "XMLEntities" below
-// to change the character entities that are currently recognized by the library.
-// The number on the second columns is the length of the string inside the
-// first column. Additionally, the syntaxes "&#xA0;" and "&#160;" are recognized.
-typedef struct { XMLCSTR s; int l; XMLCHAR c;} XMLCharacterEntity;
-static XMLCharacterEntity XMLEntities[] =
-{
-    { _CXML("&amp;" ), 5, _CXML('&' )},
-    { _CXML("&lt;"  ), 4, _CXML('<' )},
-    { _CXML("&gt;"  ), 4, _CXML('>' )},
-    { _CXML("&quot;"), 6, _CXML('\"')},
-    { _CXML("&apos;"), 6, _CXML('\'')},
-    { NULL           , 0, '\0'    }
-};
-
-// When rendering the XMLNode to a string (using the "createXMLString" function),
-// you can ask for a beautiful formatting. This formatting is using the
-// following indentation character:
-#define INDENTCHAR _CXML('\t')
-
-// The following function parses the XML errors into a user friendly string.
-// You can edit this to change the output language of the library to something else.
-XMLCSTR XMLNode::getError(XMLError xerror)
-{
-    switch (xerror)
-    {
-    case eXMLErrorNone:                  return _CXML("No error");
-    case eXMLErrorMissingEndTag:         return _CXML("Warning: Unmatched end tag");
-    case eXMLErrorNoXMLTagFound:         return _CXML("Warning: No XML tag found");
-    case eXMLErrorEmpty:                 return _CXML("Error: No XML data");
-    case eXMLErrorMissingTagName:        return _CXML("Error: Missing start tag name");
-    case eXMLErrorMissingEndTagName:     return _CXML("Error: Missing end tag name");
-    case eXMLErrorUnmatchedEndTag:       return _CXML("Error: Unmatched end tag");
-    case eXMLErrorUnmatchedEndClearTag:  return _CXML("Error: Unmatched clear tag end");
-    case eXMLErrorUnexpectedToken:       return _CXML("Error: Unexpected token found");
-    case eXMLErrorNoElements:            return _CXML("Error: No elements found");
-    case eXMLErrorFileNotFound:          return _CXML("Error: File not found");
-    case eXMLErrorFirstTagNotFound:      return _CXML("Error: First Tag not found");
-    case eXMLErrorUnknownCharacterEntity:return _CXML("Error: Unknown character entity");
-    case eXMLErrorCharacterCodeAbove255: return _CXML("Error: Character code above 255 is forbidden in MultiByte char mode.");
-    case eXMLErrorCharConversionError:   return _CXML("Error: unable to convert between WideChar and MultiByte chars");
-    case eXMLErrorCannotOpenWriteFile:   return _CXML("Error: unable to open file for writing");
-    case eXMLErrorCannotWriteFile:       return _CXML("Error: cannot write into file");
-
-    case eXMLErrorBase64DataSizeIsNotMultipleOf4: return _CXML("Warning: Base64-string length is not a multiple of 4");
-    case eXMLErrorBase64DecodeTruncatedData:      return _CXML("Warning: Base64-string is truncated");
-    case eXMLErrorBase64DecodeIllegalCharacter:   return _CXML("Error: Base64-string contains an illegal character");
-    case eXMLErrorBase64DecodeBufferTooSmall:     return _CXML("Error: Base64 decode output buffer is too small");
-    };
-    return _CXML("Unknown");
-}
-
-/////////////////////////////////////////////////////////////////////////
-//      Here start the abstraction layer to be OS-independent          //
-/////////////////////////////////////////////////////////////////////////
-
-// Here is an abstraction layer to access some common string manipulation functions.
-// The abstraction layer is currently working for gcc, Microsoft Visual Studio 6.0,
-// Microsoft Visual Studio .NET, CC (sun compiler) and Borland C++.
-// If you plan to "port" the library to a new system/compiler, all you have to do is
-// to edit the following lines.
-#ifdef XML_NO_WIDE_CHAR
-char myIsTextWideChar(const void *b, int len) { return FALSE; }
-#else
-    #if defined (UNDER_CE) || !defined(_XMLWINDOWS)
-    char myIsTextWideChar(const void *b, int len) // inspired by the Wine API: RtlIsTextUnicode
-    {
-#ifdef sun
-        // for SPARC processors: wchar_t* buffers must always be alligned, otherwise it's a char* buffer.
-        if ((((unsigned long)b)%sizeof(wchar_t))!=0) return FALSE;
-#endif
-        const wchar_t *s=(const wchar_t*)b;
-
-        // buffer too small:
-        if (len<(int)sizeof(wchar_t)) return FALSE;
-
-        // odd length test
-        if (len&1) return FALSE;
-
-        /* only checks the first 256 characters */
-        len=mmin(256,len/sizeof(wchar_t));
-
-        // Check for the special byte order:
-        if (*((unsigned short*)s) == 0xFFFE) return TRUE;     // IS_TEXT_UNICODE_REVERSE_SIGNATURE;
-        if (*((unsigned short*)s) == 0xFEFF) return TRUE;      // IS_TEXT_UNICODE_SIGNATURE
-
-        // checks for ASCII characters in the UNICODE stream
-        int i,stats=0;
-        for (i=0; i<len; i++) if (s[i]<=(unsigned short)255) stats++;
-        if (stats>len/2) return TRUE;
-
-        // Check for UNICODE NULL chars
-        for (i=0; i<len; i++) if (!s[i]) return TRUE;
-
-        return FALSE;
-    }
-    #else
-    char myIsTextWideChar(const void *b,int l) { return (char)IsTextUnicode((CONST LPVOID)b,l,NULL); };
-    #endif
-#endif
-
-#ifdef _XMLWINDOWS
-// for Microsoft Visual Studio 6.0 and Microsoft Visual Studio .NET and Borland C++ Builder 6.0
-    #ifdef _XMLWIDECHAR
-        wchar_t *myMultiByteToWideChar(const char *s, XMLNode::XMLCharEncoding ce)
-        {
-            int i;
-            if (ce==XMLNode::char_encoding_UTF8) i=(int)MultiByteToWideChar(CP_UTF8,0             ,s,-1,NULL,0);
-            else                            i=(int)MultiByteToWideChar(CP_ACP ,MB_PRECOMPOSED,s,-1,NULL,0);
-            if (i<0) return NULL;
-            wchar_t *d=(wchar_t *)malloc((i+1)*sizeof(XMLCHAR));
-            if (ce==XMLNode::char_encoding_UTF8) i=(int)MultiByteToWideChar(CP_UTF8,0             ,s,-1,d,i);
-            else                            i=(int)MultiByteToWideChar(CP_ACP ,MB_PRECOMPOSED,s,-1,d,i);
-            d[i]=0;
-            return d;
-        }
-        static inline FILE *xfopen(XMLCSTR filename,XMLCSTR mode) { return _wfopen(filename,mode); }
-        static inline int xstrlen(XMLCSTR c)   { return (int)wcslen(c); }
-        static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return _wcsnicmp(c1,c2,l);}
-        static inline int xstrncmp(XMLCSTR c1, XMLCSTR c2, int l) { return wcsncmp(c1,c2,l);}
-        static inline int xstricmp(XMLCSTR c1, XMLCSTR c2) { return _wcsicmp(c1,c2); }
-        static inline XMLSTR xstrstr(XMLCSTR c1, XMLCSTR c2) { return (XMLSTR)wcsstr(c1,c2); }
-        static inline XMLSTR xstrcpy(XMLSTR c1, XMLCSTR c2) { return (XMLSTR)wcscpy(c1,c2); }
-    #else
-        char *myWideCharToMultiByte(const wchar_t *s)
-        {
-            UINT codePage=CP_ACP; if (characterEncoding==XMLNode::char_encoding_UTF8) codePage=CP_UTF8;
-            int i=(int)WideCharToMultiByte(codePage,  // code page
-                0,                       // performance and mapping flags
-                s,                       // wide-character string
-                -1,                       // number of chars in string
-                NULL,                       // buffer for new string
-                0,                       // size of buffer
-                NULL,                    // default for unmappable chars
-                NULL                     // set when default char used
-                );
-            if (i<0) return NULL;
-            char *d=(char*)malloc(i+1);
-            WideCharToMultiByte(codePage,  // code page
-                0,                       // performance and mapping flags
-                s,                       // wide-character string
-                -1,                       // number of chars in string
-                d,                       // buffer for new string
-                i,                       // size of buffer
-                NULL,                    // default for unmappable chars
-                NULL                     // set when default char used
-                );
-            d[i]=0;
-            return d;
-        }
-        static inline FILE *xfopen(XMLCSTR filename,XMLCSTR mode) { return fopen(filename,mode); }
-        static inline int xstrlen(XMLCSTR c)   { return (int)strlen(c); }
-        #ifdef __BORLANDC__
-            static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return strnicmp(c1,c2,l);}
-            static inline int xstricmp(XMLCSTR c1, XMLCSTR c2) { return stricmp(c1,c2); }
-        #else
-            static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return _strnicmp(c1,c2,l);}
-            static inline int xstricmp(XMLCSTR c1, XMLCSTR c2) { return _stricmp(c1,c2); }
-        #endif
-        static inline int xstrncmp(XMLCSTR c1, XMLCSTR c2, int l) { return strncmp(c1,c2,l);}
-        static inline XMLSTR xstrstr(XMLCSTR c1, XMLCSTR c2) { return (XMLSTR)strstr(c1,c2); }
-        static inline XMLSTR xstrcpy(XMLSTR c1, XMLCSTR c2) { return (XMLSTR)strcpy(c1,c2); }
-    #endif
-#else
-// for gcc and CC
-    #ifdef XML_NO_WIDE_CHAR
-        char *myWideCharToMultiByte(const wchar_t *s) { return NULL; }
-    #else
-        char *myWideCharToMultiByte(const wchar_t *s)
-        {
-            const wchar_t *ss=s;
-            int i=(int)wcsrtombs(NULL,&ss,0,NULL);
-            if (i<0) return NULL;
-            char *d=(char *)malloc(i+1);
-            wcsrtombs(d,&s,i,NULL);
-            d[i]=0;
-            return d;
-        }
-    #endif
-    #ifdef _XMLWIDECHAR
-        wchar_t *myMultiByteToWideChar(const char *s, XMLNode::XMLCharEncoding ce)
-        {
-            const char *ss=s;
-            int i=(int)mbsrtowcs(NULL,&ss,0,NULL);
-            if (i<0) return NULL;
-            wchar_t *d=(wchar_t *)malloc((i+1)*sizeof(wchar_t));
-            mbsrtowcs(d,&s,i,NULL);
-            d[i]=0;
-            return d;
-        }
-        int xstrlen(XMLCSTR c)   { return wcslen(c); }
-        #ifdef sun
-        // for CC
-           #include <widec.h>
-           static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return wsncasecmp(c1,c2,l);}
-           static inline int xstrncmp(XMLCSTR c1, XMLCSTR c2, int l) { return wsncmp(c1,c2,l);}
-           static inline int xstricmp(XMLCSTR c1, XMLCSTR c2) { return wscasecmp(c1,c2); }
-        #else
-        static inline int xstrncmp(XMLCSTR c1, XMLCSTR c2, int l) { return wcsncmp(c1,c2,l);}
-            #ifdef __linux__
-            // for gcc/linux
-            static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return wcsncasecmp(c1,c2,l);}
-            static inline int xstricmp(XMLCSTR c1, XMLCSTR c2) { return wcscasecmp(c1,c2); }
-            #else
-            #include <wctype.h>
-            // for gcc/non-linux (MacOS X 10.3, FreeBSD 6.0, NetBSD 3.0, OpenBSD 3.8, AIX 4.3.2, HP-UX 11, IRIX 6.5, OSF/1 5.1, Cygwin, mingw)
-            static inline int xstricmp(XMLCSTR c1, XMLCSTR c2)
-            {
-                wchar_t left,right;
-                do
-                {
-                    left=towlower(*c1++); right=towlower(*c2++);
-                } while (left&&(left==right));
-                return (int)left-(int)right;
-            }
-            static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l)
-            {
-                wchar_t left,right;
-                while(l--)
-                {
-                    left=towlower(*c1++); right=towlower(*c2++);
-                    if ((!left)||(left!=right)) return (int)left-(int)right;
-                }
-                return 0;
-            }
-            #endif
-        #endif
-        static inline XMLSTR xstrstr(XMLCSTR c1, XMLCSTR c2) { return (XMLSTR)wcsstr(c1,c2); }
-        static inline XMLSTR xstrcpy(XMLSTR c1, XMLCSTR c2) { return (XMLSTR)wcscpy(c1,c2); }
-        static inline FILE *xfopen(XMLCSTR filename,XMLCSTR mode)
-        {
-            char *filenameAscii=myWideCharToMultiByte(filename);
-            FILE *f;
-            if (mode[0]==_CXML('r')) f=fopen(filenameAscii,"rb");
-            else                     f=fopen(filenameAscii,"wb");
-            free(filenameAscii);
-            return f;
-        }
-    #else
-        static inline FILE *xfopen(XMLCSTR filename,XMLCSTR mode) { return fopen(filename,mode); }
-        static inline int xstrlen(XMLCSTR c)   { return strlen(c); }
-        static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return _strnicmp(c1,c2,l);}
-        static inline int xstrncmp(XMLCSTR c1, XMLCSTR c2, int l) { return strncmp(c1,c2,l);}
-        static inline int xstricmp(XMLCSTR c1, XMLCSTR c2) { return _stricmp(c1,c2); }
-        static inline XMLSTR xstrstr(XMLCSTR c1, XMLCSTR c2) { return (XMLSTR)strstr(c1,c2); }
-        static inline XMLSTR xstrcpy(XMLSTR c1, XMLCSTR c2) { return (XMLSTR)strcpy(c1,c2); }
-    #endif
-    //static inline int _strnicmp(const char *c1,const char *c2, int l) { return strncasecmp(c1,c2,l);}
-#endif
-
-
-///////////////////////////////////////////////////////////////////////////////
-//            the "xmltoc,xmltob,xmltoi,xmltol,xmltof,xmltoa" functions      //
-///////////////////////////////////////////////////////////////////////////////
-// These 6 functions are not used inside the XMLparser.
-// There are only here as "convenience" functions for the user.
-// If you don't need them, you can delete them without any trouble.
-#ifdef _XMLWIDECHAR
-    #ifdef _XMLWINDOWS
-    // for Microsoft Visual Studio 6.0 and Microsoft Visual Studio .NET and Borland C++ Builder 6.0
-        char    xmltob(XMLCSTR t,int     v){ if (t&&(*t)) return (char)_wtoi(t); return v; }
-        int     xmltoi(XMLCSTR t,int     v){ if (t&&(*t)) return _wtoi(t); return v; }
-        long    xmltol(XMLCSTR t,long    v){ if (t&&(*t)) return _wtol(t); return v; }
-        double  xmltof(XMLCSTR t,double  v){ if (t&&(*t)) wscanf(t, "%f", &v); /*v=_wtof(t);*/ return v; }
-    #else
-        #ifdef sun
-        // for CC
-           #include <widec.h>
-           char    xmltob(XMLCSTR t,int     v){ if (t) return (char)wstol(t,NULL,10); return v; }
-           int     xmltoi(XMLCSTR t,int     v){ if (t) return (int)wstol(t,NULL,10); return v; }
-           long    xmltol(XMLCSTR t,long    v){ if (t) return wstol(t,NULL,10); return v; }
-        #else
-        // for gcc
-           char    xmltob(XMLCSTR t,int     v){ if (t) return (char)wcstol(t,NULL,10); return v; }
-           int     xmltoi(XMLCSTR t,int     v){ if (t) return (int)wcstol(t,NULL,10); return v; }
-           long    xmltol(XMLCSTR t,long    v){ if (t) return wcstol(t,NULL,10); return v; }
-        #endif
-		double  xmltof(XMLCSTR t,double  v){ if (t&&(*t)) wscanf(t, "%f", &v); /*v=_wtof(t);*/ return v; }
-    #endif
-#else
-    char    xmltob(XMLCSTR t,char    v){ if (t&&(*t)) return (char)atoi(t); return v; }
-    int     xmltoi(XMLCSTR t,int     v){ if (t&&(*t)) return atoi(t); return v; }
-    long    xmltol(XMLCSTR t,long    v){ if (t&&(*t)) return atol(t); return v; }
-    double  xmltof(XMLCSTR t,double  v){ if (t&&(*t)) return atof(t); return v; }
-#endif
-XMLCSTR xmltoa(XMLCSTR t,      XMLCSTR v){ if (t)       return  t; return v; }
-XMLCHAR xmltoc(XMLCSTR t,const XMLCHAR v){ if (t&&(*t)) return *t; return v; }
-
-/////////////////////////////////////////////////////////////////////////
-//                    the "openFileHelper" function                    //
-/////////////////////////////////////////////////////////////////////////
-
-// Since each application has its own way to report and deal with errors, you should modify & rewrite
-// the following "openFileHelper" function to get an "error reporting mechanism" tailored to your needs.
-XMLNode XMLNode::openFileHelper(XMLCSTR filename, XMLCSTR tag)
-{
-    // guess the value of the global parameter "characterEncoding"
-    // (the guess is based on the first 200 bytes of the file).
-    FILE *f=xfopen(filename,_CXML("rb"));
-    if (f)
-    {
-        char bb[205];
-        int l=(int)fread(bb,1,200,f);
-        setGlobalOptions(guessCharEncoding(bb,l),guessWideCharChars,dropWhiteSpace,removeCommentsInMiddleOfText);
-        fclose(f);
-    }
-
-    // parse the file
-    XMLResults pResults;
-    XMLNode xnode=XMLNode::parseFile(filename,tag,&pResults);
-
-    // display error message (if any)
-    if (pResults.error != eXMLErrorNone)
-    {
-        // create message
-        char message[2000],*s1=(char*)"",*s3=(char*)""; XMLCSTR s2=_CXML("");
-        if (pResults.error==eXMLErrorFirstTagNotFound) { s1=(char*)"First Tag should be '"; s2=tag; s3=(char*)"'.\n"; }
-        sprintf(message,
-#ifdef _XMLWIDECHAR
-            "XML Parsing error inside file '%S'.\n%S\nAt line %i, column %i.\n%s%S%s"
-#else
-            "XML Parsing error inside file '%s'.\n%s\nAt line %i, column %i.\n%s%s%s"
-#endif
-            ,filename,XMLNode::getError(pResults.error),pResults.nLine,pResults.nColumn,s1,s2,s3);
-
-        // display message
-#if defined(_XMLWINDOWS) && !defined(UNDER_CE) && !defined(_XMLPARSER_NO_MESSAGEBOX_)
-        MessageBoxA(NULL,message,"XML Parsing error",MB_OK|MB_ICONERROR|MB_TOPMOST);
-#else
-        printf("%s",message);
-#endif
-        exit(255);
-    }
-    return xnode;
-}
-
-/////////////////////////////////////////////////////////////////////////
-//      Here start the core implementation of the XMLParser library    //
-/////////////////////////////////////////////////////////////////////////
-
-// You should normally not change anything below this point.
-
-#ifndef _XMLWIDECHAR
-// If "characterEncoding=ascii" then we assume that all characters have the same length of 1 byte.
-// If "characterEncoding=UTF8" then the characters have different lengths (from 1 byte to 4 bytes).
-// If "characterEncoding=ShiftJIS" then the characters have different lengths (from 1 byte to 2 bytes).
-// This table is used as lookup-table to know the length of a character (in byte) based on the
-// content of the first byte of the character.
-// (note: if you modify this, you must always have XML_utf8ByteTable[0]=0 ).
-static const char XML_utf8ByteTable[256] =
-{
-    //  0 1 2 3 4 5 6 7 8 9 a b c d e f
-    0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x00
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x10
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x20
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x30
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x40
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x50
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x60
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x70 End of ASCII range
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x80 0x80 to 0xc1 invalid
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x90
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xa0
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xb0
-    1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xc0 0xc2 to 0xdf 2 byte
-    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xd0
-    3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,// 0xe0 0xe0 to 0xef 3 byte
-    4,4,4,4,4,1,1,1,1,1,1,1,1,1,1,1 // 0xf0 0xf0 to 0xf4 4 byte, 0xf5 and higher invalid
-};
-static const char XML_legacyByteTable[256] =
-{
-    0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
-};
-static const char XML_sjisByteTable[256] =
-{
-    //  0 1 2 3 4 5 6 7 8 9 a b c d e f
-    0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x00
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x10
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x20
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x30
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x40
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x50
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x60
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x70
-    1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0x80 0x81 to 0x9F 2 bytes
-    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0x90
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xa0
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xb0
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xc0
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xd0
-    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xe0 0xe0 to 0xef 2 bytes
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 // 0xf0
-};
-static const char XML_gb2312ByteTable[256] =
-{
-//  0 1 2 3 4 5 6 7 8 9 a b c d e f
-    0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x00
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x10
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x20
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x30
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x40
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x50
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x60
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x70
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x80
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x90
-    1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xa0 0xa1 to 0xf7 2 bytes
-    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xb0
-    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xc0
-    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xd0
-    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xe0
-    2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1 // 0xf0
-};
-static const char XML_gbk_big5_ByteTable[256] =
-{
-    //  0 1 2 3 4 5 6 7 8 9 a b c d e f
-    0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x00
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x10
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x20
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x30
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x40
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x50
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x60
-    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x70
-    1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0x80 0x81 to 0xfe 2 bytes
-    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0x90
-    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xa0
-    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xb0
-    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xc0
-    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xd0
-    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xe0
-    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1 // 0xf0
-};
-static const char *XML_ByteTable=(const char *)XML_utf8ByteTable; // the default is "characterEncoding=XMLNode::encoding_UTF8"
-#endif
-
-
-XMLNode XMLNode::emptyXMLNode;
-XMLClear XMLNode::emptyXMLClear={ NULL, NULL, NULL};
-XMLAttribute XMLNode::emptyXMLAttribute={ NULL, NULL};
-
-// Enumeration used to decipher what type a token is
-typedef enum XMLTokenTypeTag
-{
-    eTokenText = 0,
-    eTokenQuotedText,
-    eTokenTagStart,         /* "<"            */
-    eTokenTagEnd,           /* "</"           */
-    eTokenCloseTag,         /* ">"            */
-    eTokenEquals,           /* "="            */
-    eTokenDeclaration,      /* "<?"           */
-    eTokenShortHandClose,   /* "/>"           */
-    eTokenClear,
-    eTokenError
-} XMLTokenType;
-
-// Main structure used for parsing XML
-typedef struct XML
-{
-    XMLCSTR                lpXML;
-    XMLCSTR                lpszText;
-    int                    nIndex,nIndexMissigEndTag;
-    enum XMLError          error;
-    XMLCSTR                lpEndTag;
-    int                    cbEndTag;
-    XMLCSTR                lpNewElement;
-    int                    cbNewElement;
-    int                    nFirst;
-} XML;
-
-typedef struct
-{
-    ALLXMLClearTag *pClr;
-    XMLCSTR     pStr;
-} NextToken;
-
-// Enumeration used when parsing attributes
-typedef enum Attrib
-{
-    eAttribName = 0,
-    eAttribEquals,
-    eAttribValue
-} Attrib;
-
-// Enumeration used when parsing elements to dictate whether we are currently
-// inside a tag
-typedef enum Status
-{
-    eInsideTag = 0,
-    eOutsideTag
-} Status;
-
-XMLError XMLNode::writeToFile(XMLCSTR filename, const char *encoding, char nFormat) const
-{
-    if (!d) return eXMLErrorNone;
-    FILE *f=xfopen(filename,_CXML("wb"));
-    if (!f) return eXMLErrorCannotOpenWriteFile;
-#ifdef _XMLWIDECHAR
-    unsigned char h[2]={ 0xFF, 0xFE };
-    if (!fwrite(h,2,1,f)) return eXMLErrorCannotWriteFile;
-    if ((!isDeclaration())&&((d->lpszName)||(!getChildNode().isDeclaration())))
-    {
-        if (!fwrite(L"<?xml version=\"1.0\" encoding=\"utf-16\"?>\n",sizeof(wchar_t)*40,1,f))
-            return eXMLErrorCannotWriteFile;
-    }
-#else
-    if ((!isDeclaration())&&((d->lpszName)||(!getChildNode().isDeclaration())))
-    {
-        if (characterEncoding==char_encoding_UTF8)
-        {
-            // header so that windows recognize the file as UTF-8:
-            unsigned char h[3]={0xEF,0xBB,0xBF}; if (!fwrite(h,3,1,f)) return eXMLErrorCannotWriteFile;
-            encoding="utf-8";
-        } else if (characterEncoding==char_encoding_ShiftJIS) encoding="SHIFT-JIS";
-
-        if (!encoding) encoding="ISO-8859-1";
-        if (fprintf(f,"<?xml version=\"1.0\" encoding=\"%s\"?>\n",encoding)<0) return eXMLErrorCannotWriteFile;
-    } else
-    {
-        if (characterEncoding==char_encoding_UTF8)
-        {
-            unsigned char h[3]={0xEF,0xBB,0xBF}; if (!fwrite(h,3,1,f)) return eXMLErrorCannotWriteFile;
-        }
-    }
-#endif
-    int i;
-    XMLSTR t=createXMLString(nFormat,&i);
-    if (!fwrite(t,sizeof(XMLCHAR)*i,1,f)) return eXMLErrorCannotWriteFile;
-    if (fclose(f)!=0) return eXMLErrorCannotWriteFile;
-    free(t);
-    return eXMLErrorNone;
-}
-
-// Duplicate a given string.
-XMLSTR stringDup(XMLCSTR lpszData, int cbData)
-{
-    if (lpszData==NULL) return NULL;
-
-    XMLSTR lpszNew;
-    if (cbData==-1) cbData=(int)xstrlen(lpszData);
-    lpszNew = (XMLSTR)malloc((cbData+1) * sizeof(XMLCHAR));
-    if (lpszNew)
-    {
-        memcpy(lpszNew, lpszData, (cbData) * sizeof(XMLCHAR));
-        lpszNew[cbData] = (XMLCHAR)NULL;
-    }
-    return lpszNew;
-}
-
-XMLSTR ToXMLStringTool::toXMLUnSafe(XMLSTR dest,XMLCSTR source)
-{
-    XMLSTR dd=dest;
-    XMLCHAR ch;
-    XMLCharacterEntity *entity;
-    while ((ch=*source))
-    {
-        entity=XMLEntities;
-        do
-        {
-            if (ch==entity->c) {xstrcpy(dest,entity->s); dest+=entity->l; source++; goto out_of_loop1; }
-            entity++;
-        } while(entity->s);
-#ifdef _XMLWIDECHAR
-        *(dest++)=*(source++);
-#else
-        switch(XML_ByteTable[(unsigned char)ch])
-        {
-        case 4: *(dest++)=*(source++);
-        case 3: *(dest++)=*(source++);
-        case 2: *(dest++)=*(source++);
-        case 1: *(dest++)=*(source++);
-        }
-#endif
-out_of_loop1:
-        ;
-    }
-    *dest=0;
-    return dd;
-}
-
-// private (used while rendering):
-int ToXMLStringTool::lengthXMLString(XMLCSTR source)
-{
-    int r=0;
-    XMLCharacterEntity *entity;
-    XMLCHAR ch;
-    while ((ch=*source))
-    {
-        entity=XMLEntities;
-        do
-        {
-            if (ch==entity->c) { r+=entity->l; source++; goto out_of_loop1; }
-            entity++;
-        } while(entity->s);
-#ifdef _XMLWIDECHAR
-        r++; source++;
-#else
-        ch=XML_ByteTable[(unsigned char)ch]; r+=ch; source+=ch;
-#endif
-out_of_loop1:
-        ;
-    }
-    return r;
-}
-
-ToXMLStringTool::~ToXMLStringTool(){ freeBuffer(); }
-void ToXMLStringTool::freeBuffer(){ if (buf) free(buf); buf=NULL; buflen=0; }
-XMLSTR ToXMLStringTool::toXML(XMLCSTR source)
-{
-    if (!source) return _CXML("");
-    int l=lengthXMLString(source)+1;
-    if (l>buflen) { buflen=l; buf=(XMLSTR)realloc(buf,l*sizeof(XMLCHAR)); }
-    return toXMLUnSafe(buf,source);
-}
-
-// private:
-XMLSTR fromXMLString(XMLCSTR s, int lo, XML *pXML)
-{
-    // This function is the opposite of the function "toXMLString". It decodes the escape
-    // sequences &amp;, &quot;, &apos;, &lt;, &gt; and replace them by the characters
-    // &,",',<,>. This function is used internally by the XML Parser. All the calls to
-    // the XML library will always gives you back "decoded" strings.
-    //
-    // in: string (s) and length (lo) of string
-    // out:  new allocated string converted from xml
-    if (!s) return NULL;
-
-    int ll=0,j;
-    XMLSTR d;
-    XMLCSTR ss=s;
-    XMLCharacterEntity *entity;
-    while ((lo>0)&&(*s))
-    {
-        if (*s==_CXML('&'))
-        {
-            if ((lo>2)&&(s[1]==_CXML('#')))
-            {
-                s+=2; lo-=2;
-                if ((*s==_CXML('X'))||(*s==_CXML('x'))) { s++; lo--; }
-                while ((*s)&&(*s!=_CXML(';'))&&((lo--)>0)) s++;
-                if (*s!=_CXML(';'))
-                {
-                    pXML->error=eXMLErrorUnknownCharacterEntity;
-                    return NULL;
-                }
-                s++; lo--;
-            } else
-            {
-                entity=XMLEntities;
-                do
-                {
-                    if ((lo>=entity->l)&&(xstrnicmp(s,entity->s,entity->l)==0)) { s+=entity->l; lo-=entity->l; break; }
-                    entity++;
-                } while(entity->s);
-                if (!entity->s)
-                {
-                    pXML->error=eXMLErrorUnknownCharacterEntity;
-                    return NULL;
-                }
-            }
-        } else
-        {
-#ifdef _XMLWIDECHAR
-            s++; lo--;
-#else
-            j=XML_ByteTable[(unsigned char)*s]; s+=j; lo-=j; ll+=j-1;
-#endif
-        }
-        ll++;
-    }
-
-    d=(XMLSTR)malloc((ll+1)*sizeof(XMLCHAR));
-    s=d;
-    while (ll-->0)
-    {
-        if (*ss==_CXML('&'))
-        {
-            if (ss[1]==_CXML('#'))
-            {
-                ss+=2; j=0;
-                if ((*ss==_CXML('X'))||(*ss==_CXML('x')))
-                {
-                    ss++;
-                    while (*ss!=_CXML(';'))
-                    {
-                        if ((*ss>=_CXML('0'))&&(*ss<=_CXML('9'))) j=(j<<4)+*ss-_CXML('0');
-                        else if ((*ss>=_CXML('A'))&&(*ss<=_CXML('F'))) j=(j<<4)+*ss-_CXML('A')+10;
-                        else if ((*ss>=_CXML('a'))&&(*ss<=_CXML('f'))) j=(j<<4)+*ss-_CXML('a')+10;
-                        else { free((void*)s); pXML->error=eXMLErrorUnknownCharacterEntity;return NULL;}
-                        ss++;
-                    }
-                } else
-                {
-                    while (*ss!=_CXML(';'))
-                    {
-                        if ((*ss>=_CXML('0'))&&(*ss<=_CXML('9'))) j=(j*10)+*ss-_CXML('0');
-                        else { free((void*)s); pXML->error=eXMLErrorUnknownCharacterEntity;return NULL;}
-                        ss++;
-                    }
-                }
-#ifndef _XMLWIDECHAR
-                if (j>255) { free((void*)s); pXML->error=eXMLErrorCharacterCodeAbove255;return NULL;}
-#endif
-                (*d++)=(XMLCHAR)j; ss++;
-            } else
-            {
-                entity=XMLEntities;
-                do
-                {
-                    if (xstrnicmp(ss,entity->s,entity->l)==0) { *(d++)=entity->c; ss+=entity->l; break; }
-                    entity++;
-                } while(entity->s);
-            }
-        } else
-        {
-#ifdef _XMLWIDECHAR
-            *(d++)=*(ss++);
-#else
-            switch(XML_ByteTable[(unsigned char)*ss])
-            {
-            case 4: *(d++)=*(ss++); ll--;
-            case 3: *(d++)=*(ss++); ll--;
-            case 2: *(d++)=*(ss++); ll--;
-            case 1: *(d++)=*(ss++);
-            }
-#endif
-        }
-    }
-    *d=0;
-    return (XMLSTR)s;
-}
-
-#define XML_isSPACECHAR(ch) ((ch==_CXML('\n'))||(ch==_CXML(' '))||(ch== _CXML('\t'))||(ch==_CXML('\r')))
-
-// private:
-char myTagCompare(XMLCSTR cclose, XMLCSTR copen)
-// !!!! WARNING strange convention&:
-// return 0 if equals
-// return 1 if different
-{
-    if (!cclose) return 1;
-    int l=(int)xstrlen(cclose);
-    if (xstrnicmp(cclose, copen, l)!=0) return 1;
-    const XMLCHAR c=copen[l];
-    if (XML_isSPACECHAR(c)||
-        (c==_CXML('/' ))||
-        (c==_CXML('<' ))||
-        (c==_CXML('>' ))||
-        (c==_CXML('=' ))) return 0;
-    return 1;
-}
-
-// Obtain the next character from the string.
-static inline XMLCHAR getNextChar(XML *pXML)
-{
-    XMLCHAR ch = pXML->lpXML[pXML->nIndex];
-#ifdef _XMLWIDECHAR
-    if (ch!=0) pXML->nIndex++;
-#else
-    pXML->nIndex+=XML_ByteTable[(unsigned char)ch];
-#endif
-    return ch;
-}
-
-// Find the next token in a string.
-// pcbToken contains the number of characters that have been read.
-static NextToken GetNextToken(XML *pXML, int *pcbToken, enum XMLTokenTypeTag *pType)
-{
-    NextToken        result;
-    XMLCHAR            ch;
-    XMLCHAR            chTemp;
-    int              indexStart,nFoundMatch,nIsText=FALSE;
-    result.pClr=NULL; // prevent warning
-
-    // Find next non-white space character
-    do { indexStart=pXML->nIndex; ch=getNextChar(pXML); } while XML_isSPACECHAR(ch);
-
-    if (ch)
-    {
-        // Cache the current string pointer
-        result.pStr = &pXML->lpXML[indexStart];
-
-        // First check whether the token is in the clear tag list (meaning it
-        // does not need formatting).
-        ALLXMLClearTag *ctag=XMLClearTags;
-        do
-        {
-            if (xstrncmp(ctag->lpszOpen, result.pStr, ctag->openTagLen)==0)
-            {
-                result.pClr=ctag;
-                pXML->nIndex+=ctag->openTagLen-1;
-                *pType=eTokenClear;
-                return result;
-            }
-            ctag++;
-        } while(ctag->lpszOpen);
-
-        // If we didn't find a clear tag then check for standard tokens
-        switch(ch)
-        {
-        // Check for quotes
-        case _CXML('\''):
-        case _CXML('\"'):
-            // Type of token
-            *pType = eTokenQuotedText;
-            chTemp = ch;
-
-            // Set the size
-            nFoundMatch = FALSE;
-
-            // Search through the string to find a matching quote
-            while((ch = getNextChar(pXML)))
-            {
-                if (ch==chTemp) { nFoundMatch = TRUE; break; }
-                if (ch==_CXML('<')) break;
-            }
-
-            // If we failed to find a matching quote
-            if (nFoundMatch == FALSE)
-            {
-                pXML->nIndex=indexStart+1;
-                nIsText=TRUE;
-                break;
-            }
-
-//  4.02.2002
-//            if (FindNonWhiteSpace(pXML)) pXML->nIndex--;
-
-            break;
-
-        // Equals (used with attribute values)
-        case _CXML('='):
-            *pType = eTokenEquals;
-            break;
-
-        // Close tag
-        case _CXML('>'):
-            *pType = eTokenCloseTag;
-            break;
-
-        // Check for tag start and tag end
-        case _CXML('<'):
-
-            // Peek at the next character to see if we have an end tag '</',
-            // or an xml declaration '<?'
-            chTemp = pXML->lpXML[pXML->nIndex];
-
-            // If we have a tag end...
-            if (chTemp == _CXML('/'))
-            {
-                // Set the type and ensure we point at the next character
-                getNextChar(pXML);
-                *pType = eTokenTagEnd;
-            }
-
-            // If we have an XML declaration tag
-            else if (chTemp == _CXML('?'))
-            {
-
-                // Set the type and ensure we point at the next character
-                getNextChar(pXML);
-                *pType = eTokenDeclaration;
-            }
-
-            // Otherwise we must have a start tag
-            else
-            {
-                *pType = eTokenTagStart;
-            }
-            break;
-
-        // Check to see if we have a short hand type end tag ('/>').
-        case _CXML('/'):
-
-            // Peek at the next character to see if we have a short end tag '/>'
-            chTemp = pXML->lpXML[pXML->nIndex];
-
-            // If we have a short hand end tag...
-            if (chTemp == _CXML('>'))
-            {
-                // Set the type and ensure we point at the next character
-                getNextChar(pXML);
-                *pType = eTokenShortHandClose;
-                break;
-            }
-
-            // If we haven't found a short hand closing tag then drop into the
-            // text process
-
-        // Other characters
-        default:
-            nIsText = TRUE;
-        }
-
-        // If this is a TEXT node
-        if (nIsText)
-        {
-            // Indicate we are dealing with text
-            *pType = eTokenText;
-            while((ch = getNextChar(pXML)))
-            {
-                if XML_isSPACECHAR(ch)
-                {
-                    indexStart++; break;
-
-                } else if (ch==_CXML('/'))
-                {
-                    // If we find a slash then this maybe text or a short hand end tag
-                    // Peek at the next character to see it we have short hand end tag
-                    ch=pXML->lpXML[pXML->nIndex];
-                    // If we found a short hand end tag then we need to exit the loop
-                    if (ch==_CXML('>')) { pXML->nIndex--; break; }
-
-                } else if ((ch==_CXML('<'))||(ch==_CXML('>'))||(ch==_CXML('=')))
-                {
-                    pXML->nIndex--; break;
-                }
-            }
-        }
-        *pcbToken = pXML->nIndex-indexStart;
-    } else
-    {
-        // If we failed to obtain a valid character
-        *pcbToken = 0;
-        *pType = eTokenError;
-        result.pStr=NULL;
-    }
-
-    return result;
-}
-
-XMLCSTR XMLNode::updateName_WOSD(XMLSTR lpszName)
-{
-    if (!d) { free(lpszName); return NULL; }
-    if (d->lpszName&&(lpszName!=d->lpszName)) free((void*)d->lpszName);
-    d->lpszName=lpszName;
-    return lpszName;
-}
-
-// private:
-XMLNode::XMLNode(struct XMLNodeDataTag *p){ d=p; (p->ref_count)++; }
-XMLNode::XMLNode(XMLNodeData *pParent, XMLSTR lpszName, char isDeclaration)
-{
-    d=(XMLNodeData*)malloc(sizeof(XMLNodeData));
-    d->ref_count=1;
-
-    d->lpszName=NULL;
-    d->nChild= 0;
-    d->nText = 0;
-    d->nClear = 0;
-    d->nAttribute = 0;
-
-    d->isDeclaration = isDeclaration;
-
-    d->pParent = pParent;
-    d->pChild= NULL;
-    d->pText= NULL;
-    d->pClear= NULL;
-    d->pAttribute= NULL;
-    d->pOrder= NULL;
-
-    updateName_WOSD(lpszName);
-}
-
-XMLNode XMLNode::createXMLTopNode_WOSD(XMLSTR lpszName, char isDeclaration) { return XMLNode(NULL,lpszName,isDeclaration); }
-XMLNode XMLNode::createXMLTopNode(XMLCSTR lpszName, char isDeclaration) { return XMLNode(NULL,stringDup(lpszName),isDeclaration); }
-
-#define MEMORYINCREASE 50
-
-static inline void myFree(void *p) { if (p) free(p); }
-static inline void *myRealloc(void *p, int newsize, int memInc, int sizeofElem)
-{
-    if (p==NULL) { if (memInc) return malloc(memInc*sizeofElem); return malloc(sizeofElem); }
-    if ((memInc==0)||((newsize%memInc)==0)) p=realloc(p,(newsize+memInc)*sizeofElem);
-//    if (!p)
-//    {
-//        printf("XMLParser Error: Not enough memory! Aborting...\n"); exit(220);
-//    }
-    return p;
-}
-
-// private:
-XMLElementPosition XMLNode::findPosition(XMLNodeData *d, int index, XMLElementType xxtype)
-{
-    if (index<0) return -1;
-    int i=0,j=(int)((index<<2)+xxtype),*o=d->pOrder; while (o[i]!=j) i++; return i;
-}
-
-// private:
-// update "order" information when deleting a content of a XMLNode
-int XMLNode::removeOrderElement(XMLNodeData *d, XMLElementType t, int index)
-{
-    int n=d->nChild+d->nText+d->nClear, *o=d->pOrder,i=findPosition(d,index,t);
-    memmove(o+i, o+i+1, (n-i)*sizeof(int));
-    for (;i<n;i++)
-        if ((o[i]&3)==(int)t) o[i]-=4;
-    // We should normally do:
-    // d->pOrder=(int)realloc(d->pOrder,n*sizeof(int));
-    // but we skip reallocation because it's too time consuming.
-    // Anyway, at the end, it will be free'd completely at once.
-    return i;
-}
-
-void *XMLNode::addToOrder(int memoryIncrease,int *_pos, int nc, void *p, int size, XMLElementType xtype)
-{
-    //  in: *_pos is the position inside d->pOrder ("-1" means "EndOf")
-    // out: *_pos is the index inside p
-    p=myRealloc(p,(nc+1),memoryIncrease,size);
-    int n=d->nChild+d->nText+d->nClear;
-    d->pOrder=(int*)myRealloc(d->pOrder,n+1,memoryIncrease*3,sizeof(int));
-    int pos=*_pos,*o=d->pOrder;
-
-    if ((pos<0)||(pos>=n)) { *_pos=nc; o[n]=(int)((nc<<2)+xtype); return p; }
-
-    int i=pos;
-    memmove(o+i+1, o+i, (n-i)*sizeof(int));
-
-    while ((pos<n)&&((o[pos]&3)!=(int)xtype)) pos++;
-    if (pos==n) { *_pos=nc; o[n]=(int)((nc<<2)+xtype); return p; }
-
-    o[i]=o[pos];
-    for (i=pos+1;i<=n;i++) if ((o[i]&3)==(int)xtype) o[i]+=4;
-
-    *_pos=pos=o[pos]>>2;
-    memmove(((char*)p)+(pos+1)*size,((char*)p)+pos*size,(nc-pos)*size);
-
-    return p;
-}
-
-// Add a child node to the given element.
-XMLNode XMLNode::addChild_priv(int memoryIncrease, XMLSTR lpszName, char isDeclaration, int pos)
-{
-    if (!lpszName) return emptyXMLNode;
-    d->pChild=(XMLNode*)addToOrder(memoryIncrease,&pos,d->nChild,d->pChild,sizeof(XMLNode),eNodeChild);
-    d->pChild[pos].d=NULL;
-    d->pChild[pos]=XMLNode(d,lpszName,isDeclaration);
-    d->nChild++;
-    return d->pChild[pos];
-}
-
-// Add an attribute to an element.
-XMLAttribute *XMLNode::addAttribute_priv(int memoryIncrease,XMLSTR lpszName, XMLSTR lpszValuev)
-{
-    if (!lpszName) return &emptyXMLAttribute;
-    if (!d) { myFree(lpszName); myFree(lpszValuev); return &emptyXMLAttribute; }
-    int nc=d->nAttribute;
-    d->pAttribute=(XMLAttribute*)myRealloc(d->pAttribute,(nc+1),memoryIncrease,sizeof(XMLAttribute));
-    XMLAttribute *pAttr=d->pAttribute+nc;
-    pAttr->lpszName = lpszName;
-    pAttr->lpszValue = lpszValuev;
-    d->nAttribute++;
-    return pAttr;
-}
-
-// Add text to the element.
-XMLCSTR XMLNode::addText_priv(int memoryIncrease, XMLSTR lpszValue, int pos)
-{
-    if (!lpszValue) return NULL;
-    if (!d) { myFree(lpszValue); return NULL; }
-    d->pText=(XMLCSTR*)addToOrder(memoryIncrease,&pos,d->nText,d->pText,sizeof(XMLSTR),eNodeText);
-    d->pText[pos]=lpszValue;
-    d->nText++;
-    return lpszValue;
-}
-
-// Add clear (unformatted) text to the element.
-XMLClear *XMLNode::addClear_priv(int memoryIncrease, XMLSTR lpszValue, XMLCSTR lpszOpen, XMLCSTR lpszClose, int pos)
-{
-    if (!lpszValue) return &emptyXMLClear;
-    if (!d) { myFree(lpszValue); return &emptyXMLClear; }
-    d->pClear=(XMLClear *)addToOrder(memoryIncrease,&pos,d->nClear,d->pClear,sizeof(XMLClear),eNodeClear);
-    XMLClear *pNewClear=d->pClear+pos;
-    pNewClear->lpszValue = lpszValue;
-    if (!lpszOpen) lpszOpen=XMLClearTags->lpszOpen;
-    if (!lpszClose) lpszClose=XMLClearTags->lpszClose;
-    pNewClear->lpszOpenTag = lpszOpen;
-    pNewClear->lpszCloseTag = lpszClose;
-    d->nClear++;
-    return pNewClear;
-}
-
-// private:
-// Parse a clear (unformatted) type node.
-char XMLNode::parseClearTag(void *px, void *_pClear)
-{
-    XML *pXML=(XML *)px;
-    ALLXMLClearTag pClear=*((ALLXMLClearTag*)_pClear);
-    int cbTemp=0;
-    XMLCSTR lpszTemp=NULL;
-    XMLCSTR lpXML=&pXML->lpXML[pXML->nIndex];
-    static XMLCSTR docTypeEnd=_CXML("]>");
-
-    // Find the closing tag
-    // Seems the <!DOCTYPE need a better treatment so lets handle it
-    if (pClear.lpszOpen==XMLClearTags[1].lpszOpen)
-    {
-        XMLCSTR pCh=lpXML;
-        while (*pCh)
-        {
-            if (*pCh==_CXML('<')) { pClear.lpszClose=docTypeEnd; lpszTemp=xstrstr(lpXML,docTypeEnd); break; }
-            else if (*pCh==_CXML('>')) { lpszTemp=pCh; break; }
-#ifdef _XMLWIDECHAR
-            pCh++;
-#else
-            pCh+=XML_ByteTable[(unsigned char)(*pCh)];
-#endif
-        }
-    } else lpszTemp=xstrstr(lpXML, pClear.lpszClose);
-
-    if (lpszTemp)
-    {
-        // Cache the size and increment the index
-        cbTemp = (int)(lpszTemp - lpXML);
-
-        pXML->nIndex += cbTemp+(int)xstrlen(pClear.lpszClose);
-
-        // Add the clear node to the current element
-        addClear_priv(MEMORYINCREASE,stringDup(lpXML,cbTemp), pClear.lpszOpen, pClear.lpszClose,-1);
-        return 0;
-    }
-
-    // If we failed to find the end tag
-    pXML->error = eXMLErrorUnmatchedEndClearTag;
-    return 1;
-}
-
-void XMLNode::exactMemory(XMLNodeData *d)
-{
-    if (d->pOrder)     d->pOrder=(int*)realloc(d->pOrder,(d->nChild+d->nText+d->nClear)*sizeof(int));
-    if (d->pChild)     d->pChild=(XMLNode*)realloc(d->pChild,d->nChild*sizeof(XMLNode));
-    if (d->pAttribute) d->pAttribute=(XMLAttribute*)realloc(d->pAttribute,d->nAttribute*sizeof(XMLAttribute));
-    if (d->pText)      d->pText=(XMLCSTR*)realloc(d->pText,d->nText*sizeof(XMLSTR));
-    if (d->pClear)     d->pClear=(XMLClear *)realloc(d->pClear,d->nClear*sizeof(XMLClear));
-}
-
-char XMLNode::maybeAddTxT(void *pa, XMLCSTR tokenPStr)
-{
-    XML *pXML=(XML *)pa;
-    XMLCSTR lpszText=pXML->lpszText;
-    if (!lpszText) return 0;
-    if (dropWhiteSpace) while (XML_isSPACECHAR(*lpszText)&&(lpszText!=tokenPStr)) lpszText++;
-    int cbText = (int)(tokenPStr - lpszText);
-    if (!cbText) { pXML->lpszText=NULL; return 0; }
-    if (dropWhiteSpace) { cbText--; while ((cbText)&&XML_isSPACECHAR(lpszText[cbText])) cbText--; cbText++; }
-    if (!cbText) { pXML->lpszText=NULL; return 0; }
-    XMLSTR lpt=fromXMLString(lpszText,cbText,pXML);
-    if (!lpt) return 1;
-    pXML->lpszText=NULL;
-    if (removeCommentsInMiddleOfText && d->nText && d->nClear)
-    {
-        // if the previous insertion was a comment (<!-- -->) AND
-        // if the previous previous insertion was a text then, delete the comment and append the text
-        int n=d->nChild+d->nText+d->nClear-1,*o=d->pOrder;
-        if (((o[n]&3)==eNodeClear)&&((o[n-1]&3)==eNodeText))
-        {
-            int i=o[n]>>2;
-            if (d->pClear[i].lpszOpenTag==XMLClearTags[2].lpszOpen)
-            {
-                deleteClear(i);
-                i=o[n-1]>>2;
-                n=xstrlen(d->pText[i]);
-                int n2=xstrlen(lpt)+1;
-                d->pText[i]=(XMLSTR)realloc((void*)d->pText[i],(n+n2)*sizeof(XMLCHAR));
-                if (!d->pText[i]) return 1;
-                memcpy((void*)(d->pText[i]+n),lpt,n2*sizeof(XMLCHAR));
-                free(lpt);
-                return 0;
-            }
-        }
-    }
-    addText_priv(MEMORYINCREASE,lpt,-1);
-    return 0;
-}
-// private:
-// Recursively parse an XML element.
-int XMLNode::ParseXMLElement(void *pa)
-{
-    XML *pXML=(XML *)pa;
-    int cbToken;
-    enum XMLTokenTypeTag xtype;
-    NextToken token;
-    XMLCSTR lpszTemp=NULL;
-    int cbTemp=0;
-    char nDeclaration;
-    XMLNode pNew;
-    enum Status status; // inside or outside a tag
-    enum Attrib attrib = eAttribName;
-
-    assert(pXML);
-
-    // If this is the first call to the function
-    if (pXML->nFirst)
-    {
-        // Assume we are outside of a tag definition
-        pXML->nFirst = FALSE;
-        status = eOutsideTag;
-    } else
-    {
-        // If this is not the first call then we should only be called when inside a tag.
-        status = eInsideTag;
-    }
-
-    // Iterate through the tokens in the document
-    for(;;)
-    {
-        // Obtain the next token
-        token = GetNextToken(pXML, &cbToken, &xtype);
-
-        if (xtype != eTokenError)
-        {
-            // Check the current status
-            switch(status)
-            {
-
-            // If we are outside of a tag definition
-            case eOutsideTag:
-
-                // Check what type of token we obtained
-                switch(xtype)
-                {
-                // If we have found text or quoted text
-                case eTokenText:
-                case eTokenCloseTag:          /* '>'         */
-                case eTokenShortHandClose:    /* '/>'        */
-                case eTokenQuotedText:
-                case eTokenEquals:
-                    break;
-
-                // If we found a start tag '<' and declarations '<?'
-                case eTokenTagStart:
-                case eTokenDeclaration:
-
-                    // Cache whether this new element is a declaration or not
-                    nDeclaration = (xtype == eTokenDeclaration);
-
-                    // If we have node text then add this to the element
-                    if (maybeAddTxT(pXML,token.pStr)) return FALSE;
-
-                    // Find the name of the tag
-                    token = GetNextToken(pXML, &cbToken, &xtype);
-
-                    // Return an error if we couldn't obtain the next token or
-                    // it wasnt text
-                    if (xtype != eTokenText)
-                    {
-                        pXML->error = eXMLErrorMissingTagName;
-                        return FALSE;
-                    }
-
-                    // If we found a new element which is the same as this
-                    // element then we need to pass this back to the caller..
-
-#ifdef APPROXIMATE_PARSING
-                    if (d->lpszName &&
-                        myTagCompare(d->lpszName, token.pStr) == 0)
-                    {
-                        // Indicate to the caller that it needs to create a
-                        // new element.
-                        pXML->lpNewElement = token.pStr;
-                        pXML->cbNewElement = cbToken;
-                        return TRUE;
-                    } else
-#endif
-                    {
-                        // If the name of the new element differs from the name of
-                        // the current element we need to add the new element to
-                        // the current one and recurse
-                        pNew = addChild_priv(MEMORYINCREASE,stringDup(token.pStr,cbToken), nDeclaration,-1);
-
-                        while (!pNew.isEmpty())
-                        {
-                            // Callself to process the new node.  If we return
-                            // FALSE this means we dont have any more
-                            // processing to do...
-
-                            if (!pNew.ParseXMLElement(pXML)) return FALSE;
-                            else
-                            {
-                                // If the call to recurse this function
-                                // evented in a end tag specified in XML then
-                                // we need to unwind the calls to this
-                                // function until we find the appropriate node
-                                // (the element name and end tag name must
-                                // match)
-                                if (pXML->cbEndTag)
-                                {
-                                    // If we are back at the root node then we
-                                    // have an unmatched end tag
-                                    if (!d->lpszName)
-                                    {
-                                        pXML->error=eXMLErrorUnmatchedEndTag;
-                                        return FALSE;
-                                    }
-
-                                    // If the end tag matches the name of this
-                                    // element then we only need to unwind
-                                    // once more...
-
-                                    if (myTagCompare(d->lpszName, pXML->lpEndTag)==0)
-                                    {
-                                        pXML->cbEndTag = 0;
-                                    }
-
-                                    return TRUE;
-                                } else
-                                    if (pXML->cbNewElement)
-                                    {
-                                        // If the call indicated a new element is to
-                                        // be created on THIS element.
-
-                                        // If the name of this element matches the
-                                        // name of the element we need to create
-                                        // then we need to return to the caller
-                                        // and let it process the element.
-
-                                        if (myTagCompare(d->lpszName, pXML->lpNewElement)==0)
-                                        {
-                                            return TRUE;
-                                        }
-
-                                        // Add the new element and recurse
-                                        pNew = addChild_priv(MEMORYINCREASE,stringDup(pXML->lpNewElement,pXML->cbNewElement),0,-1);
-                                        pXML->cbNewElement = 0;
-                                    }
-                                    else
-                                    {
-                                        // If we didn't have a new element to create
-                                        pNew = emptyXMLNode;
-
-                                    }
-                            }
-                        }
-                    }
-                    break;
-
-                // If we found an end tag
-                case eTokenTagEnd:
-
-                    // If we have node text then add this to the element
-                    if (maybeAddTxT(pXML,token.pStr)) return FALSE;
-
-                    // Find the name of the end tag
-                    token = GetNextToken(pXML, &cbTemp, &xtype);
-
-                    // The end tag should be text
-                    if (xtype != eTokenText)
-                    {
-                        pXML->error = eXMLErrorMissingEndTagName;
-                        return FALSE;
-                    }
-                    lpszTemp = token.pStr;
-
-                    // After the end tag we should find a closing tag
-                    token = GetNextToken(pXML, &cbToken, &xtype);
-                    if (xtype != eTokenCloseTag)
-                    {
-                        pXML->error = eXMLErrorMissingEndTagName;
-                        return FALSE;
-                    }
-                    pXML->lpszText=pXML->lpXML+pXML->nIndex;
-
-                    // We need to return to the previous caller.  If the name
-                    // of the tag cannot be found we need to keep returning to
-                    // caller until we find a match
-                    if (myTagCompare(d->lpszName, lpszTemp) != 0)
-#ifdef STRICT_PARSING
-                    {
-                        pXML->error=eXMLErrorUnmatchedEndTag;
-                        pXML->nIndexMissigEndTag=pXML->nIndex;
-                        return FALSE;
-                    }
-#else
-                    {
-                        pXML->error=eXMLErrorMissingEndTag;
-                        pXML->nIndexMissigEndTag=pXML->nIndex;
-                        pXML->lpEndTag = lpszTemp;
-                        pXML->cbEndTag = cbTemp;
-                    }
-#endif
-
-                    // Return to the caller
-                    exactMemory(d);
-                    return TRUE;
-
-                // If we found a clear (unformatted) token
-                case eTokenClear:
-                    // If we have node text then add this to the element
-                    if (maybeAddTxT(pXML,token.pStr)) return FALSE;
-                    if (parseClearTag(pXML, token.pClr)) return FALSE;
-                    pXML->lpszText=pXML->lpXML+pXML->nIndex;
-                    break;
-
-                default:
-                    break;
-                }
-                break;
-
-            // If we are inside a tag definition we need to search for attributes
-            case eInsideTag:
-
-                // Check what part of the attribute (name, equals, value) we
-                // are looking for.
-                switch(attrib)
-                {
-                // If we are looking for a new attribute
-                case eAttribName:
-
-                    // Check what the current token type is
-                    switch(xtype)
-                    {
-                    // If the current type is text...
-                    // Eg.  'attribute'
-                    case eTokenText:
-                        // Cache the token then indicate that we are next to
-                        // look for the equals
-                        lpszTemp = token.pStr;
-                        cbTemp = cbToken;
-                        attrib = eAttribEquals;
-                        break;
-
-                    // If we found a closing tag...
-                    // Eg.  '>'
-                    case eTokenCloseTag:
-                        // We are now outside the tag
-                        status = eOutsideTag;
-                        pXML->lpszText=pXML->lpXML+pXML->nIndex;
-                        break;
-
-                    // If we found a short hand '/>' closing tag then we can
-                    // return to the caller
-                    case eTokenShortHandClose:
-                        exactMemory(d);
-                        pXML->lpszText=pXML->lpXML+pXML->nIndex;
-                        return TRUE;
-
-                    // Errors...
-                    case eTokenQuotedText:    /* '"SomeText"'   */
-                    case eTokenTagStart:      /* '<'            */
-                    case eTokenTagEnd:        /* '</'           */
-                    case eTokenEquals:        /* '='            */
-                    case eTokenDeclaration:   /* '<?'           */
-                    case eTokenClear:
-                        pXML->error = eXMLErrorUnexpectedToken;
-                        return FALSE;
-                    default: break;
-                    }
-                    break;
-
-                // If we are looking for an equals
-                case eAttribEquals:
-                    // Check what the current token type is
-                    switch(xtype)
-                    {
-                    // If the current type is text...
-                    // Eg.  'Attribute AnotherAttribute'
-                    case eTokenText:
-                        // Add the unvalued attribute to the list
-                        addAttribute_priv(MEMORYINCREASE,stringDup(lpszTemp,cbTemp), NULL);
-                        // Cache the token then indicate.  We are next to
-                        // look for the equals attribute
-                        lpszTemp = token.pStr;
-                        cbTemp = cbToken;
-                        break;
-
-                    // If we found a closing tag 'Attribute >' or a short hand
-                    // closing tag 'Attribute />'
-                    case eTokenShortHandClose:
-                    case eTokenCloseTag:
-                        // If we are a declaration element '<?' then we need
-                        // to remove extra closing '?' if it exists
-                        pXML->lpszText=pXML->lpXML+pXML->nIndex;
-
-                        if (d->isDeclaration &&
-                            (lpszTemp[cbTemp-1]) == _CXML('?'))
-                        {
-                            cbTemp--;
-                            if (d->pParent && d->pParent->pParent) xtype = eTokenShortHandClose;
-                        }
-
-                        if (cbTemp)
-                        {
-                            // Add the unvalued attribute to the list
-                            addAttribute_priv(MEMORYINCREASE,stringDup(lpszTemp,cbTemp), NULL);
-                        }
-
-                        // If this is the end of the tag then return to the caller
-                        if (xtype == eTokenShortHandClose)
-                        {
-                            exactMemory(d);
-                            return TRUE;
-                        }
-
-                        // We are now outside the tag
-                        status = eOutsideTag;
-                        break;
-
-                    // If we found the equals token...
-                    // Eg.  'Attribute ='
-                    case eTokenEquals:
-                        // Indicate that we next need to search for the value
-                        // for the attribute
-                        attrib = eAttribValue;
-                        break;
-
-                    // Errors...
-                    case eTokenQuotedText:    /* 'Attribute "InvalidAttr"'*/
-                    case eTokenTagStart:      /* 'Attribute <'            */
-                    case eTokenTagEnd:        /* 'Attribute </'           */
-                    case eTokenDeclaration:   /* 'Attribute <?'           */
-                    case eTokenClear:
-                        pXML->error = eXMLErrorUnexpectedToken;
-                        return FALSE;
-                    default: break;
-                    }
-                    break;
-
-                // If we are looking for an attribute value
-                case eAttribValue:
-                    // Check what the current token type is
-                    switch(xtype)
-                    {
-                    // If the current type is text or quoted text...
-                    // Eg.  'Attribute = "Value"' or 'Attribute = Value' or
-                    // 'Attribute = 'Value''.
-                    case eTokenText:
-                    case eTokenQuotedText:
-                        // If we are a declaration element '<?' then we need
-                        // to remove extra closing '?' if it exists
-                        if (d->isDeclaration &&
-                            (token.pStr[cbToken-1]) == _CXML('?'))
-                        {
-                            cbToken--;
-                        }
-
-                        if (cbTemp)
-                        {
-                            // Add the valued attribute to the list
-                            if (xtype==eTokenQuotedText) { token.pStr++; cbToken-=2; }
-                            XMLSTR attrVal=(XMLSTR)token.pStr;
-                            if (attrVal)
-                            {
-                                attrVal=fromXMLString(attrVal,cbToken,pXML);
-                                if (!attrVal) return FALSE;
-                            }
-                            addAttribute_priv(MEMORYINCREASE,stringDup(lpszTemp,cbTemp),attrVal);
-                        }
-
-                        // Indicate we are searching for a new attribute
-                        attrib = eAttribName;
-                        break;
-
-                    // Errors...
-                    case eTokenTagStart:        /* 'Attr = <'          */
-                    case eTokenTagEnd:          /* 'Attr = </'         */
-                    case eTokenCloseTag:        /* 'Attr = >'          */
-                    case eTokenShortHandClose:  /* "Attr = />"         */
-                    case eTokenEquals:          /* 'Attr = ='          */
-                    case eTokenDeclaration:     /* 'Attr = <?'         */
-                    case eTokenClear:
-                        pXML->error = eXMLErrorUnexpectedToken;
-                        return FALSE;
-                        break;
-                    default: break;
-                    }
-                }
-            }
-        }
-        // If we failed to obtain the next token
-        else
-        {
-            if ((!d->isDeclaration)&&(d->pParent))
-            {
-#ifdef STRICT_PARSING
-                pXML->error=eXMLErrorUnmatchedEndTag;
-#else
-                pXML->error=eXMLErrorMissingEndTag;
-#endif
-                pXML->nIndexMissigEndTag=pXML->nIndex;
-            }
-            maybeAddTxT(pXML,pXML->lpXML+pXML->nIndex);
-            return FALSE;
-        }
-    }
-}
-
-// Count the number of lines and columns in an XML string.
-static void CountLinesAndColumns(XMLCSTR lpXML, int nUpto, XMLResults *pResults)
-{
-    XMLCHAR ch;
-    assert(lpXML);
-    assert(pResults);
-
-    struct XML xml={ lpXML,lpXML, 0, 0, eXMLErrorNone, NULL, 0, NULL, 0, TRUE };
-
-    pResults->nLine = 1;
-    pResults->nColumn = 1;
-    while (xml.nIndex<nUpto)
-    {
-        ch = getNextChar(&xml);
-        if (ch != _CXML('\n')) pResults->nColumn++;
-        else
-        {
-            pResults->nLine++;
-            pResults->nColumn=1;
-        }
-    }
-}
-
-// Parse XML and return the root element.
-XMLNode XMLNode::parseString(XMLCSTR lpszXML, XMLCSTR tag, XMLResults *pResults)
-{
-    if (!lpszXML)
-    {
-        if (pResults)
-        {
-            pResults->error=eXMLErrorNoElements;
-            pResults->nLine=0;
-            pResults->nColumn=0;
-        }
-        return emptyXMLNode;
-    }
-
-    XMLNode xnode(NULL,NULL,FALSE);
-    struct XML xml={ lpszXML, lpszXML, 0, 0, eXMLErrorNone, NULL, 0, NULL, 0, TRUE };
-
-    // Create header element
-    xnode.ParseXMLElement(&xml);
-    enum XMLError error = xml.error;
-    if (!xnode.nChildNode()) error=eXMLErrorNoXMLTagFound;
-    if ((xnode.nChildNode()==1)&&(xnode.nElement()==1)) xnode=xnode.getChildNode(); // skip the empty node
-
-    // If no error occurred
-    if ((error==eXMLErrorNone)||(error==eXMLErrorMissingEndTag)||(error==eXMLErrorNoXMLTagFound))
-    {
-        XMLCSTR name=xnode.getName();
-        if (tag&&(*tag)&&((!name)||(xstricmp(name,tag))))
-        {
-            xnode=xnode.getChildNode(tag);
-            if (xnode.isEmpty())
-            {
-                if (pResults)
-                {
-                    pResults->error=eXMLErrorFirstTagNotFound;
-                    pResults->nLine=0;
-                    pResults->nColumn=0;
-                }
-                return emptyXMLNode;
-            }
-        }
-    } else
-    {
-        // Cleanup: this will destroy all the nodes
-        xnode = emptyXMLNode;
-    }
-
-
-    // If we have been given somewhere to place results
-    if (pResults)
-    {
-        pResults->error = error;
-
-        // If we have an error
-        if (error!=eXMLErrorNone)
-        {
-            if (error==eXMLErrorMissingEndTag) xml.nIndex=xml.nIndexMissigEndTag;
-            // Find which line and column it starts on.
-            CountLinesAndColumns(xml.lpXML, xml.nIndex, pResults);
-        }
-    }
-    return xnode;
-}
-
-XMLNode XMLNode::parseFile(XMLCSTR filename, XMLCSTR tag, XMLResults *pResults)
-{
-    if (pResults) { pResults->nLine=0; pResults->nColumn=0; }
-    FILE *f=xfopen(filename,_CXML("rb"));
-    if (f==NULL) { if (pResults) pResults->error=eXMLErrorFileNotFound; return emptyXMLNode; }
-    fseek(f,0,SEEK_END);
-    int l=(int)ftell(f),headerSz=0;
-    if (!l) { if (pResults) pResults->error=eXMLErrorEmpty; fclose(f); return emptyXMLNode; }
-    fseek(f,0,SEEK_SET);
-    unsigned char *buf=(unsigned char*)malloc(l+4);
-    l=(int)fread(buf,1,l,f);
-    fclose(f);
-    buf[l]=0;buf[l+1]=0;buf[l+2]=0;buf[l+3]=0;
-#ifdef _XMLWIDECHAR
-    if (guessWideCharChars)
-    {
-        if (!myIsTextWideChar(buf,l))
-        {
-            XMLNode::XMLCharEncoding ce=XMLNode::char_encoding_legacy;
-            if ((buf[0]==0xef)&&(buf[1]==0xbb)&&(buf[2]==0xbf)) { headerSz=3; ce=XMLNode::char_encoding_UTF8; }
-            XMLSTR b2=myMultiByteToWideChar((const char*)(buf+headerSz),ce);
-            free(buf); buf=(unsigned char*)b2; headerSz=0;
-        } else
-        {
-            if ((buf[0]==0xef)&&(buf[1]==0xff)) headerSz=2;
-            if ((buf[0]==0xff)&&(buf[1]==0xfe)) headerSz=2;
-        }
-    }
-#else
-    if (guessWideCharChars)
-    {
-        if (myIsTextWideChar(buf,l))
-        {
-            if ((buf[0]==0xef)&&(buf[1]==0xff)) headerSz=2;
-            if ((buf[0]==0xff)&&(buf[1]==0xfe)) headerSz=2;
-            char *b2=myWideCharToMultiByte((const wchar_t*)(buf+headerSz));
-            free(buf); buf=(unsigned char*)b2; headerSz=0;
-        } else
-        {
-            if ((buf[0]==0xef)&&(buf[1]==0xbb)&&(buf[2]==0xbf)) headerSz=3;
-        }
-    }
-#endif
-
-    if (!buf) { if (pResults) pResults->error=eXMLErrorCharConversionError; return emptyXMLNode; }
-    XMLNode x=parseString((XMLSTR)(buf+headerSz),tag,pResults);
-    free(buf);
-    return x;
-}
-
-static inline void charmemset(XMLSTR dest,XMLCHAR c,int l) { while (l--) *(dest++)=c; }
-// private:
-// Creates an user friendly XML string from a given element with
-// appropriate white space and carriage returns.
-//
-// This recurses through all subnodes then adds contents of the nodes to the
-// string.
-int XMLNode::CreateXMLStringR(XMLNodeData *pEntry, XMLSTR lpszMarker, int nFormat)
-{
-    int nResult = 0;
-    int cb=nFormat<0?0:nFormat;
-    int cbElement;
-    int nChildFormat=-1;
-    int nElementI=pEntry->nChild+pEntry->nText+pEntry->nClear;
-    int i,j;
-    if ((nFormat>=0)&&(nElementI==1)&&(pEntry->nText==1)&&(!pEntry->isDeclaration)) nFormat=-2;
-
-    assert(pEntry);
-
-#define LENSTR(lpsz) (lpsz ? xstrlen(lpsz) : 0)
-
-    // If the element has no name then assume this is the head node.
-    cbElement = (int)LENSTR(pEntry->lpszName);
-
-    if (cbElement)
-    {
-        // "<elementname "
-        if (lpszMarker)
-        {
-            if (cb) charmemset(lpszMarker, INDENTCHAR, cb);
-            nResult = cb;
-            lpszMarker[nResult++]=_CXML('<');
-            if (pEntry->isDeclaration) lpszMarker[nResult++]=_CXML('?');
-            xstrcpy(&lpszMarker[nResult], pEntry->lpszName);
-            nResult+=cbElement;
-            lpszMarker[nResult++]=_CXML(' ');
-
-        } else
-        {
-            nResult+=cbElement+2+cb;
-            if (pEntry->isDeclaration) nResult++;
-        }
-
-        // Enumerate attributes and add them to the string
-        XMLAttribute *pAttr=pEntry->pAttribute;
-        for (i=0; i<pEntry->nAttribute; i++)
-        {
-            // "Attrib
-            cb = (int)LENSTR(pAttr->lpszName);
-            if (cb)
-            {
-                if (lpszMarker) xstrcpy(&lpszMarker[nResult], pAttr->lpszName);
-                nResult += cb;
-                // "Attrib=Value "
-                if (pAttr->lpszValue)
-                {
-                    cb=(int)ToXMLStringTool::lengthXMLString(pAttr->lpszValue);
-                    if (lpszMarker)
-                    {
-                        lpszMarker[nResult]=_CXML('=');
-                        lpszMarker[nResult+1]=_CXML('"');
-                        if (cb) ToXMLStringTool::toXMLUnSafe(&lpszMarker[nResult+2],pAttr->lpszValue);
-                        lpszMarker[nResult+cb+2]=_CXML('"');
-                    }
-                    nResult+=cb+3;
-                }
-                if (lpszMarker) lpszMarker[nResult] = _CXML(' ');
-                nResult++;
-            }
-            pAttr++;
-        }
-
-        if (pEntry->isDeclaration)
-        {
-            if (lpszMarker)
-            {
-                lpszMarker[nResult-1]=_CXML('?');
-                lpszMarker[nResult]=_CXML('>');
-            }
-            nResult++;
-            if (nFormat!=-1)
-            {
-                if (lpszMarker) lpszMarker[nResult]=_CXML('\n');
-                nResult++;
-            }
-        } else
-            // If there are child nodes we need to terminate the start tag
-            if (nElementI)
-            {
-                if (lpszMarker) lpszMarker[nResult-1]=_CXML('>');
-                if (nFormat>=0)
-                {
-                    if (lpszMarker) lpszMarker[nResult]=_CXML('\n');
-                    nResult++;
-                }
-            } else nResult--;
-    }
-
-    // Calculate the child format for when we recurse.  This is used to
-    // determine the number of spaces used for prefixes.
-    if (nFormat!=-1)
-    {
-        if (cbElement&&(!pEntry->isDeclaration)) nChildFormat=nFormat+1;
-        else nChildFormat=nFormat;
-    }
-
-    // Enumerate through remaining children
-    for (i=0; i<nElementI; i++)
-    {
-        j=pEntry->pOrder[i];
-        switch((XMLElementType)(j&3))
-        {
-        // Text nodes
-        case eNodeText:
-            {
-                // "Text"
-                XMLCSTR pChild=pEntry->pText[j>>2];
-                cb = (int)ToXMLStringTool::lengthXMLString(pChild);
-                if (cb)
-                {
-                    if (nFormat>=0)
-                    {
-                        if (lpszMarker)
-                        {
-                            charmemset(&lpszMarker[nResult],INDENTCHAR,nFormat+1);
-                            ToXMLStringTool::toXMLUnSafe(&lpszMarker[nResult+nFormat+1],pChild);
-                            lpszMarker[nResult+nFormat+1+cb]=_CXML('\n');
-                        }
-                        nResult+=cb+nFormat+2;
-                    } else
-                    {
-                        if (lpszMarker) ToXMLStringTool::toXMLUnSafe(&lpszMarker[nResult], pChild);
-                        nResult += cb;
-                    }
-                }
-                break;
-            }
-
-        // Clear type nodes
-        case eNodeClear:
-            {
-                XMLClear *pChild=pEntry->pClear+(j>>2);
-                // "OpenTag"
-                cb = (int)LENSTR(pChild->lpszOpenTag);
-                if (cb)
-                {
-                    if (nFormat!=-1)
-                    {
-                        if (lpszMarker)
-                        {
-                            charmemset(&lpszMarker[nResult], INDENTCHAR, nFormat+1);
-                            xstrcpy(&lpszMarker[nResult+nFormat+1], pChild->lpszOpenTag);
-                        }
-                        nResult+=cb+nFormat+1;
-                    }
-                    else
-                    {
-                        if (lpszMarker)xstrcpy(&lpszMarker[nResult], pChild->lpszOpenTag);
-                        nResult += cb;
-                    }
-                }
-
-                // "OpenTag Value"
-                cb = (int)LENSTR(pChild->lpszValue);
-                if (cb)
-                {
-                    if (lpszMarker) xstrcpy(&lpszMarker[nResult], pChild->lpszValue);
-                    nResult += cb;
-                }
-
-                // "OpenTag Value CloseTag"
-                cb = (int)LENSTR(pChild->lpszCloseTag);
-                if (cb)
-                {
-                    if (lpszMarker) xstrcpy(&lpszMarker[nResult], pChild->lpszCloseTag);
-                    nResult += cb;
-                }
-
-                if (nFormat!=-1)
-                {
-                    if (lpszMarker) lpszMarker[nResult] = _CXML('\n');
-                    nResult++;
-                }
-                break;
-            }
-
-        // Element nodes
-        case eNodeChild:
-            {
-                // Recursively add child nodes
-                nResult += CreateXMLStringR(pEntry->pChild[j>>2].d, lpszMarker ? lpszMarker + nResult : 0, nChildFormat);
-                break;
-            }
-        default: break;
-        }
-    }
-
-    if ((cbElement)&&(!pEntry->isDeclaration))
-    {
-        // If we have child entries we need to use long XML notation for
-        // closing the element - "<elementname>blah blah blah</elementname>"
-        if (nElementI)
-        {
-            // "</elementname>\0"
-            if (lpszMarker)
-            {
-                if (nFormat >=0)
-                {
-                    charmemset(&lpszMarker[nResult], INDENTCHAR,nFormat);
-                    nResult+=nFormat;
-                }
-
-                lpszMarker[nResult]=_CXML('<'); lpszMarker[nResult+1]=_CXML('/');
-                nResult += 2;
-                xstrcpy(&lpszMarker[nResult], pEntry->lpszName);
-                nResult += cbElement;
-
-                lpszMarker[nResult]=_CXML('>');
-                if (nFormat == -1) nResult++;
-                else
-                {
-                    lpszMarker[nResult+1]=_CXML('\n');
-                    nResult+=2;
-                }
-            } else
-            {
-                if (nFormat>=0) nResult+=cbElement+4+nFormat;
-                else if (nFormat==-1) nResult+=cbElement+3;
-                else nResult+=cbElement+4;
-            }
-        } else
-        {
-            // If there are no children we can use shorthand XML notation -
-            // "<elementname/>"
-            // "/>\0"
-            if (lpszMarker)
-            {
-                lpszMarker[nResult]=_CXML('/'); lpszMarker[nResult+1]=_CXML('>');
-                if (nFormat != -1) lpszMarker[nResult+2]=_CXML('\n');
-            }
-            nResult += nFormat == -1 ? 2 : 3;
-        }
-    }
-
-    return nResult;
-}
-
-#undef LENSTR
-
-// Create an XML string
-// @param       int nFormat             - 0 if no formatting is required
-//                                        otherwise nonzero for formatted text
-//                                        with carriage returns and indentation.
-// @param       int *pnSize             - [out] pointer to the size of the
-//                                        returned string not including the
-//                                        NULL terminator.
-// @return      XMLSTR                  - Allocated XML string, you must free
-//                                        this with free().
-XMLSTR XMLNode::createXMLString(int nFormat, int *pnSize) const
-{
-    if (!d) { if (pnSize) *pnSize=0; return NULL; }
-
-    XMLSTR lpszResult = NULL;
-    int cbStr;
-
-    // Recursively Calculate the size of the XML string
-    if (!dropWhiteSpace) nFormat=0;
-    nFormat = nFormat ? 0 : -1;
-    cbStr = CreateXMLStringR(d, 0, nFormat);
-    // Alllocate memory for the XML string + the NULL terminator and
-    // create the recursively XML string.
-    lpszResult=(XMLSTR)malloc((cbStr+1)*sizeof(XMLCHAR));
-    CreateXMLStringR(d, lpszResult, nFormat);
-    lpszResult[cbStr]=_CXML('\0');
-    if (pnSize) *pnSize = cbStr;
-    return lpszResult;
-}
-
-int XMLNode::detachFromParent(XMLNodeData *d)
-{
-    XMLNode *pa=d->pParent->pChild;
-    int i=0;
-    while (((void*)(pa[i].d))!=((void*)d)) i++;
-    d->pParent->nChild--;
-    if (d->pParent->nChild) memmove(pa+i,pa+i+1,(d->pParent->nChild-i)*sizeof(XMLNode));
-    else { free(pa); d->pParent->pChild=NULL; }
-    return removeOrderElement(d->pParent,eNodeChild,i);
-}
-
-XMLNode::~XMLNode()
-{
-    if (!d) return;
-    d->ref_count--;
-    emptyTheNode(0);
-}
-void XMLNode::deleteNodeContent()
-{
-    if (!d) return;
-    if (d->pParent) { detachFromParent(d); d->pParent=NULL; d->ref_count--; }
-    emptyTheNode(1);
-}
-void XMLNode::emptyTheNode(char force)
-{
-    XMLNodeData *dd=d; // warning: must stay this way!
-    if ((dd->ref_count==0)||force)
-    {
-        if (d->pParent) detachFromParent(d);
-        int i;
-        XMLNode *pc;
-        for(i=0; i<dd->nChild; i++)
-        {
-            pc=dd->pChild+i;
-            pc->d->pParent=NULL;
-            pc->d->ref_count--;
-            pc->emptyTheNode(force);
-        }
-        myFree(dd->pChild);
-        for(i=0; i<dd->nText; i++) free((void*)dd->pText[i]);
-        myFree(dd->pText);
-        for(i=0; i<dd->nClear; i++) free((void*)dd->pClear[i].lpszValue);
-        myFree(dd->pClear);
-        for(i=0; i<dd->nAttribute; i++)
-        {
-            free((void*)dd->pAttribute[i].lpszName);
-            if (dd->pAttribute[i].lpszValue) free((void*)dd->pAttribute[i].lpszValue);
-        }
-        myFree(dd->pAttribute);
-        myFree(dd->pOrder);
-        myFree((void*)dd->lpszName);
-        dd->nChild=0;    dd->nText=0;    dd->nClear=0;    dd->nAttribute=0;
-        dd->pChild=NULL; dd->pText=NULL; dd->pClear=NULL; dd->pAttribute=NULL;
-        dd->pOrder=NULL; dd->lpszName=NULL; dd->pParent=NULL;
-    }
-    if (dd->ref_count==0)
-    {
-        free(dd);
-        d=NULL;
-    }
-}
-
-XMLNode& XMLNode::operator=( const XMLNode& A )
-{
-    // shallow copy
-    if (this != &A)
-    {
-        if (d) { d->ref_count--; emptyTheNode(0); }
-        d=A.d;
-        if (d) (d->ref_count) ++ ;
-    }
-    return *this;
-}
-
-XMLNode::XMLNode(const XMLNode &A)
-{
-    // shallow copy
-    d=A.d;
-    if (d) (d->ref_count)++ ;
-}
-
-XMLNode XMLNode::deepCopy() const
-{
-    if (!d) return XMLNode::emptyXMLNode;
-    XMLNode x(NULL,stringDup(d->lpszName),d->isDeclaration);
-    XMLNodeData *p=x.d;
-    int n=d->nAttribute;
-    if (n)
-    {
-        p->nAttribute=n; p->pAttribute=(XMLAttribute*)malloc(n*sizeof(XMLAttribute));
-        while (n--)
-        {
-            p->pAttribute[n].lpszName=stringDup(d->pAttribute[n].lpszName);
-            p->pAttribute[n].lpszValue=stringDup(d->pAttribute[n].lpszValue);
-        }
-    }
-    if (d->pOrder)
-    {
-        n=(d->nChild+d->nText+d->nClear)*sizeof(int); p->pOrder=(int*)malloc(n); memcpy(p->pOrder,d->pOrder,n);
-    }
-    n=d->nText;
-    if (n)
-    {
-        p->nText=n; p->pText=(XMLCSTR*)malloc(n*sizeof(XMLCSTR));
-        while(n--) p->pText[n]=stringDup(d->pText[n]);
-    }
-    n=d->nClear;
-    if (n)
-    {
-        p->nClear=n; p->pClear=(XMLClear*)malloc(n*sizeof(XMLClear));
-        while (n--)
-        {
-            p->pClear[n].lpszCloseTag=d->pClear[n].lpszCloseTag;
-            p->pClear[n].lpszOpenTag=d->pClear[n].lpszOpenTag;
-            p->pClear[n].lpszValue=stringDup(d->pClear[n].lpszValue);
-        }
-    }
-    n=d->nChild;
-    if (n)
-    {
-        p->nChild=n; p->pChild=(XMLNode*)malloc(n*sizeof(XMLNode));
-        while (n--)
-        {
-            p->pChild[n].d=NULL;
-            p->pChild[n]=d->pChild[n].deepCopy();
-            p->pChild[n].d->pParent=p;
-        }
-    }
-    return x;
-}
-
-XMLNode XMLNode::addChild(XMLNode childNode, int pos)
-{
-    XMLNodeData *dc=childNode.d;
-    if ((!dc)||(!d)) return childNode;
-    if (!dc->lpszName)
-    {
-        // this is a root node: todo: correct fix
-        int j=pos;
-        while (dc->nChild)
-        {
-            addChild(dc->pChild[0],j);
-            if (pos>=0) j++;
-        }
-        return childNode;
-    }
-    if (dc->pParent) { if ((detachFromParent(dc)<=pos)&&(dc->pParent==d)) pos--; } else dc->ref_count++;
-    dc->pParent=d;
-//     int nc=d->nChild;
-//     d->pChild=(XMLNode*)myRealloc(d->pChild,(nc+1),memoryIncrease,sizeof(XMLNode));
-    d->pChild=(XMLNode*)addToOrder(0,&pos,d->nChild,d->pChild,sizeof(XMLNode),eNodeChild);
-    d->pChild[pos].d=dc;
-    d->nChild++;
-    return childNode;
-}
-
-void XMLNode::deleteAttribute(int i)
-{
-    if ((!d)||(i<0)||(i>=d->nAttribute)) return;
-    d->nAttribute--;
-    XMLAttribute *p=d->pAttribute+i;
-    free((void*)p->lpszName);
-    if (p->lpszValue) free((void*)p->lpszValue);
-    if (d->nAttribute) memmove(p,p+1,(d->nAttribute-i)*sizeof(XMLAttribute)); else { free(p); d->pAttribute=NULL; }
-}
-
-void XMLNode::deleteAttribute(XMLAttribute *a){ if (a) deleteAttribute(a->lpszName); }
-void XMLNode::deleteAttribute(XMLCSTR lpszName)
-{
-    int j=0;
-    getAttribute(lpszName,&j);
-    if (j) deleteAttribute(j-1);
-}
-
-XMLAttribute *XMLNode::updateAttribute_WOSD(XMLSTR lpszNewValue, XMLSTR lpszNewName,int i)
-{
-    if (!d) { if (lpszNewValue) free(lpszNewValue); if (lpszNewName) free(lpszNewName); return NULL; }
-    if (i>=d->nAttribute)
-    {
-        if (lpszNewName) return addAttribute_WOSD(lpszNewName,lpszNewValue);
-        return NULL;
-    }
-    XMLAttribute *p=d->pAttribute+i;
-    if (p->lpszValue&&p->lpszValue!=lpszNewValue) free((void*)p->lpszValue);
-    p->lpszValue=lpszNewValue;
-    if (lpszNewName&&p->lpszName!=lpszNewName) { free((void*)p->lpszName); p->lpszName=lpszNewName; };
-    return p;
-}
-
-XMLAttribute *XMLNode::updateAttribute_WOSD(XMLAttribute *newAttribute, XMLAttribute *oldAttribute)
-{
-    if (oldAttribute) return updateAttribute_WOSD((XMLSTR)newAttribute->lpszValue,(XMLSTR)newAttribute->lpszName,oldAttribute->lpszName);
-    return addAttribute_WOSD((XMLSTR)newAttribute->lpszName,(XMLSTR)newAttribute->lpszValue);
-}
-
-XMLAttribute *XMLNode::updateAttribute_WOSD(XMLSTR lpszNewValue, XMLSTR lpszNewName,XMLCSTR lpszOldName)
-{
-    int j=0;
-    getAttribute(lpszOldName,&j);
-    if (j) return updateAttribute_WOSD(lpszNewValue,lpszNewName,j-1);
-    else
-    {
-        if (lpszNewName) return addAttribute_WOSD(lpszNewName,lpszNewValue);
-        else             return addAttribute_WOSD(stringDup(lpszOldName),lpszNewValue);
-    }
-}
-
-int XMLNode::indexText(XMLCSTR lpszValue) const
-{
-    if (!d) return -1;
-    int i,l=d->nText;
-    if (!lpszValue) { if (l) return 0; return -1; }
-    XMLCSTR *p=d->pText;
-    for (i=0; i<l; i++) if (lpszValue==p[i]) return i;
-    return -1;
-}
-
-void XMLNode::deleteText(int i)
-{
-    if ((!d)||(i<0)||(i>=d->nText)) return;
-    d->nText--;
-    XMLCSTR *p=d->pText+i;
-    free((void*)*p);
-    if (d->nText) memmove(p,p+1,(d->nText-i)*sizeof(XMLCSTR)); else { free(p); d->pText=NULL; }
-    removeOrderElement(d,eNodeText,i);
-}
-
-void XMLNode::deleteText(XMLCSTR lpszValue) { deleteText(indexText(lpszValue)); }
-
-XMLCSTR XMLNode::updateText_WOSD(XMLSTR lpszNewValue, int i)
-{
-    if (!d) { if (lpszNewValue) free(lpszNewValue); return NULL; }
-    if (i>=d->nText) return addText_WOSD(lpszNewValue);
-    XMLCSTR *p=d->pText+i;
-    if (*p!=lpszNewValue) { free((void*)*p); *p=lpszNewValue; }
-    return lpszNewValue;
-}
-
-XMLCSTR XMLNode::updateText_WOSD(XMLSTR lpszNewValue, XMLCSTR lpszOldValue)
-{
-    if (!d) { if (lpszNewValue) free(lpszNewValue); return NULL; }
-    int i=indexText(lpszOldValue);
-    if (i>=0) return updateText_WOSD(lpszNewValue,i);
-    return addText_WOSD(lpszNewValue);
-}
-
-void XMLNode::deleteClear(int i)
-{
-    if ((!d)||(i<0)||(i>=d->nClear)) return;
-    d->nClear--;
-    XMLClear *p=d->pClear+i;
-    free((void*)p->lpszValue);
-    if (d->nClear) memmove(p,p+1,(d->nClear-i)*sizeof(XMLClear)); else { free(p); d->pClear=NULL; }
-    removeOrderElement(d,eNodeClear,i);
-}
-
-int XMLNode::indexClear(XMLCSTR lpszValue) const
-{
-    if (!d) return -1;
-    int i,l=d->nClear;
-    if (!lpszValue) { if (l) return 0; return -1; }
-    XMLClear *p=d->pClear;
-    for (i=0; i<l; i++) if (lpszValue==p[i].lpszValue) return i;
-    return -1;
-}
-
-void XMLNode::deleteClear(XMLCSTR lpszValue) { deleteClear(indexClear(lpszValue)); }
-void XMLNode::deleteClear(XMLClear *a) { if (a) deleteClear(a->lpszValue); }
-
-XMLClear *XMLNode::updateClear_WOSD(XMLSTR lpszNewContent, int i)
-{
-    if (!d) { if (lpszNewContent) free(lpszNewContent); return NULL; }
-    if (i>=d->nClear) return addClear_WOSD(lpszNewContent);
-    XMLClear *p=d->pClear+i;
-    if (lpszNewContent!=p->lpszValue) { free((void*)p->lpszValue); p->lpszValue=lpszNewContent; }
-    return p;
-}
-
-XMLClear *XMLNode::updateClear_WOSD(XMLSTR lpszNewContent, XMLCSTR lpszOldValue)
-{
-    if (!d) { if (lpszNewContent) free(lpszNewContent); return NULL; }
-    int i=indexClear(lpszOldValue);
-    if (i>=0) return updateClear_WOSD(lpszNewContent,i);
-    return addClear_WOSD(lpszNewContent);
-}
-
-XMLClear *XMLNode::updateClear_WOSD(XMLClear *newP,XMLClear *oldP)
-{
-    if (oldP) return updateClear_WOSD((XMLSTR)newP->lpszValue,(XMLSTR)oldP->lpszValue);
-    return NULL;
-}
-
-int XMLNode::nChildNode(XMLCSTR name) const
-{
-    if (!d) return 0;
-    int i,j=0,n=d->nChild;
-    XMLNode *pc=d->pChild;
-    for (i=0; i<n; i++)
-    {
-        if (xstricmp(pc->d->lpszName, name)==0) j++;
-        pc++;
-    }
-    return j;
-}
-
-XMLNode XMLNode::getChildNode(XMLCSTR name, int *j) const
-{
-    if (!d) return emptyXMLNode;
-    int i=0,n=d->nChild;
-    if (j) i=*j;
-    XMLNode *pc=d->pChild+i;
-    for (; i<n; i++)
-    {
-        if (!xstricmp(pc->d->lpszName, name))
-        {
-            if (j) *j=i+1;
-            return *pc;
-        }
-        pc++;
-    }
-    return emptyXMLNode;
-}
-
-XMLNode XMLNode::getChildNode(XMLCSTR name, int j) const
-{
-    if (!d) return emptyXMLNode;
-    if (j>=0)
-    {
-        int i=0;
-        while (j-->0) getChildNode(name,&i);
-        return getChildNode(name,&i);
-    }
-    int i=d->nChild;
-    while (i--) if (!xstricmp(name,d->pChild[i].d->lpszName)) break;
-    if (i<0) return emptyXMLNode;
-    return getChildNode(i);
-}
-
-XMLNode XMLNode::getChildNodeByPath(XMLCSTR _path, char createMissing, XMLCHAR sep)
-{
-    XMLSTR path=stringDup(_path);
-    XMLNode x=getChildNodeByPathNonConst(path,createMissing,sep);
-    if (path) free(path);
-    return x;
-}
-
-XMLNode XMLNode::getChildNodeByPathNonConst(XMLSTR path, char createIfMissing, XMLCHAR sep)
-{
-    if ((!path)||(!(*path))) return *this;
-    XMLNode xn,xbase=*this;
-    XMLCHAR *tend1,sepString[2]; sepString[0]=sep; sepString[1]=0;
-    tend1=xstrstr(path,sepString);
-    while(tend1)
-    {
-        *tend1=0;
-        xn=xbase.getChildNode(path);
-        if (xn.isEmpty())
-        {
-            if (createIfMissing) xn=xbase.addChild(path);
-            else { *tend1=sep; return XMLNode::emptyXMLNode; }
-        }
-        *tend1=sep;
-        xbase=xn;
-        path=tend1+1;
-        tend1=xstrstr(path,sepString);
-    }
-    xn=xbase.getChildNode(path);
-    if (xn.isEmpty()&&createIfMissing) xn=xbase.addChild(path);
-    return xn;
-}
-
-XMLElementPosition XMLNode::positionOfText     (int i) const { if (i>=d->nText ) i=d->nText-1;  return findPosition(d,i,eNodeText ); }
-XMLElementPosition XMLNode::positionOfClear    (int i) const { if (i>=d->nClear) i=d->nClear-1; return findPosition(d,i,eNodeClear); }
-XMLElementPosition XMLNode::positionOfChildNode(int i) const { if (i>=d->nChild) i=d->nChild-1; return findPosition(d,i,eNodeChild); }
-XMLElementPosition XMLNode::positionOfText (XMLCSTR lpszValue) const { return positionOfText (indexText (lpszValue)); }
-XMLElementPosition XMLNode::positionOfClear(XMLCSTR lpszValue) const { return positionOfClear(indexClear(lpszValue)); }
-XMLElementPosition XMLNode::positionOfClear(XMLClear *a) const { if (a) return positionOfClear(a->lpszValue); return positionOfClear(); }
-XMLElementPosition XMLNode::positionOfChildNode(XMLNode x)  const
-{
-    if ((!d)||(!x.d)) return -1;
-    XMLNodeData *dd=x.d;
-    XMLNode *pc=d->pChild;
-    int i=d->nChild;
-    while (i--) if (pc[i].d==dd) return findPosition(d,i,eNodeChild);
-    return -1;
-}
-XMLElementPosition XMLNode::positionOfChildNode(XMLCSTR name, int count) const
-{
-    if (!name) return positionOfChildNode(count);
-    int j=0;
-    do { getChildNode(name,&j); if (j<0) return -1; } while (count--);
-    return findPosition(d,j-1,eNodeChild);
-}
-
-XMLNode XMLNode::getChildNodeWithAttribute(XMLCSTR name,XMLCSTR attributeName,XMLCSTR attributeValue, int *k) const
-{
-     int i=0,j;
-     if (k) i=*k;
-     XMLNode x;
-     XMLCSTR t;
-     do
-     {
-         x=getChildNode(name,&i);
-         if (!x.isEmpty())
-         {
-             if (attributeValue)
-             {
-                 j=0;
-                 do
-                 {
-                     t=x.getAttribute(attributeName,&j);
-                     if (t&&(xstricmp(attributeValue,t)==0)) { if (k) *k=i; return x; }
-                 } while (t);
-             } else
-             {
-                 if (x.isAttributeSet(attributeName)) { if (k) *k=i; return x; }
-             }
-         }
-     } while (!x.isEmpty());
-     return emptyXMLNode;
-}
-
-// Find an attribute on an node.
-XMLCSTR XMLNode::getAttribute(XMLCSTR lpszAttrib, int *j) const
-{
-    if (!d) return NULL;
-    int i=0,n=d->nAttribute;
-    if (j) i=*j;
-    XMLAttribute *pAttr=d->pAttribute+i;
-    for (; i<n; i++)
-    {
-        if (xstricmp(pAttr->lpszName, lpszAttrib)==0)
-        {
-            if (j) *j=i+1;
-            return pAttr->lpszValue;
-        }
-        pAttr++;
-    }
-    return NULL;
-}
-
-char XMLNode::isAttributeSet(XMLCSTR lpszAttrib) const
-{
-    if (!d) return FALSE;
-    int i,n=d->nAttribute;
-    XMLAttribute *pAttr=d->pAttribute;
-    for (i=0; i<n; i++)
-    {
-        if (xstricmp(pAttr->lpszName, lpszAttrib)==0)
-        {
-            return TRUE;
-        }
-        pAttr++;
-    }
-    return FALSE;
-}
-
-XMLCSTR XMLNode::getAttribute(XMLCSTR name, int j) const
-{
-    if (!d) return NULL;
-    int i=0;
-    while (j-->0) getAttribute(name,&i);
-    return getAttribute(name,&i);
-}
-
-XMLNodeContents XMLNode::enumContents(int i) const
-{
-    XMLNodeContents c;
-    if (!d) { c.etype=eNodeNULL; return c; }
-    if (i<d->nAttribute)
-    {
-        c.etype=eNodeAttribute;
-        c.attrib=d->pAttribute[i];
-        return c;
-    }
-    i-=d->nAttribute;
-    c.etype=(XMLElementType)(d->pOrder[i]&3);
-    i=(d->pOrder[i])>>2;
-    switch (c.etype)
-    {
-    case eNodeChild:     c.child = d->pChild[i];      break;
-    case eNodeText:      c.text  = d->pText[i];       break;
-    case eNodeClear:     c.clear = d->pClear[i];      break;
-    default: break;
-    }
-    return c;
-}
-
-XMLCSTR XMLNode::getName() const { if (!d) return NULL; return d->lpszName;   }
-int XMLNode::nText()       const { if (!d) return 0;    return d->nText;      }
-int XMLNode::nChildNode()  const { if (!d) return 0;    return d->nChild;     }
-int XMLNode::nAttribute()  const { if (!d) return 0;    return d->nAttribute; }
-int XMLNode::nClear()      const { if (!d) return 0;    return d->nClear;     }
-int XMLNode::nElement()    const { if (!d) return 0;    return d->nAttribute+d->nChild+d->nText+d->nClear; }
-XMLClear     XMLNode::getClear         (int i) const { if ((!d)||(i>=d->nClear    )) return emptyXMLClear;     return d->pClear[i];     }
-XMLAttribute XMLNode::getAttribute     (int i) const { if ((!d)||(i>=d->nAttribute)) return emptyXMLAttribute; return d->pAttribute[i]; }
-XMLCSTR      XMLNode::getAttributeName (int i) const { if ((!d)||(i>=d->nAttribute)) return NULL;              return d->pAttribute[i].lpszName;  }
-XMLCSTR      XMLNode::getAttributeValue(int i) const { if ((!d)||(i>=d->nAttribute)) return NULL;              return d->pAttribute[i].lpszValue; }
-XMLCSTR      XMLNode::getText          (int i) const { if ((!d)||(i>=d->nText     )) return NULL;              return d->pText[i];      }
-XMLNode      XMLNode::getChildNode     (int i) const { if ((!d)||(i>=d->nChild    )) return emptyXMLNode;      return d->pChild[i];     }
-XMLNode      XMLNode::getParentNode    (     ) const { if ((!d)||(!d->pParent     )) return emptyXMLNode;      return XMLNode(d->pParent); }
-char         XMLNode::isDeclaration    (     ) const { if (!d) return 0;             return d->isDeclaration; }
-char         XMLNode::isEmpty          (     ) const { return (d==NULL); }
-XMLNode       XMLNode::emptyNode       (     )       { return XMLNode::emptyXMLNode; }
-
-XMLNode       XMLNode::addChild(XMLCSTR lpszName, char isDeclaration, XMLElementPosition pos)
-              { return addChild_priv(0,stringDup(lpszName),isDeclaration,pos); }
-XMLNode       XMLNode::addChild_WOSD(XMLSTR lpszName, char isDeclaration, XMLElementPosition pos)
-              { return addChild_priv(0,lpszName,isDeclaration,pos); }
-XMLAttribute *XMLNode::addAttribute(XMLCSTR lpszName, XMLCSTR lpszValue)
-              { return addAttribute_priv(0,stringDup(lpszName),stringDup(lpszValue)); }
-XMLAttribute *XMLNode::addAttribute_WOSD(XMLSTR lpszName, XMLSTR lpszValuev)
-              { return addAttribute_priv(0,lpszName,lpszValuev); }
-XMLCSTR       XMLNode::addText(XMLCSTR lpszValue, XMLElementPosition pos)
-              { return addText_priv(0,stringDup(lpszValue),pos); }
-XMLCSTR       XMLNode::addText_WOSD(XMLSTR lpszValue, XMLElementPosition pos)
-              { return addText_priv(0,lpszValue,pos); }
-XMLClear     *XMLNode::addClear(XMLCSTR lpszValue, XMLCSTR lpszOpen, XMLCSTR lpszClose, XMLElementPosition pos)
-              { return addClear_priv(0,stringDup(lpszValue),lpszOpen,lpszClose,pos); }
-XMLClear     *XMLNode::addClear_WOSD(XMLSTR lpszValue, XMLCSTR lpszOpen, XMLCSTR lpszClose, XMLElementPosition pos)
-              { return addClear_priv(0,lpszValue,lpszOpen,lpszClose,pos); }
-XMLCSTR       XMLNode::updateName(XMLCSTR lpszName)
-              { return updateName_WOSD(stringDup(lpszName)); }
-XMLAttribute *XMLNode::updateAttribute(XMLAttribute *newAttribute, XMLAttribute *oldAttribute)
-              { return updateAttribute_WOSD(stringDup(newAttribute->lpszValue),stringDup(newAttribute->lpszName),oldAttribute->lpszName); }
-XMLAttribute *XMLNode::updateAttribute(XMLCSTR lpszNewValue, XMLCSTR lpszNewName,int i)
-              { return updateAttribute_WOSD(stringDup(lpszNewValue),stringDup(lpszNewName),i); }
-XMLAttribute *XMLNode::updateAttribute(XMLCSTR lpszNewValue, XMLCSTR lpszNewName,XMLCSTR lpszOldName)
-              { return updateAttribute_WOSD(stringDup(lpszNewValue),stringDup(lpszNewName),lpszOldName); }
-XMLCSTR       XMLNode::updateText(XMLCSTR lpszNewValue, int i)
-              { return updateText_WOSD(stringDup(lpszNewValue),i); }
-XMLCSTR       XMLNode::updateText(XMLCSTR lpszNewValue, XMLCSTR lpszOldValue)
-              { return updateText_WOSD(stringDup(lpszNewValue),lpszOldValue); }
-XMLClear     *XMLNode::updateClear(XMLCSTR lpszNewContent, int i)
-              { return updateClear_WOSD(stringDup(lpszNewContent),i); }
-XMLClear     *XMLNode::updateClear(XMLCSTR lpszNewValue, XMLCSTR lpszOldValue)
-              { return updateClear_WOSD(stringDup(lpszNewValue),lpszOldValue); }
-XMLClear     *XMLNode::updateClear(XMLClear *newP,XMLClear *oldP)
-              { return updateClear_WOSD(stringDup(newP->lpszValue),oldP->lpszValue); }
-
-char XMLNode::setGlobalOptions(XMLCharEncoding _characterEncoding, char _guessWideCharChars,
-                               char _dropWhiteSpace, char _removeCommentsInMiddleOfText)
-{
-    guessWideCharChars=_guessWideCharChars; dropWhiteSpace=_dropWhiteSpace; removeCommentsInMiddleOfText=_removeCommentsInMiddleOfText;
-#ifdef _XMLWIDECHAR
-    if (_characterEncoding) characterEncoding=_characterEncoding;
-#else
-    switch(_characterEncoding)
-    {
-    case char_encoding_UTF8:     characterEncoding=_characterEncoding; XML_ByteTable=XML_utf8ByteTable; break;
-    case char_encoding_legacy:   characterEncoding=_characterEncoding; XML_ByteTable=XML_legacyByteTable; break;
-    case char_encoding_ShiftJIS: characterEncoding=_characterEncoding; XML_ByteTable=XML_sjisByteTable; break;
-    case char_encoding_GB2312:   characterEncoding=_characterEncoding; XML_ByteTable=XML_gb2312ByteTable; break;
-    case char_encoding_Big5:
-    case char_encoding_GBK:      characterEncoding=_characterEncoding; XML_ByteTable=XML_gbk_big5_ByteTable; break;
-    default: return 1;
-    }
-#endif
-    return 0;
-}
-
-XMLNode::XMLCharEncoding XMLNode::guessCharEncoding(void *buf,int l, char useXMLEncodingAttribute)
-{
-#ifdef _XMLWIDECHAR
-    return (XMLCharEncoding)0;
-#else
-    if (l<25) return (XMLCharEncoding)0;
-    if (guessWideCharChars&&(myIsTextWideChar(buf,l))) return (XMLCharEncoding)0;
-    unsigned char *b=(unsigned char*)buf;
-    if ((b[0]==0xef)&&(b[1]==0xbb)&&(b[2]==0xbf)) return char_encoding_UTF8;
-
-    // Match utf-8 model ?
-    XMLCharEncoding bestGuess=char_encoding_UTF8;
-    int i=0;
-    while (i<l)
-        switch (XML_utf8ByteTable[b[i]])
-        {
-        case 4: i++; if ((i<l)&&(b[i]& 0xC0)!=0x80) { bestGuess=char_encoding_legacy; i=l; } // 10bbbbbb ?
-        case 3: i++; if ((i<l)&&(b[i]& 0xC0)!=0x80) { bestGuess=char_encoding_legacy; i=l; } // 10bbbbbb ?
-        case 2: i++; if ((i<l)&&(b[i]& 0xC0)!=0x80) { bestGuess=char_encoding_legacy; i=l; } // 10bbbbbb ?
-        case 1: i++; break;
-        case 0: i=l;
-        }
-    if (!useXMLEncodingAttribute) return bestGuess;
-    // if encoding is specified and different from utf-8 than it's non-utf8
-    // otherwise it's utf-8
-    char bb[201];
-    l=mmin(l,200);
-    memcpy(bb,buf,l); // copy buf into bb to be able to do "bb[l]=0"
-    bb[l]=0;
-    b=(unsigned char*)strstr(bb,"encoding");
-    if (!b) return bestGuess;
-    b+=8; while XML_isSPACECHAR(*b) b++; if (*b!='=') return bestGuess;
-    b++;  while XML_isSPACECHAR(*b) b++; if ((*b!='\'')&&(*b!='"')) return bestGuess;
-    b++;  while XML_isSPACECHAR(*b) b++;
-
-    if ((xstrnicmp((char*)b,"utf-8",5)==0)||
-        (xstrnicmp((char*)b,"utf8",4)==0))
-    {
-        if (bestGuess==char_encoding_legacy) return char_encoding_error;
-        return char_encoding_UTF8;
-    }
-
-    if ((xstrnicmp((char*)b,"shiftjis",8)==0)||
-        (xstrnicmp((char*)b,"shift-jis",9)==0)||
-        (xstrnicmp((char*)b,"sjis",4)==0)) return char_encoding_ShiftJIS;
-
-    if (xstrnicmp((char*)b,"GB2312",6)==0) return char_encoding_GB2312;
-    if (xstrnicmp((char*)b,"Big5",4)==0) return char_encoding_Big5;
-    if (xstrnicmp((char*)b,"GBK",3)==0) return char_encoding_GBK;
-
-    return char_encoding_legacy;
-#endif
-}
-#undef XML_isSPACECHAR
-
-//////////////////////////////////////////////////////////
-//      Here starts the base64 conversion functions.    //
-//////////////////////////////////////////////////////////
-
-static const char base64Fillchar = _CXML('='); // used to mark partial words at the end
-
-// this lookup table defines the base64 encoding
-XMLCSTR base64EncodeTable=_CXML("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
-
-// Decode Table gives the index of any valid base64 character in the Base64 table]
-// 96: '='  -   97: space char   -   98: illegal char   -   99: end of string
-const unsigned char base64DecodeTable[] = {
-    99,98,98,98,98,98,98,98,98,97,  97,98,98,97,98,98,98,98,98,98,  98,98,98,98,98,98,98,98,98,98,  //00 -29
-    98,98,97,98,98,98,98,98,98,98,  98,98,98,62,98,98,98,63,52,53,  54,55,56,57,58,59,60,61,98,98,  //30 -59
-    98,96,98,98,98, 0, 1, 2, 3, 4,   5, 6, 7, 8, 9,10,11,12,13,14,  15,16,17,18,19,20,21,22,23,24,  //60 -89
-    25,98,98,98,98,98,98,26,27,28,  29,30,31,32,33,34,35,36,37,38,  39,40,41,42,43,44,45,46,47,48,  //90 -119
-    49,50,51,98,98,98,98,98,98,98,  98,98,98,98,98,98,98,98,98,98,  98,98,98,98,98,98,98,98,98,98,  //120 -149
-    98,98,98,98,98,98,98,98,98,98,  98,98,98,98,98,98,98,98,98,98,  98,98,98,98,98,98,98,98,98,98,  //150 -179
-    98,98,98,98,98,98,98,98,98,98,  98,98,98,98,98,98,98,98,98,98,  98,98,98,98,98,98,98,98,98,98,  //180 -209
-    98,98,98,98,98,98,98,98,98,98,  98,98,98,98,98,98,98,98,98,98,  98,98,98,98,98,98,98,98,98,98,  //210 -239
-    98,98,98,98,98,98,98,98,98,98,  98,98,98,98,98,98                                               //240 -255
-};
-
-XMLParserBase64Tool::~XMLParserBase64Tool(){ freeBuffer(); }
-
-void XMLParserBase64Tool::freeBuffer(){ if (buf) free(buf); buf=NULL; buflen=0; }
-
-int XMLParserBase64Tool::encodeLength(int inlen, char formatted)
-{
-    unsigned int i=((inlen-1)/3*4+4+1);
-    if (formatted) i+=inlen/54;
-    return i;
-}
-
-XMLSTR XMLParserBase64Tool::encode(unsigned char *inbuf, unsigned int inlen, char formatted)
-{
-    int i=encodeLength(inlen,formatted),k=17,eLen=inlen/3,j;
-    alloc(i*sizeof(XMLCHAR));
-    XMLSTR curr=(XMLSTR)buf;
-    for(i=0;i<eLen;i++)
-    {
-        // Copy next three bytes into lower 24 bits of int, paying attention to sign.
-        j=(inbuf[0]<<16)|(inbuf[1]<<8)|inbuf[2]; inbuf+=3;
-        // Encode the int into four chars
-        *(curr++)=base64EncodeTable[ j>>18      ];
-        *(curr++)=base64EncodeTable[(j>>12)&0x3f];
-        *(curr++)=base64EncodeTable[(j>> 6)&0x3f];
-        *(curr++)=base64EncodeTable[(j    )&0x3f];
-        if (formatted) { if (!k) { *(curr++)=_CXML('\n'); k=18; } k--; }
-    }
-    eLen=inlen-eLen*3; // 0 - 2.
-    if (eLen==1)
-    {
-        *(curr++)=base64EncodeTable[ inbuf[0]>>2      ];
-        *(curr++)=base64EncodeTable[(inbuf[0]<<4)&0x3F];
-        *(curr++)=base64Fillchar;
-        *(curr++)=base64Fillchar;
-    } else if (eLen==2)
-    {
-        j=(inbuf[0]<<8)|inbuf[1];
-        *(curr++)=base64EncodeTable[ j>>10      ];
-        *(curr++)=base64EncodeTable[(j>> 4)&0x3f];
-        *(curr++)=base64EncodeTable[(j<< 2)&0x3f];
-        *(curr++)=base64Fillchar;
-    }
-    *(curr++)=0;
-    return (XMLSTR)buf;
-}
-
-unsigned int XMLParserBase64Tool::decodeSize(XMLCSTR data,XMLError *xe)
-{
-    if (!data) return 0;
-    if (xe) *xe=eXMLErrorNone;
-    int size=0;
-    unsigned char c;
-    //skip any extra characters (e.g. newlines or spaces)
-    while (*data)
-    {
-#ifdef _XMLWIDECHAR
-        if (*data>255) { if (xe) *xe=eXMLErrorBase64DecodeIllegalCharacter; return 0; }
-#endif
-        c=base64DecodeTable[(unsigned char)(*data)];
-        if (c<97) size++;
-        else if (c==98) { if (xe) *xe=eXMLErrorBase64DecodeIllegalCharacter; return 0; }
-        data++;
-    }
-    if (xe&&(size%4!=0)) *xe=eXMLErrorBase64DataSizeIsNotMultipleOf4;
-    if (size==0) return 0;
-    do { data--; size--; } while(*data==base64Fillchar); size++;
-    return (unsigned int)((size*3)/4);
-}
-
-unsigned char XMLParserBase64Tool::decode(XMLCSTR data, unsigned char *buf, int len, XMLError *xe)
-{
-    if (!data) return 0;
-    if (xe) *xe=eXMLErrorNone;
-    int i=0,p=0;
-    unsigned char d,c;
-    for(;;)
-    {
-
-#ifdef _XMLWIDECHAR
-#define BASE64DECODE_READ_NEXT_CHAR(c)                                              \
-        do {                                                                        \
-            if (data[i]>255){ c=98; break; }                                        \
-            c=base64DecodeTable[(unsigned char)data[i++]];                       \
-        }while (c==97);                                                             \
-        if(c==98){ if(xe)*xe=eXMLErrorBase64DecodeIllegalCharacter; return 0; }
-#else
-#define BASE64DECODE_READ_NEXT_CHAR(c)                                           \
-        do { c=base64DecodeTable[(unsigned char)data[i++]]; }while (c==97);   \
-        if(c==98){ if(xe)*xe=eXMLErrorBase64DecodeIllegalCharacter; return 0; }
-#endif
-
-        BASE64DECODE_READ_NEXT_CHAR(c)
-        if (c==99) { return 2; }
-        if (c==96)
-        {
-            if (p==(int)len) return 2;
-            if (xe) *xe=eXMLErrorBase64DecodeTruncatedData;
-            return 1;
-        }
-
-        BASE64DECODE_READ_NEXT_CHAR(d)
-        if ((d==99)||(d==96)) { if (xe) *xe=eXMLErrorBase64DecodeTruncatedData;  return 1; }
-        if (p==(int)len) {      if (xe) *xe=eXMLErrorBase64DecodeBufferTooSmall; return 0; }
-        buf[p++]=(unsigned char)((c<<2)|((d>>4)&0x3));
-
-        BASE64DECODE_READ_NEXT_CHAR(c)
-        if (c==99) { if (xe) *xe=eXMLErrorBase64DecodeTruncatedData;  return 1; }
-        if (p==(int)len)
-        {
-            if (c==96) return 2;
-            if (xe) *xe=eXMLErrorBase64DecodeBufferTooSmall;
-            return 0;
-        }
-        if (c==96) { if (xe) *xe=eXMLErrorBase64DecodeTruncatedData;  return 1; }
-        buf[p++]=(unsigned char)(((d<<4)&0xf0)|((c>>2)&0xf));
-
-        BASE64DECODE_READ_NEXT_CHAR(d)
-        if (d==99 ) { if (xe) *xe=eXMLErrorBase64DecodeTruncatedData;  return 1; }
-        if (p==(int)len)
-        {
-            if (d==96) return 2;
-            if (xe) *xe=eXMLErrorBase64DecodeBufferTooSmall;
-            return 0;
-        }
-        if (d==96) { if (xe) *xe=eXMLErrorBase64DecodeTruncatedData;  return 1; }
-        buf[p++]=(unsigned char)(((c<<6)&0xc0)|d);
-    }
-}
-#undef BASE64DECODE_READ_NEXT_CHAR
-
-void XMLParserBase64Tool::alloc(int newsize)
-{
-    if ((!buf)&&(newsize)) { buf=malloc(newsize); buflen=newsize; return; }
-    if (newsize>buflen) { buf=realloc(buf,newsize); buflen=newsize; }
-}
-
-unsigned char *XMLParserBase64Tool::decode(XMLCSTR data, int *outlen, XMLError *xe)
-{
-    if (xe) *xe=eXMLErrorNone;
-    if (!data) { *outlen=0; return (unsigned char*)""; }
-    unsigned int len=decodeSize(data,xe);
-    if (outlen) *outlen=len;
-    if (!len) return NULL;
-    alloc(len+1);
-    if(!decode(data,(unsigned char*)buf,len,xe)){ return NULL; }
-    return (unsigned char*)buf;
-}
-
+/**
+ ****************************************************************************
+ * <P> XML.c - implementation file for basic XML parser written in ANSI C++
+ * for portability. It works by using recursion and a node tree for breaking
+ * down the elements of an XML document.  </P>
+ *
+ * @version     V2.41
+ * @author      Frank Vanden Berghen
+ *
+ * NOTE:
+ *
+ *   If you add "#define STRICT_PARSING", on the first line of this file
+ *   the parser will see the following XML-stream:
+ *      <a><b>some text</b><b>other text    </a>
+ *   as an error. Otherwise, this tring will be equivalent to:
+ *      <a><b>some text</b><b>other text</b></a>
+ *
+ * NOTE:
+ *
+ *   If you add "#define APPROXIMATE_PARSING" on the first line of this file
+ *   the parser will see the following XML-stream:
+ *     <data name="n1">
+ *     <data name="n2">
+ *     <data name="n3" />
+ *   as equivalent to the following XML-stream:
+ *     <data name="n1" />
+ *     <data name="n2" />
+ *     <data name="n3" />
+ *   This can be useful for badly-formed XML-streams but prevent the use
+ *   of the following XML-stream (problem is: tags at contiguous levels
+ *   have the same names):
+ *     <data name="n1">
+ *        <data name="n2">
+ *            <data name="n3" />
+ *        </data>
+ *     </data>
+ *
+ * NOTE:
+ *
+ *   If you add "#define _XMLPARSER_NO_MESSAGEBOX_" on the first line of this file
+ *   the "openFileHelper" function will always display error messages inside the
+ *   console instead of inside a message-box-window. Message-box-windows are
+ *   available on windows 9x/NT/2000/XP/Vista only.
+ *
+ * Copyright (c) 2002, Business-Insight
+ * <a href="http://www.Business-Insight.com">Business-Insight</a>
+ * All rights reserved.
+ * See the file "AFPL-license.txt" about the licensing terms
+ *
+ ****************************************************************************
+ */
+#ifndef _CRT_SECURE_NO_DEPRECATE
+#define _CRT_SECURE_NO_DEPRECATE
+#endif
+#include "xmlParser.h"
+#ifdef _XMLWINDOWS
+//#ifdef _DEBUG
+//#define _CRTDBG_MAP_ALLOC
+//#include <crtdbg.h>
+//#endif
+#define WIN32_LEAN_AND_MEAN
+#include <Windows.h> // to have IsTextUnicode, MultiByteToWideChar, WideCharToMultiByte to handle unicode files
+                     // to have "MessageBoxA" to display error messages for openFilHelper
+#endif
+
+#include <memory.h>
+#include <assert.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+#include <filemgr.h>
+
+using sword::FileDesc;
+using sword::FileMgr;
+
+XMLCSTR XMLNode::getVersion() { return _CXML("v2.41"); }
+void freeXMLString(XMLSTR t){if(t)free(t);}
+
+static XMLNode::XMLCharEncoding characterEncoding=XMLNode::char_encoding_UTF8;
+static char guessWideCharChars=1, dropWhiteSpace=1, removeCommentsInMiddleOfText=1;
+
+inline int mmin( const int t1, const int t2 ) { return t1 < t2 ? t1 : t2; }
+
+// You can modify the initialization of the variable "XMLClearTags" below
+// to change the clearTags that are currently recognized by the library.
+// The number on the second columns is the length of the string inside the
+// first column. The "<!DOCTYPE" declaration must be the second in the list.
+// The "<!--" declaration must be the third in the list.
+typedef struct { XMLCSTR lpszOpen; int openTagLen; XMLCSTR lpszClose;} ALLXMLClearTag;
+static ALLXMLClearTag XMLClearTags[] =
+{
+    {    _CXML("<![CDATA["),9,  _CXML("]]>")      },
+    {    _CXML("<!DOCTYPE"),9,  _CXML(">")        },
+    {    _CXML("<!--")     ,4,  _CXML("-->")      },
+    {    _CXML("<PRE>")    ,5,  _CXML("</PRE>")   },
+//  {    _CXML("<Script>") ,8,  _CXML("</Script>")},
+    {    NULL              ,0,  NULL           }
+};
+
+// You can modify the initialization of the variable "XMLEntities" below
+// to change the character entities that are currently recognized by the library.
+// The number on the second columns is the length of the string inside the
+// first column. Additionally, the syntaxes "&#xA0;" and "&#160;" are recognized.
+typedef struct { XMLCSTR s; int l; XMLCHAR c;} XMLCharacterEntity;
+static XMLCharacterEntity XMLEntities[] =
+{
+    { _CXML("&amp;" ), 5, _CXML('&' )},
+    { _CXML("&lt;"  ), 4, _CXML('<' )},
+    { _CXML("&gt;"  ), 4, _CXML('>' )},
+    { _CXML("&quot;"), 6, _CXML('\"')},
+    { _CXML("&apos;"), 6, _CXML('\'')},
+    { NULL           , 0, '\0'    }
+};
+
+// When rendering the XMLNode to a string (using the "createXMLString" function),
+// you can ask for a beautiful formatting. This formatting is using the
+// following indentation character:
+#define INDENTCHAR _CXML('\t')
+
+// The following function parses the XML errors into a user friendly string.
+// You can edit this to change the output language of the library to something else.
+XMLCSTR XMLNode::getError(XMLError xerror)
+{
+    switch (xerror)
+    {
+    case eXMLErrorNone:                  return _CXML("No error");
+    case eXMLErrorMissingEndTag:         return _CXML("Warning: Unmatched end tag");
+    case eXMLErrorNoXMLTagFound:         return _CXML("Warning: No XML tag found");
+    case eXMLErrorEmpty:                 return _CXML("Error: No XML data");
+    case eXMLErrorMissingTagName:        return _CXML("Error: Missing start tag name");
+    case eXMLErrorMissingEndTagName:     return _CXML("Error: Missing end tag name");
+    case eXMLErrorUnmatchedEndTag:       return _CXML("Error: Unmatched end tag");
+    case eXMLErrorUnmatchedEndClearTag:  return _CXML("Error: Unmatched clear tag end");
+    case eXMLErrorUnexpectedToken:       return _CXML("Error: Unexpected token found");
+    case eXMLErrorNoElements:            return _CXML("Error: No elements found");
+    case eXMLErrorFileNotFound:          return _CXML("Error: File not found");
+    case eXMLErrorFirstTagNotFound:      return _CXML("Error: First Tag not found");
+    case eXMLErrorUnknownCharacterEntity:return _CXML("Error: Unknown character entity");
+    case eXMLErrorCharacterCodeAbove255: return _CXML("Error: Character code above 255 is forbidden in MultiByte char mode.");
+    case eXMLErrorCharConversionError:   return _CXML("Error: unable to convert between WideChar and MultiByte chars");
+    case eXMLErrorCannotOpenWriteFile:   return _CXML("Error: unable to open file for writing");
+    case eXMLErrorCannotWriteFile:       return _CXML("Error: cannot write into file");
+
+    case eXMLErrorBase64DataSizeIsNotMultipleOf4: return _CXML("Warning: Base64-string length is not a multiple of 4");
+    case eXMLErrorBase64DecodeTruncatedData:      return _CXML("Warning: Base64-string is truncated");
+    case eXMLErrorBase64DecodeIllegalCharacter:   return _CXML("Error: Base64-string contains an illegal character");
+    case eXMLErrorBase64DecodeBufferTooSmall:     return _CXML("Error: Base64 decode output buffer is too small");
+    };
+    return _CXML("Unknown");
+}
+
+/////////////////////////////////////////////////////////////////////////
+//      Here start the abstraction layer to be OS-independent          //
+/////////////////////////////////////////////////////////////////////////
+
+// Here is an abstraction layer to access some common string manipulation functions.
+// The abstraction layer is currently working for gcc, Microsoft Visual Studio 6.0,
+// Microsoft Visual Studio .NET, CC (sun compiler) and Borland C++.
+// If you plan to "port" the library to a new system/compiler, all you have to do is
+// to edit the following lines.
+#ifdef XML_NO_WIDE_CHAR
+char myIsTextWideChar(const void *b, int len) { return FALSE; }
+#else
+    #if defined (UNDER_CE) || !defined(_XMLWINDOWS)
+    char myIsTextWideChar(const void *b, int len) // inspired by the Wine API: RtlIsTextUnicode
+    {
+#ifdef sun
+        // for SPARC processors: wchar_t* buffers must always be alligned, otherwise it's a char* buffer.
+        if ((((unsigned long)b)%sizeof(wchar_t))!=0) return FALSE;
+#endif
+        const wchar_t *s=(const wchar_t*)b;
+
+        // buffer too small:
+        if (len<(int)sizeof(wchar_t)) return FALSE;
+
+        // odd length test
+        if (len&1) return FALSE;
+
+        /* only checks the first 256 characters */
+        len=mmin(256,len/sizeof(wchar_t));
+
+        // Check for the special byte order:
+        if (*((unsigned short*)s) == 0xFFFE) return TRUE;     // IS_TEXT_UNICODE_REVERSE_SIGNATURE;
+        if (*((unsigned short*)s) == 0xFEFF) return TRUE;      // IS_TEXT_UNICODE_SIGNATURE
+
+        // checks for ASCII characters in the UNICODE stream
+        int i,stats=0;
+        for (i=0; i<len; i++) if (s[i]<=(unsigned short)255) stats++;
+        if (stats>len/2) return TRUE;
+
+        // Check for UNICODE NULL chars
+        for (i=0; i<len; i++) if (!s[i]) return TRUE;
+
+        return FALSE;
+    }
+    #else
+    char myIsTextWideChar(const void *b,int l) { return (char)IsTextUnicode((CONST LPVOID)b,l,NULL); };
+    #endif
+#endif
+
+#ifdef _XMLWINDOWS
+// for Microsoft Visual Studio 6.0 and Microsoft Visual Studio .NET and Borland C++ Builder 6.0
+    #ifdef _XMLWIDECHAR
+        wchar_t *myMultiByteToWideChar(const char *s, XMLNode::XMLCharEncoding ce)
+        {
+            int i;
+            if (ce==XMLNode::char_encoding_UTF8) i=(int)MultiByteToWideChar(CP_UTF8,0             ,s,-1,NULL,0);
+            else                            i=(int)MultiByteToWideChar(CP_ACP ,MB_PRECOMPOSED,s,-1,NULL,0);
+            if (i<0) return NULL;
+            wchar_t *d=(wchar_t *)malloc((i+1)*sizeof(XMLCHAR));
+            if (ce==XMLNode::char_encoding_UTF8) i=(int)MultiByteToWideChar(CP_UTF8,0             ,s,-1,d,i);
+            else                            i=(int)MultiByteToWideChar(CP_ACP ,MB_PRECOMPOSED,s,-1,d,i);
+            d[i]=0;
+            return d;
+        }
+        static inline FILE *xfopen(XMLCSTR filename,XMLCSTR mode) { return _wfopen(filename,mode); }
+        static inline int xstrlen(XMLCSTR c)   { return (int)wcslen(c); }
+        static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return _wcsnicmp(c1,c2,l);}
+        static inline int xstrncmp(XMLCSTR c1, XMLCSTR c2, int l) { return wcsncmp(c1,c2,l);}
+        static inline int xstricmp(XMLCSTR c1, XMLCSTR c2) { return _wcsicmp(c1,c2); }
+        static inline XMLSTR xstrstr(XMLCSTR c1, XMLCSTR c2) { return (XMLSTR)wcsstr(c1,c2); }
+        static inline XMLSTR xstrcpy(XMLSTR c1, XMLCSTR c2) { return (XMLSTR)wcscpy(c1,c2); }
+    #else
+        char *myWideCharToMultiByte(const wchar_t *s)
+        {
+            UINT codePage=CP_ACP; if (characterEncoding==XMLNode::char_encoding_UTF8) codePage=CP_UTF8;
+            int i=(int)WideCharToMultiByte(codePage,  // code page
+                0,                       // performance and mapping flags
+                s,                       // wide-character string
+                -1,                       // number of chars in string
+                NULL,                       // buffer for new string
+                0,                       // size of buffer
+                NULL,                    // default for unmappable chars
+                NULL                     // set when default char used
+                );
+            if (i<0) return NULL;
+            char *d=(char*)malloc(i+1);
+            WideCharToMultiByte(codePage,  // code page
+                0,                       // performance and mapping flags
+                s,                       // wide-character string
+                -1,                       // number of chars in string
+                d,                       // buffer for new string
+                i,                       // size of buffer
+                NULL,                    // default for unmappable chars
+                NULL                     // set when default char used
+                );
+            d[i]=0;
+            return d;
+        }
+        static inline FILE *xfopen(XMLCSTR filename,XMLCSTR mode) { return fopen(filename,mode); }
+        static inline int xstrlen(XMLCSTR c)   { return (int)strlen(c); }
+        #ifdef __BORLANDC__
+            static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return strnicmp(c1,c2,l);}
+            static inline int xstricmp(XMLCSTR c1, XMLCSTR c2) { return stricmp(c1,c2); }
+        #else
+            static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return _strnicmp(c1,c2,l);}
+            static inline int xstricmp(XMLCSTR c1, XMLCSTR c2) { return _stricmp(c1,c2); }
+        #endif
+        static inline int xstrncmp(XMLCSTR c1, XMLCSTR c2, int l) { return strncmp(c1,c2,l);}
+        static inline XMLSTR xstrstr(XMLCSTR c1, XMLCSTR c2) { return (XMLSTR)strstr(c1,c2); }
+        static inline XMLSTR xstrcpy(XMLSTR c1, XMLCSTR c2) { return (XMLSTR)strcpy(c1,c2); }
+    #endif
+#else
+// for gcc and CC
+    #ifdef XML_NO_WIDE_CHAR
+        char *myWideCharToMultiByte(const wchar_t *s) { return NULL; }
+    #else
+        char *myWideCharToMultiByte(const wchar_t *s)
+        {
+            const wchar_t *ss=s;
+            int i=(int)wcsrtombs(NULL,&ss,0,NULL);
+            if (i<0) return NULL;
+            char *d=(char *)malloc(i+1);
+            wcsrtombs(d,&s,i,NULL);
+            d[i]=0;
+            return d;
+        }
+    #endif
+    #ifdef _XMLWIDECHAR
+        wchar_t *myMultiByteToWideChar(const char *s, XMLNode::XMLCharEncoding ce)
+        {
+            const char *ss=s;
+            int i=(int)mbsrtowcs(NULL,&ss,0,NULL);
+            if (i<0) return NULL;
+            wchar_t *d=(wchar_t *)malloc((i+1)*sizeof(wchar_t));
+            mbsrtowcs(d,&s,i,NULL);
+            d[i]=0;
+            return d;
+        }
+        int xstrlen(XMLCSTR c)   { return wcslen(c); }
+        #ifdef sun
+        // for CC
+           #include <widec.h>
+           static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return wsncasecmp(c1,c2,l);}
+           static inline int xstrncmp(XMLCSTR c1, XMLCSTR c2, int l) { return wsncmp(c1,c2,l);}
+           static inline int xstricmp(XMLCSTR c1, XMLCSTR c2) { return wscasecmp(c1,c2); }
+        #else
+        static inline int xstrncmp(XMLCSTR c1, XMLCSTR c2, int l) { return wcsncmp(c1,c2,l);}
+            #ifdef __linux__
+            // for gcc/linux
+            static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return wcsncasecmp(c1,c2,l);}
+            static inline int xstricmp(XMLCSTR c1, XMLCSTR c2) { return wcscasecmp(c1,c2); }
+            #else
+            #include <wctype.h>
+            // for gcc/non-linux (MacOS X 10.3, FreeBSD 6.0, NetBSD 3.0, OpenBSD 3.8, AIX 4.3.2, HP-UX 11, IRIX 6.5, OSF/1 5.1, Cygwin, mingw)
+            static inline int xstricmp(XMLCSTR c1, XMLCSTR c2)
+            {
+                wchar_t left,right;
+                do
+                {
+                    left=towlower(*c1++); right=towlower(*c2++);
+                } while (left&&(left==right));
+                return (int)left-(int)right;
+            }
+            static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l)
+            {
+                wchar_t left,right;
+                while(l--)
+                {
+                    left=towlower(*c1++); right=towlower(*c2++);
+                    if ((!left)||(left!=right)) return (int)left-(int)right;
+                }
+                return 0;
+            }
+            #endif
+        #endif
+        static inline XMLSTR xstrstr(XMLCSTR c1, XMLCSTR c2) { return (XMLSTR)wcsstr(c1,c2); }
+        static inline XMLSTR xstrcpy(XMLSTR c1, XMLCSTR c2) { return (XMLSTR)wcscpy(c1,c2); }
+        static inline FILE *xfopen(XMLCSTR filename,XMLCSTR mode)
+        {
+            char *filenameAscii=myWideCharToMultiByte(filename);
+            FILE *f;
+            if (mode[0]==_CXML('r')) f=fopen(filenameAscii,"rb");
+            else                     f=fopen(filenameAscii,"wb");
+            free(filenameAscii);
+            return f;
+        }
+    #else
+        static inline FILE *xfopen(XMLCSTR filename,XMLCSTR mode) { return fopen(filename,mode); }
+        static inline int xstrlen(XMLCSTR c)   { return strlen(c); }
+        static inline int xstrnicmp(XMLCSTR c1, XMLCSTR c2, int l) { return _strnicmp(c1,c2,l);}
+        static inline int xstrncmp(XMLCSTR c1, XMLCSTR c2, int l) { return strncmp(c1,c2,l);}
+        static inline int xstricmp(XMLCSTR c1, XMLCSTR c2) { return _stricmp(c1,c2); }
+        static inline XMLSTR xstrstr(XMLCSTR c1, XMLCSTR c2) { return (XMLSTR)strstr(c1,c2); }
+        static inline XMLSTR xstrcpy(XMLSTR c1, XMLCSTR c2) { return (XMLSTR)strcpy(c1,c2); }
+    #endif
+    //static inline int _strnicmp(const char *c1,const char *c2, int l) { return strncasecmp(c1,c2,l);}
+#endif
+
+
+///////////////////////////////////////////////////////////////////////////////
+//            the "xmltoc,xmltob,xmltoi,xmltol,xmltof,xmltoa" functions      //
+///////////////////////////////////////////////////////////////////////////////
+// These 6 functions are not used inside the XMLparser.
+// There are only here as "convenience" functions for the user.
+// If you don't need them, you can delete them without any trouble.
+#ifdef _XMLWIDECHAR
+    #ifdef _XMLWINDOWS
+    // for Microsoft Visual Studio 6.0 and Microsoft Visual Studio .NET and Borland C++ Builder 6.0
+        char    xmltob(XMLCSTR t,int     v){ if (t&&(*t)) return (char)_wtoi(t); return v; }
+        int     xmltoi(XMLCSTR t,int     v){ if (t&&(*t)) return _wtoi(t); return v; }
+        long    xmltol(XMLCSTR t,long    v){ if (t&&(*t)) return _wtol(t); return v; }
+        double  xmltof(XMLCSTR t,double  v){ if (t&&(*t)) wscanf(t, "%f", &v); /*v=_wtof(t);*/ return v; }
+    #else
+        #ifdef sun
+        // for CC
+           #include <widec.h>
+           char    xmltob(XMLCSTR t,int     v){ if (t) return (char)wstol(t,NULL,10); return v; }
+           int     xmltoi(XMLCSTR t,int     v){ if (t) return (int)wstol(t,NULL,10); return v; }
+           long    xmltol(XMLCSTR t,long    v){ if (t) return wstol(t,NULL,10); return v; }
+        #else
+        // for gcc
+           char    xmltob(XMLCSTR t,int     v){ if (t) return (char)wcstol(t,NULL,10); return v; }
+           int     xmltoi(XMLCSTR t,int     v){ if (t) return (int)wcstol(t,NULL,10); return v; }
+           long    xmltol(XMLCSTR t,long    v){ if (t) return wcstol(t,NULL,10); return v; }
+        #endif
+		double  xmltof(XMLCSTR t,double  v){ if (t&&(*t)) wscanf(t, "%f", &v); /*v=_wtof(t);*/ return v; }
+    #endif
+#else
+    char    xmltob(XMLCSTR t,char    v){ if (t&&(*t)) return (char)atoi(t); return v; }
+    int     xmltoi(XMLCSTR t,int     v){ if (t&&(*t)) return atoi(t); return v; }
+    long    xmltol(XMLCSTR t,long    v){ if (t&&(*t)) return atol(t); return v; }
+    double  xmltof(XMLCSTR t,double  v){ if (t&&(*t)) return atof(t); return v; }
+#endif
+XMLCSTR xmltoa(XMLCSTR t,      XMLCSTR v){ if (t)       return  t; return v; }
+XMLCHAR xmltoc(XMLCSTR t,const XMLCHAR v){ if (t&&(*t)) return *t; return v; }
+
+/////////////////////////////////////////////////////////////////////////
+//                    the "openFileHelper" function                    //
+/////////////////////////////////////////////////////////////////////////
+
+// Since each application has its own way to report and deal with errors, you should modify & rewrite
+// the following "openFileHelper" function to get an "error reporting mechanism" tailored to your needs.
+XMLNode XMLNode::openFileHelper(XMLCSTR filename, XMLCSTR tag)
+{
+    // guess the value of the global parameter "characterEncoding"
+    // (the guess is based on the first 200 bytes of the file).
+	FileDesc * file = FileMgr::getSystemFileMgr()->open(filename , FileMgr::RDONLY);
+
+    if (file->getFd() > 0)
+    {
+        char bb[205];
+        int l = file->read(bb,200);
+        setGlobalOptions(guessCharEncoding(bb,l),guessWideCharChars,dropWhiteSpace,removeCommentsInMiddleOfText);
+        FileMgr::getSystemFileMgr()->close(file);
+    }
+
+    // parse the file
+    XMLResults pResults;
+    XMLNode xnode=XMLNode::parseFile(filename,tag,&pResults);
+
+    if (pResults.error != eXMLErrorNone)
+    	return emptyXMLNode;
+    
+    return xnode;
+}
+
+/////////////////////////////////////////////////////////////////////////
+//      Here start the core implementation of the XMLParser library    //
+/////////////////////////////////////////////////////////////////////////
+
+// You should normally not change anything below this point.
+
+#ifndef _XMLWIDECHAR
+// If "characterEncoding=ascii" then we assume that all characters have the same length of 1 byte.
+// If "characterEncoding=UTF8" then the characters have different lengths (from 1 byte to 4 bytes).
+// If "characterEncoding=ShiftJIS" then the characters have different lengths (from 1 byte to 2 bytes).
+// This table is used as lookup-table to know the length of a character (in byte) based on the
+// content of the first byte of the character.
+// (note: if you modify this, you must always have XML_utf8ByteTable[0]=0 ).
+static const char XML_utf8ByteTable[256] =
+{
+    //  0 1 2 3 4 5 6 7 8 9 a b c d e f
+    0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x00
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x10
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x20
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x30
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x40
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x50
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x60
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x70 End of ASCII range
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x80 0x80 to 0xc1 invalid
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x90
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xa0
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xb0
+    1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xc0 0xc2 to 0xdf 2 byte
+    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xd0
+    3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,// 0xe0 0xe0 to 0xef 3 byte
+    4,4,4,4,4,1,1,1,1,1,1,1,1,1,1,1 // 0xf0 0xf0 to 0xf4 4 byte, 0xf5 and higher invalid
+};
+static const char XML_legacyByteTable[256] =
+{
+    0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
+};
+static const char XML_sjisByteTable[256] =
+{
+    //  0 1 2 3 4 5 6 7 8 9 a b c d e f
+    0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x00
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x10
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x20
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x30
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x40
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x50
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x60
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x70
+    1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0x80 0x81 to 0x9F 2 bytes
+    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0x90
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xa0
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xb0
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xc0
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0xd0
+    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xe0 0xe0 to 0xef 2 bytes
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 // 0xf0
+};
+static const char XML_gb2312ByteTable[256] =
+{
+//  0 1 2 3 4 5 6 7 8 9 a b c d e f
+    0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x00
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x10
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x20
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x30
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x40
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x50
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x60
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x70
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x80
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x90
+    1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xa0 0xa1 to 0xf7 2 bytes
+    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xb0
+    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xc0
+    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xd0
+    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xe0
+    2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1 // 0xf0
+};
+static const char XML_gbk_big5_ByteTable[256] =
+{
+    //  0 1 2 3 4 5 6 7 8 9 a b c d e f
+    0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x00
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x10
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x20
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x30
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x40
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x50
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x60
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,// 0x70
+    1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0x80 0x81 to 0xfe 2 bytes
+    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0x90
+    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xa0
+    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xb0
+    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xc0
+    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xd0
+    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,// 0xe0
+    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1 // 0xf0
+};
+static const char *XML_ByteTable=(const char *)XML_utf8ByteTable; // the default is "characterEncoding=XMLNode::encoding_UTF8"
+#endif
+
+
+XMLNode XMLNode::emptyXMLNode;
+XMLClear XMLNode::emptyXMLClear={ NULL, NULL, NULL};
+XMLAttribute XMLNode::emptyXMLAttribute={ NULL, NULL};
+
+// Enumeration used to decipher what type a token is
+typedef enum XMLTokenTypeTag
+{
+    eTokenText = 0,
+    eTokenQuotedText,
+    eTokenTagStart,         /* "<"            */
+    eTokenTagEnd,           /* "</"           */
+    eTokenCloseTag,         /* ">"            */
+    eTokenEquals,           /* "="            */
+    eTokenDeclaration,      /* "<?"           */
+    eTokenShortHandClose,   /* "/>"           */
+    eTokenClear,
+    eTokenError
+} XMLTokenType;
+
+// Main structure used for parsing XML
+typedef struct XML
+{
+    XMLCSTR                lpXML;
+    XMLCSTR                lpszText;
+    int                    nIndex,nIndexMissigEndTag;
+    enum XMLError          error;
+    XMLCSTR                lpEndTag;
+    int                    cbEndTag;
+    XMLCSTR                lpNewElement;
+    int                    cbNewElement;
+    int                    nFirst;
+} XML;
+
+typedef struct
+{
+    ALLXMLClearTag *pClr;
+    XMLCSTR     pStr;
+} NextToken;
+
+// Enumeration used when parsing attributes
+typedef enum Attrib
+{
+    eAttribName = 0,
+    eAttribEquals,
+    eAttribValue
+} Attrib;
+
+// Enumeration used when parsing elements to dictate whether we are currently
+// inside a tag
+typedef enum Status
+{
+    eInsideTag = 0,
+    eOutsideTag
+} Status;
+
+XMLError XMLNode::writeToFile(XMLCSTR filename, const char *encoding, char nFormat) const
+{
+    if (!d) return eXMLErrorNone;
+
+	FileDesc * file = FileMgr::getSystemFileMgr()->open(filename, FileMgr::CREAT | FileMgr::WRONLY | FileMgr::TRUNC );
+    
+	if (file->getFd() <= 0) return eXMLErrorCannotOpenWriteFile;
+
+#ifdef _XMLWIDECHAR
+    unsigned char h[2]={ 0xFF, 0xFE };
+    if (!write(f,h,2)) return eXMLErrorCannotWriteFile;
+    if ((!isDeclaration())&&((d->lpszName)||(!getChildNode().isDeclaration())))
+    {
+        if (!write(f,L"<?xml version=\"1.0\" encoding=\"utf-16\"?>\n",sizeof(wchar_t)*40))
+            return eXMLErrorCannotWriteFile;
+    }
+#else
+    if ((!isDeclaration())&&((d->lpszName)||(!getChildNode().isDeclaration())))
+    {
+        if (characterEncoding==char_encoding_UTF8)
+        {
+            // header so that windows recognize the file as UTF-8:
+            unsigned char h[3]={0xEF,0xBB,0xBF}; if (!file->write(h,3)) return eXMLErrorCannotWriteFile;
+            encoding="utf-8";
+        } else if (characterEncoding==char_encoding_ShiftJIS) encoding="SHIFT-JIS";
+
+        if (!encoding) encoding="ISO-8859-1";
+
+        if (!file->write("<?xml version=\"1.0\" encoding=\"",30)) return eXMLErrorCannotWriteFile;
+		if (!file->write(encoding,strlen(encoding))) return eXMLErrorCannotWriteFile;
+		if (!file->write("\"?>\n",4)) return eXMLErrorCannotWriteFile;
+    } else
+    {
+        if (characterEncoding==char_encoding_UTF8)
+        {
+            unsigned char h[3]={0xEF,0xBB,0xBF}; if (!file->write(h,3)) return eXMLErrorCannotWriteFile;
+        }
+    }
+#endif
+    
+	int i;
+
+    XMLSTR t = createXMLString(nFormat,&i);
+    
+	if (!file->write(t,sizeof(XMLCHAR)*i)) return eXMLErrorCannotWriteFile;
+    
+	FileMgr::getSystemFileMgr()->close(file);
+    
+	free(t);
+
+    return eXMLErrorNone;
+}
+
+// Duplicate a given string.
+XMLSTR stringDup(XMLCSTR lpszData, int cbData)
+{
+    if (lpszData==NULL) return NULL;
+
+    XMLSTR lpszNew;
+    if (cbData==-1) cbData=(int)xstrlen(lpszData);
+    lpszNew = (XMLSTR)malloc((cbData+1) * sizeof(XMLCHAR));
+    if (lpszNew)
+    {
+        memcpy(lpszNew, lpszData, (cbData) * sizeof(XMLCHAR));
+        lpszNew[cbData] = (XMLCHAR)NULL;
+    }
+    return lpszNew;
+}
+
+XMLSTR ToXMLStringTool::toXMLUnSafe(XMLSTR dest,XMLCSTR source)
+{
+    XMLSTR dd=dest;
+    XMLCHAR ch;
+    XMLCharacterEntity *entity;
+    while ((ch=*source))
+    {
+        entity=XMLEntities;
+        do
+        {
+            if (ch==entity->c) {xstrcpy(dest,entity->s); dest+=entity->l; source++; goto out_of_loop1; }
+            entity++;
+        } while(entity->s);
+#ifdef _XMLWIDECHAR
+        *(dest++)=*(source++);
+#else
+        switch(XML_ByteTable[(unsigned char)ch])
+        {
+        case 4: *(dest++)=*(source++);
+        case 3: *(dest++)=*(source++);
+        case 2: *(dest++)=*(source++);
+        case 1: *(dest++)=*(source++);
+        }
+#endif
+out_of_loop1:
+        ;
+    }
+    *dest=0;
+    return dd;
+}
+
+// private (used while rendering):
+int ToXMLStringTool::lengthXMLString(XMLCSTR source)
+{
+    int r=0;
+    XMLCharacterEntity *entity;
+    XMLCHAR ch;
+    while ((ch=*source))
+    {
+        entity=XMLEntities;
+        do
+        {
+            if (ch==entity->c) { r+=entity->l; source++; goto out_of_loop1; }
+            entity++;
+        } while(entity->s);
+#ifdef _XMLWIDECHAR
+        r++; source++;
+#else
+        ch=XML_ByteTable[(unsigned char)ch]; r+=ch; source+=ch;
+#endif
+out_of_loop1:
+        ;
+    }
+    return r;
+}
+
+ToXMLStringTool::~ToXMLStringTool(){ freeBuffer(); }
+void ToXMLStringTool::freeBuffer(){ if (buf) free(buf); buf=NULL; buflen=0; }
+XMLSTR ToXMLStringTool::toXML(XMLCSTR source)
+{
+    if (!source) return _CXML("");
+    int l=lengthXMLString(source)+1;
+    if (l>buflen) { buflen=l; buf=(XMLSTR)realloc(buf,l*sizeof(XMLCHAR)); }
+    return toXMLUnSafe(buf,source);
+}
+
+// private:
+XMLSTR fromXMLString(XMLCSTR s, int lo, XML *pXML)
+{
+    // This function is the opposite of the function "toXMLString". It decodes the escape
+    // sequences &amp;, &quot;, &apos;, &lt;, &gt; and replace them by the characters
+    // &,",',<,>. This function is used internally by the XML Parser. All the calls to
+    // the XML library will always gives you back "decoded" strings.
+    //
+    // in: string (s) and length (lo) of string
+    // out:  new allocated string converted from xml
+    if (!s) return NULL;
+
+    int ll=0,j;
+    XMLSTR d;
+    XMLCSTR ss=s;
+    XMLCharacterEntity *entity;
+    while ((lo>0)&&(*s))
+    {
+        if (*s==_CXML('&'))
+        {
+            if ((lo>2)&&(s[1]==_CXML('#')))
+            {
+                s+=2; lo-=2;
+                if ((*s==_CXML('X'))||(*s==_CXML('x'))) { s++; lo--; }
+                while ((*s)&&(*s!=_CXML(';'))&&((lo--)>0)) s++;
+                if (*s!=_CXML(';'))
+                {
+                    pXML->error=eXMLErrorUnknownCharacterEntity;
+                    return NULL;
+                }
+                s++; lo--;
+            } else
+            {
+                entity=XMLEntities;
+                do
+                {
+                    if ((lo>=entity->l)&&(xstrnicmp(s,entity->s,entity->l)==0)) { s+=entity->l; lo-=entity->l; break; }
+                    entity++;
+                } while(entity->s);
+                if (!entity->s)
+                {
+                    pXML->error=eXMLErrorUnknownCharacterEntity;
+                    return NULL;
+                }
+            }
+        } else
+        {
+#ifdef _XMLWIDECHAR
+            s++; lo--;
+#else
+            j=XML_ByteTable[(unsigned char)*s]; s+=j; lo-=j; ll+=j-1;
+#endif
+        }
+        ll++;
+    }
+
+    d=(XMLSTR)malloc((ll+1)*sizeof(XMLCHAR));
+    s=d;
+    while (ll-->0)
+    {
+        if (*ss==_CXML('&'))
+        {
+            if (ss[1]==_CXML('#'))
+            {
+                ss+=2; j=0;
+                if ((*ss==_CXML('X'))||(*ss==_CXML('x')))
+                {
+                    ss++;
+                    while (*ss!=_CXML(';'))
+                    {
+                        if ((*ss>=_CXML('0'))&&(*ss<=_CXML('9'))) j=(j<<4)+*ss-_CXML('0');
+                        else if ((*ss>=_CXML('A'))&&(*ss<=_CXML('F'))) j=(j<<4)+*ss-_CXML('A')+10;
+                        else if ((*ss>=_CXML('a'))&&(*ss<=_CXML('f'))) j=(j<<4)+*ss-_CXML('a')+10;
+                        else { free((void*)s); pXML->error=eXMLErrorUnknownCharacterEntity;return NULL;}
+                        ss++;
+                    }
+                } else
+                {
+                    while (*ss!=_CXML(';'))
+                    {
+                        if ((*ss>=_CXML('0'))&&(*ss<=_CXML('9'))) j=(j*10)+*ss-_CXML('0');
+                        else { free((void*)s); pXML->error=eXMLErrorUnknownCharacterEntity;return NULL;}
+                        ss++;
+                    }
+                }
+#ifndef _XMLWIDECHAR
+                if (j>255) { free((void*)s); pXML->error=eXMLErrorCharacterCodeAbove255;return NULL;}
+#endif
+                (*d++)=(XMLCHAR)j; ss++;
+            } else
+            {
+                entity=XMLEntities;
+                do
+                {
+                    if (xstrnicmp(ss,entity->s,entity->l)==0) { *(d++)=entity->c; ss+=entity->l; break; }
+                    entity++;
+                } while(entity->s);
+            }
+        } else
+        {
+#ifdef _XMLWIDECHAR
+            *(d++)=*(ss++);
+#else
+            switch(XML_ByteTable[(unsigned char)*ss])
+            {
+            case 4: *(d++)=*(ss++); ll--;
+            case 3: *(d++)=*(ss++); ll--;
+            case 2: *(d++)=*(ss++); ll--;
+            case 1: *(d++)=*(ss++);
+            }
+#endif
+        }
+    }
+    *d=0;
+    return (XMLSTR)s;
+}
+
+#define XML_isSPACECHAR(ch) ((ch==_CXML('\n'))||(ch==_CXML(' '))||(ch== _CXML('\t'))||(ch==_CXML('\r')))
+
+// private:
+char myTagCompare(XMLCSTR cclose, XMLCSTR copen)
+// !!!! WARNING strange convention&:
+// return 0 if equals
+// return 1 if different
+{
+    if (!cclose) return 1;
+    int l=(int)xstrlen(cclose);
+    if (xstrnicmp(cclose, copen, l)!=0) return 1;
+    const XMLCHAR c=copen[l];
+    if (XML_isSPACECHAR(c)||
+        (c==_CXML('/' ))||
+        (c==_CXML('<' ))||
+        (c==_CXML('>' ))||
+        (c==_CXML('=' ))) return 0;
+    return 1;
+}
+
+// Obtain the next character from the string.
+static inline XMLCHAR getNextChar(XML *pXML)
+{
+    XMLCHAR ch = pXML->lpXML[pXML->nIndex];
+#ifdef _XMLWIDECHAR
+    if (ch!=0) pXML->nIndex++;
+#else
+    pXML->nIndex+=XML_ByteTable[(unsigned char)ch];
+#endif
+    return ch;
+}
+
+// Find the next token in a string.
+// pcbToken contains the number of characters that have been read.
+static NextToken GetNextToken(XML *pXML, int *pcbToken, enum XMLTokenTypeTag *pType)
+{
+    NextToken        result;
+    XMLCHAR            ch;
+    XMLCHAR            chTemp;
+    int              indexStart,nFoundMatch,nIsText=FALSE;
+    result.pClr=NULL; // prevent warning
+
+    // Find next non-white space character
+    do { indexStart=pXML->nIndex; ch=getNextChar(pXML); } while XML_isSPACECHAR(ch);
+
+    if (ch)
+    {
+        // Cache the current string pointer
+        result.pStr = &pXML->lpXML[indexStart];
+
+        // First check whether the token is in the clear tag list (meaning it
+        // does not need formatting).
+        ALLXMLClearTag *ctag=XMLClearTags;
+        do
+        {
+            if (xstrncmp(ctag->lpszOpen, result.pStr, ctag->openTagLen)==0)
+            {
+                result.pClr=ctag;
+                pXML->nIndex+=ctag->openTagLen-1;
+                *pType=eTokenClear;
+                return result;
+            }
+            ctag++;
+        } while(ctag->lpszOpen);
+
+        // If we didn't find a clear tag then check for standard tokens
+        switch(ch)
+        {
+        // Check for quotes
+        case _CXML('\''):
+        case _CXML('\"'):
+            // Type of token
+            *pType = eTokenQuotedText;
+            chTemp = ch;
+
+            // Set the size
+            nFoundMatch = FALSE;
+
+            // Search through the string to find a matching quote
+            while((ch = getNextChar(pXML)))
+            {
+                if (ch==chTemp) { nFoundMatch = TRUE; break; }
+                if (ch==_CXML('<')) break;
+            }
+
+            // If we failed to find a matching quote
+            if (nFoundMatch == FALSE)
+            {
+                pXML->nIndex=indexStart+1;
+                nIsText=TRUE;
+                break;
+            }
+
+//  4.02.2002
+//            if (FindNonWhiteSpace(pXML)) pXML->nIndex--;
+
+            break;
+
+        // Equals (used with attribute values)
+        case _CXML('='):
+            *pType = eTokenEquals;
+            break;
+
+        // Close tag
+        case _CXML('>'):
+            *pType = eTokenCloseTag;
+            break;
+
+        // Check for tag start and tag end
+        case _CXML('<'):
+
+            // Peek at the next character to see if we have an end tag '</',
+            // or an xml declaration '<?'
+            chTemp = pXML->lpXML[pXML->nIndex];
+
+            // If we have a tag end...
+            if (chTemp == _CXML('/'))
+            {
+                // Set the type and ensure we point at the next character
+                getNextChar(pXML);
+                *pType = eTokenTagEnd;
+            }
+
+            // If we have an XML declaration tag
+            else if (chTemp == _CXML('?'))
+            {
+
+                // Set the type and ensure we point at the next character
+                getNextChar(pXML);
+                *pType = eTokenDeclaration;
+            }
+
+            // Otherwise we must have a start tag
+            else
+            {
+                *pType = eTokenTagStart;
+            }
+            break;
+
+        // Check to see if we have a short hand type end tag ('/>').
+        case _CXML('/'):
+
+            // Peek at the next character to see if we have a short end tag '/>'
+            chTemp = pXML->lpXML[pXML->nIndex];
+
+            // If we have a short hand end tag...
+            if (chTemp == _CXML('>'))
+            {
+                // Set the type and ensure we point at the next character
+                getNextChar(pXML);
+                *pType = eTokenShortHandClose;
+                break;
+            }
+
+            // If we haven't found a short hand closing tag then drop into the
+            // text process
+
+        // Other characters
+        default:
+            nIsText = TRUE;
+        }
+
+        // If this is a TEXT node
+        if (nIsText)
+        {
+            // Indicate we are dealing with text
+            *pType = eTokenText;
+            while((ch = getNextChar(pXML)))
+            {
+                if XML_isSPACECHAR(ch)
+                {
+                    indexStart++; break;
+
+                } else if (ch==_CXML('/'))
+                {
+                    // If we find a slash then this maybe text or a short hand end tag
+                    // Peek at the next character to see it we have short hand end tag
+                    ch=pXML->lpXML[pXML->nIndex];
+                    // If we found a short hand end tag then we need to exit the loop
+                    if (ch==_CXML('>')) { pXML->nIndex--; break; }
+
+                } else if ((ch==_CXML('<'))||(ch==_CXML('>'))||(ch==_CXML('=')))
+                {
+                    pXML->nIndex--; break;
+                }
+            }
+        }
+        *pcbToken = pXML->nIndex-indexStart;
+    } else
+    {
+        // If we failed to obtain a valid character
+        *pcbToken = 0;
+        *pType = eTokenError;
+        result.pStr=NULL;
+    }
+
+    return result;
+}
+
+XMLCSTR XMLNode::updateName_WOSD(XMLSTR lpszName)
+{
+    if (!d) { free(lpszName); return NULL; }
+    if (d->lpszName&&(lpszName!=d->lpszName)) free((void*)d->lpszName);
+    d->lpszName=lpszName;
+    return lpszName;
+}
+
+// private:
+XMLNode::XMLNode(struct XMLNodeDataTag *p){ d=p; (p->ref_count)++; }
+XMLNode::XMLNode(XMLNodeData *pParent, XMLSTR lpszName, char isDeclaration)
+{
+    d=(XMLNodeData*)malloc(sizeof(XMLNodeData));
+    d->ref_count=1;
+
+    d->lpszName=NULL;
+    d->nChild= 0;
+    d->nText = 0;
+    d->nClear = 0;
+    d->nAttribute = 0;
+
+    d->isDeclaration = isDeclaration;
+
+    d->pParent = pParent;
+    d->pChild= NULL;
+    d->pText= NULL;
+    d->pClear= NULL;
+    d->pAttribute= NULL;
+    d->pOrder= NULL;
+
+    updateName_WOSD(lpszName);
+}
+
+XMLNode XMLNode::createXMLTopNode_WOSD(XMLSTR lpszName, char isDeclaration) { return XMLNode(NULL,lpszName,isDeclaration); }
+XMLNode XMLNode::createXMLTopNode(XMLCSTR lpszName, char isDeclaration) { return XMLNode(NULL,stringDup(lpszName),isDeclaration); }
+
+#define MEMORYINCREASE 50
+
+static inline void myFree(void *p) { if (p) free(p); }
+static inline void *myRealloc(void *p, int newsize, int memInc, int sizeofElem)
+{
+    if (p==NULL) { if (memInc) return malloc(memInc*sizeofElem); return malloc(sizeofElem); }
+    if ((memInc==0)||((newsize%memInc)==0)) p=realloc(p,(newsize+memInc)*sizeofElem);
+//    if (!p)
+//    {
+//        printf("XMLParser Error: Not enough memory! Aborting...\n"); exit(220);
+//    }
+    return p;
+}
+
+// private:
+XMLElementPosition XMLNode::findPosition(XMLNodeData *d, int index, XMLElementType xxtype)
+{
+    if (index<0) return -1;
+    int i=0,j=(int)((index<<2)+xxtype),*o=d->pOrder; while (o[i]!=j) i++; return i;
+}
+
+// private:
+// update "order" information when deleting a content of a XMLNode
+int XMLNode::removeOrderElement(XMLNodeData *d, XMLElementType t, int index)
+{
+    int n=d->nChild+d->nText+d->nClear, *o=d->pOrder,i=findPosition(d,index,t);
+    memmove(o+i, o+i+1, (n-i)*sizeof(int));
+    for (;i<n;i++)
+        if ((o[i]&3)==(int)t) o[i]-=4;
+    // We should normally do:
+    // d->pOrder=(int)realloc(d->pOrder,n*sizeof(int));
+    // but we skip reallocation because it's too time consuming.
+    // Anyway, at the end, it will be free'd completely at once.
+    return i;
+}
+
+void *XMLNode::addToOrder(int memoryIncrease,int *_pos, int nc, void *p, int size, XMLElementType xtype)
+{
+    //  in: *_pos is the position inside d->pOrder ("-1" means "EndOf")
+    // out: *_pos is the index inside p
+    p=myRealloc(p,(nc+1),memoryIncrease,size);
+    int n=d->nChild+d->nText+d->nClear;
+    d->pOrder=(int*)myRealloc(d->pOrder,n+1,memoryIncrease*3,sizeof(int));
+    int pos=*_pos,*o=d->pOrder;
+
+    if ((pos<0)||(pos>=n)) { *_pos=nc; o[n]=(int)((nc<<2)+xtype); return p; }
+
+    int i=pos;
+    memmove(o+i+1, o+i, (n-i)*sizeof(int));
+
+    while ((pos<n)&&((o[pos]&3)!=(int)xtype)) pos++;
+    if (pos==n) { *_pos=nc; o[n]=(int)((nc<<2)+xtype); return p; }
+
+    o[i]=o[pos];
+    for (i=pos+1;i<=n;i++) if ((o[i]&3)==(int)xtype) o[i]+=4;
+
+    *_pos=pos=o[pos]>>2;
+    memmove(((char*)p)+(pos+1)*size,((char*)p)+pos*size,(nc-pos)*size);
+
+    return p;
+}
+
+// Add a child node to the given element.
+XMLNode XMLNode::addChild_priv(int memoryIncrease, XMLSTR lpszName, char isDeclaration, int pos)
+{
+    if (!lpszName) return emptyXMLNode;
+	if (!d) return emptyXMLNode;
+    d->pChild=(XMLNode*)addToOrder(memoryIncrease,&pos,d->nChild,d->pChild,sizeof(XMLNode),eNodeChild);
+    d->pChild[pos].d=NULL;
+    d->pChild[pos]=XMLNode(d,lpszName,isDeclaration);
+    d->nChild++;
+    return d->pChild[pos];
+}
+
+// Add an attribute to an element.
+XMLAttribute *XMLNode::addAttribute_priv(int memoryIncrease,XMLSTR lpszName, XMLSTR lpszValuev)
+{
+    if (!lpszName) return &emptyXMLAttribute;
+    if (!d) { myFree(lpszName); myFree(lpszValuev); return &emptyXMLAttribute; }
+    int nc=d->nAttribute;
+    d->pAttribute=(XMLAttribute*)myRealloc(d->pAttribute,(nc+1),memoryIncrease,sizeof(XMLAttribute));
+    XMLAttribute *pAttr=d->pAttribute+nc;
+    pAttr->lpszName = lpszName;
+    pAttr->lpszValue = lpszValuev;
+    d->nAttribute++;
+    return pAttr;
+}
+
+// Add text to the element.
+XMLCSTR XMLNode::addText_priv(int memoryIncrease, XMLSTR lpszValue, int pos)
+{
+    if (!lpszValue) return NULL;
+    if (!d) { myFree(lpszValue); return NULL; }
+    d->pText=(XMLCSTR*)addToOrder(memoryIncrease,&pos,d->nText,d->pText,sizeof(XMLSTR),eNodeText);
+    d->pText[pos]=lpszValue;
+    d->nText++;
+    return lpszValue;
+}
+
+// Add clear (unformatted) text to the element.
+XMLClear *XMLNode::addClear_priv(int memoryIncrease, XMLSTR lpszValue, XMLCSTR lpszOpen, XMLCSTR lpszClose, int pos)
+{
+    if (!lpszValue) return &emptyXMLClear;
+    if (!d) { myFree(lpszValue); return &emptyXMLClear; }
+    d->pClear=(XMLClear *)addToOrder(memoryIncrease,&pos,d->nClear,d->pClear,sizeof(XMLClear),eNodeClear);
+    XMLClear *pNewClear=d->pClear+pos;
+    pNewClear->lpszValue = lpszValue;
+    if (!lpszOpen) lpszOpen=XMLClearTags->lpszOpen;
+    if (!lpszClose) lpszClose=XMLClearTags->lpszClose;
+    pNewClear->lpszOpenTag = lpszOpen;
+    pNewClear->lpszCloseTag = lpszClose;
+    d->nClear++;
+    return pNewClear;
+}
+
+// private:
+// Parse a clear (unformatted) type node.
+char XMLNode::parseClearTag(void *px, void *_pClear)
+{
+    XML *pXML=(XML *)px;
+    ALLXMLClearTag pClear=*((ALLXMLClearTag*)_pClear);
+    int cbTemp=0;
+    XMLCSTR lpszTemp=NULL;
+    XMLCSTR lpXML=&pXML->lpXML[pXML->nIndex];
+    static XMLCSTR docTypeEnd=_CXML("]>");
+
+    // Find the closing tag
+    // Seems the <!DOCTYPE need a better treatment so lets handle it
+    if (pClear.lpszOpen==XMLClearTags[1].lpszOpen)
+    {
+        XMLCSTR pCh=lpXML;
+        while (*pCh)
+        {
+            if (*pCh==_CXML('<')) { pClear.lpszClose=docTypeEnd; lpszTemp=xstrstr(lpXML,docTypeEnd); break; }
+            else if (*pCh==_CXML('>')) { lpszTemp=pCh; break; }
+#ifdef _XMLWIDECHAR
+            pCh++;
+#else
+            pCh+=XML_ByteTable[(unsigned char)(*pCh)];
+#endif
+        }
+    } else lpszTemp=xstrstr(lpXML, pClear.lpszClose);
+
+    if (lpszTemp)
+    {
+        // Cache the size and increment the index
+        cbTemp = (int)(lpszTemp - lpXML);
+
+        pXML->nIndex += cbTemp+(int)xstrlen(pClear.lpszClose);
+
+        // Add the clear node to the current element
+        addClear_priv(MEMORYINCREASE,stringDup(lpXML,cbTemp), pClear.lpszOpen, pClear.lpszClose,-1);
+        return 0;
+    }
+
+    // If we failed to find the end tag
+    pXML->error = eXMLErrorUnmatchedEndClearTag;
+    return 1;
+}
+
+void XMLNode::exactMemory(XMLNodeData *d)
+{
+    if (d->pOrder)     d->pOrder=(int*)realloc(d->pOrder,(d->nChild+d->nText+d->nClear)*sizeof(int));
+    if (d->pChild)     d->pChild=(XMLNode*)realloc(d->pChild,d->nChild*sizeof(XMLNode));
+    if (d->pAttribute) d->pAttribute=(XMLAttribute*)realloc(d->pAttribute,d->nAttribute*sizeof(XMLAttribute));
+    if (d->pText)      d->pText=(XMLCSTR*)realloc(d->pText,d->nText*sizeof(XMLSTR));
+    if (d->pClear)     d->pClear=(XMLClear *)realloc(d->pClear,d->nClear*sizeof(XMLClear));
+}
+
+char XMLNode::maybeAddTxT(void *pa, XMLCSTR tokenPStr)
+{
+    XML *pXML=(XML *)pa;
+    XMLCSTR lpszText=pXML->lpszText;
+    if (!lpszText) return 0;
+    if (dropWhiteSpace) while (XML_isSPACECHAR(*lpszText)&&(lpszText!=tokenPStr)) lpszText++;
+    int cbText = (int)(tokenPStr - lpszText);
+    if (!cbText) { pXML->lpszText=NULL; return 0; }
+    if (dropWhiteSpace) { cbText--; while ((cbText)&&XML_isSPACECHAR(lpszText[cbText])) cbText--; cbText++; }
+    if (!cbText) { pXML->lpszText=NULL; return 0; }
+    XMLSTR lpt=fromXMLString(lpszText,cbText,pXML);
+    if (!lpt) return 1;
+    pXML->lpszText=NULL;
+    if (removeCommentsInMiddleOfText && d->nText && d->nClear)
+    {
+        // if the previous insertion was a comment (<!-- -->) AND
+        // if the previous previous insertion was a text then, delete the comment and append the text
+        int n=d->nChild+d->nText+d->nClear-1,*o=d->pOrder;
+        if (((o[n]&3)==eNodeClear)&&((o[n-1]&3)==eNodeText))
+        {
+            int i=o[n]>>2;
+            if (d->pClear[i].lpszOpenTag==XMLClearTags[2].lpszOpen)
+            {
+                deleteClear(i);
+                i=o[n-1]>>2;
+                n=xstrlen(d->pText[i]);
+                int n2=xstrlen(lpt)+1;
+                d->pText[i]=(XMLSTR)realloc((void*)d->pText[i],(n+n2)*sizeof(XMLCHAR));
+                if (!d->pText[i]) return 1;
+                memcpy((void*)(d->pText[i]+n),lpt,n2*sizeof(XMLCHAR));
+                free(lpt);
+                return 0;
+            }
+        }
+    }
+    addText_priv(MEMORYINCREASE,lpt,-1);
+    return 0;
+}
+// private:
+// Recursively parse an XML element.
+int XMLNode::ParseXMLElement(void *pa)
+{
+    XML *pXML=(XML *)pa;
+    int cbToken;
+    enum XMLTokenTypeTag xtype;
+    NextToken token;
+    XMLCSTR lpszTemp=NULL;
+    int cbTemp=0;
+    char nDeclaration;
+    XMLNode pNew;
+    enum Status status; // inside or outside a tag
+    enum Attrib attrib = eAttribName;
+
+    assert(pXML);
+
+    // If this is the first call to the function
+    if (pXML->nFirst)
+    {
+        // Assume we are outside of a tag definition
+        pXML->nFirst = FALSE;
+        status = eOutsideTag;
+    } else
+    {
+        // If this is not the first call then we should only be called when inside a tag.
+        status = eInsideTag;
+    }
+
+    // Iterate through the tokens in the document
+    for(;;)
+    {
+        // Obtain the next token
+        token = GetNextToken(pXML, &cbToken, &xtype);
+
+        if (xtype != eTokenError)
+        {
+            // Check the current status
+            switch(status)
+            {
+
+            // If we are outside of a tag definition
+            case eOutsideTag:
+
+                // Check what type of token we obtained
+                switch(xtype)
+                {
+                // If we have found text or quoted text
+                case eTokenText:
+                case eTokenCloseTag:          /* '>'         */
+                case eTokenShortHandClose:    /* '/>'        */
+                case eTokenQuotedText:
+                case eTokenEquals:
+                    break;
+
+                // If we found a start tag '<' and declarations '<?'
+                case eTokenTagStart:
+                case eTokenDeclaration:
+
+                    // Cache whether this new element is a declaration or not
+                    nDeclaration = (xtype == eTokenDeclaration);
+
+                    // If we have node text then add this to the element
+                    if (maybeAddTxT(pXML,token.pStr)) return FALSE;
+
+                    // Find the name of the tag
+                    token = GetNextToken(pXML, &cbToken, &xtype);
+
+                    // Return an error if we couldn't obtain the next token or
+                    // it wasnt text
+                    if (xtype != eTokenText)
+                    {
+                        pXML->error = eXMLErrorMissingTagName;
+                        return FALSE;
+                    }
+
+                    // If we found a new element which is the same as this
+                    // element then we need to pass this back to the caller..
+
+#ifdef APPROXIMATE_PARSING
+                    if (d->lpszName &&
+                        myTagCompare(d->lpszName, token.pStr) == 0)
+                    {
+                        // Indicate to the caller that it needs to create a
+                        // new element.
+                        pXML->lpNewElement = token.pStr;
+                        pXML->cbNewElement = cbToken;
+                        return TRUE;
+                    } else
+#endif
+                    {
+                        // If the name of the new element differs from the name of
+                        // the current element we need to add the new element to
+                        // the current one and recurse
+                        pNew = addChild_priv(MEMORYINCREASE,stringDup(token.pStr,cbToken), nDeclaration,-1);
+
+                        while (!pNew.isEmpty())
+                        {
+                            // Callself to process the new node.  If we return
+                            // FALSE this means we dont have any more
+                            // processing to do...
+
+                            if (!pNew.ParseXMLElement(pXML)) return FALSE;
+                            else
+                            {
+                                // If the call to recurse this function
+                                // evented in a end tag specified in XML then
+                                // we need to unwind the calls to this
+                                // function until we find the appropriate node
+                                // (the element name and end tag name must
+                                // match)
+                                if (pXML->cbEndTag)
+                                {
+                                    // If we are back at the root node then we
+                                    // have an unmatched end tag
+                                    if (!d->lpszName)
+                                    {
+                                        pXML->error=eXMLErrorUnmatchedEndTag;
+                                        return FALSE;
+                                    }
+
+                                    // If the end tag matches the name of this
+                                    // element then we only need to unwind
+                                    // once more...
+
+                                    if (myTagCompare(d->lpszName, pXML->lpEndTag)==0)
+                                    {
+                                        pXML->cbEndTag = 0;
+                                    }
+
+                                    return TRUE;
+                                } else
+                                    if (pXML->cbNewElement)
+                                    {
+                                        // If the call indicated a new element is to
+                                        // be created on THIS element.
+
+                                        // If the name of this element matches the
+                                        // name of the element we need to create
+                                        // then we need to return to the caller
+                                        // and let it process the element.
+
+                                        if (myTagCompare(d->lpszName, pXML->lpNewElement)==0)
+                                        {
+                                            return TRUE;
+                                        }
+
+                                        // Add the new element and recurse
+                                        pNew = addChild_priv(MEMORYINCREASE,stringDup(pXML->lpNewElement,pXML->cbNewElement),0,-1);
+                                        pXML->cbNewElement = 0;
+                                    }
+                                    else
+                                    {
+                                        // If we didn't have a new element to create
+                                        pNew = emptyXMLNode;
+
+                                    }
+                            }
+                        }
+                    }
+                    break;
+
+                // If we found an end tag
+                case eTokenTagEnd:
+
+                    // If we have node text then add this to the element
+                    if (maybeAddTxT(pXML,token.pStr)) return FALSE;
+
+                    // Find the name of the end tag
+                    token = GetNextToken(pXML, &cbTemp, &xtype);
+
+                    // The end tag should be text
+                    if (xtype != eTokenText)
+                    {
+                        pXML->error = eXMLErrorMissingEndTagName;
+                        return FALSE;
+                    }
+                    lpszTemp = token.pStr;
+
+                    // After the end tag we should find a closing tag
+                    token = GetNextToken(pXML, &cbToken, &xtype);
+                    if (xtype != eTokenCloseTag)
+                    {
+                        pXML->error = eXMLErrorMissingEndTagName;
+                        return FALSE;
+                    }
+                    pXML->lpszText=pXML->lpXML+pXML->nIndex;
+
+                    // We need to return to the previous caller.  If the name
+                    // of the tag cannot be found we need to keep returning to
+                    // caller until we find a match
+                    if (myTagCompare(d->lpszName, lpszTemp) != 0)
+#ifdef STRICT_PARSING
+                    {
+                        pXML->error=eXMLErrorUnmatchedEndTag;
+                        pXML->nIndexMissigEndTag=pXML->nIndex;
+                        return FALSE;
+                    }
+#else
+                    {
+                        pXML->error=eXMLErrorMissingEndTag;
+                        pXML->nIndexMissigEndTag=pXML->nIndex;
+                        pXML->lpEndTag = lpszTemp;
+                        pXML->cbEndTag = cbTemp;
+                    }
+#endif
+
+                    // Return to the caller
+                    exactMemory(d);
+                    return TRUE;
+
+                // If we found a clear (unformatted) token
+                case eTokenClear:
+                    // If we have node text then add this to the element
+                    if (maybeAddTxT(pXML,token.pStr)) return FALSE;
+                    if (parseClearTag(pXML, token.pClr)) return FALSE;
+                    pXML->lpszText=pXML->lpXML+pXML->nIndex;
+                    break;
+
+                default:
+                    break;
+                }
+                break;
+
+            // If we are inside a tag definition we need to search for attributes
+            case eInsideTag:
+
+                // Check what part of the attribute (name, equals, value) we
+                // are looking for.
+                switch(attrib)
+                {
+                // If we are looking for a new attribute
+                case eAttribName:
+
+                    // Check what the current token type is
+                    switch(xtype)
+                    {
+                    // If the current type is text...
+                    // Eg.  'attribute'
+                    case eTokenText:
+                        // Cache the token then indicate that we are next to
+                        // look for the equals
+                        lpszTemp = token.pStr;
+                        cbTemp = cbToken;
+                        attrib = eAttribEquals;
+                        break;
+
+                    // If we found a closing tag...
+                    // Eg.  '>'
+                    case eTokenCloseTag:
+                        // We are now outside the tag
+                        status = eOutsideTag;
+                        pXML->lpszText=pXML->lpXML+pXML->nIndex;
+                        break;
+
+                    // If we found a short hand '/>' closing tag then we can
+                    // return to the caller
+                    case eTokenShortHandClose:
+                        exactMemory(d);
+                        pXML->lpszText=pXML->lpXML+pXML->nIndex;
+                        return TRUE;
+
+                    // Errors...
+                    case eTokenQuotedText:    /* '"SomeText"'   */
+                    case eTokenTagStart:      /* '<'            */
+                    case eTokenTagEnd:        /* '</'           */
+                    case eTokenEquals:        /* '='            */
+                    case eTokenDeclaration:   /* '<?'           */
+                    case eTokenClear:
+                        pXML->error = eXMLErrorUnexpectedToken;
+                        return FALSE;
+                    default: break;
+                    }
+                    break;
+
+                // If we are looking for an equals
+                case eAttribEquals:
+                    // Check what the current token type is
+                    switch(xtype)
+                    {
+                    // If the current type is text...
+                    // Eg.  'Attribute AnotherAttribute'
+                    case eTokenText:
+                        // Add the unvalued attribute to the list
+                        addAttribute_priv(MEMORYINCREASE,stringDup(lpszTemp,cbTemp), NULL);
+                        // Cache the token then indicate.  We are next to
+                        // look for the equals attribute
+                        lpszTemp = token.pStr;
+                        cbTemp = cbToken;
+                        break;
+
+                    // If we found a closing tag 'Attribute >' or a short hand
+                    // closing tag 'Attribute />'
+                    case eTokenShortHandClose:
+                    case eTokenCloseTag:
+                        // If we are a declaration element '<?' then we need
+                        // to remove extra closing '?' if it exists
+                        pXML->lpszText=pXML->lpXML+pXML->nIndex;
+
+                        if (d->isDeclaration &&
+                            (lpszTemp[cbTemp-1]) == _CXML('?'))
+                        {
+                            cbTemp--;
+                            if (d->pParent && d->pParent->pParent) xtype = eTokenShortHandClose;
+                        }
+
+                        if (cbTemp)
+                        {
+                            // Add the unvalued attribute to the list
+                            addAttribute_priv(MEMORYINCREASE,stringDup(lpszTemp,cbTemp), NULL);
+                        }
+
+                        // If this is the end of the tag then return to the caller
+                        if (xtype == eTokenShortHandClose)
+                        {
+                            exactMemory(d);
+                            return TRUE;
+                        }
+
+                        // We are now outside the tag
+                        status = eOutsideTag;
+                        break;
+
+                    // If we found the equals token...
+                    // Eg.  'Attribute ='
+                    case eTokenEquals:
+                        // Indicate that we next need to search for the value
+                        // for the attribute
+                        attrib = eAttribValue;
+                        break;
+
+                    // Errors...
+                    case eTokenQuotedText:    /* 'Attribute "InvalidAttr"'*/
+                    case eTokenTagStart:      /* 'Attribute <'            */
+                    case eTokenTagEnd:        /* 'Attribute </'           */
+                    case eTokenDeclaration:   /* 'Attribute <?'           */
+                    case eTokenClear:
+                        pXML->error = eXMLErrorUnexpectedToken;
+                        return FALSE;
+                    default: break;
+                    }
+                    break;
+
+                // If we are looking for an attribute value
+                case eAttribValue:
+                    // Check what the current token type is
+                    switch(xtype)
+                    {
+                    // If the current type is text or quoted text...
+                    // Eg.  'Attribute = "Value"' or 'Attribute = Value' or
+                    // 'Attribute = 'Value''.
+                    case eTokenText:
+                    case eTokenQuotedText:
+                        // If we are a declaration element '<?' then we need
+                        // to remove extra closing '?' if it exists
+                        if (d->isDeclaration &&
+                            (token.pStr[cbToken-1]) == _CXML('?'))
+                        {
+                            cbToken--;
+                        }
+
+                        if (cbTemp)
+                        {
+                            // Add the valued attribute to the list
+                            if (xtype==eTokenQuotedText) { token.pStr++; cbToken-=2; }
+                            XMLSTR attrVal=(XMLSTR)token.pStr;
+                            if (attrVal)
+                            {
+                                attrVal=fromXMLString(attrVal,cbToken,pXML);
+                                if (!attrVal) return FALSE;
+                            }
+                            addAttribute_priv(MEMORYINCREASE,stringDup(lpszTemp,cbTemp),attrVal);
+                        }
+
+                        // Indicate we are searching for a new attribute
+                        attrib = eAttribName;
+                        break;
+
+                    // Errors...
+                    case eTokenTagStart:        /* 'Attr = <'          */
+                    case eTokenTagEnd:          /* 'Attr = </'         */
+                    case eTokenCloseTag:        /* 'Attr = >'          */
+                    case eTokenShortHandClose:  /* "Attr = />"         */
+                    case eTokenEquals:          /* 'Attr = ='          */
+                    case eTokenDeclaration:     /* 'Attr = <?'         */
+                    case eTokenClear:
+                        pXML->error = eXMLErrorUnexpectedToken;
+                        return FALSE;
+                        break;
+                    default: break;
+                    }
+                }
+            }
+        }
+        // If we failed to obtain the next token
+        else
+        {
+            if ((!d->isDeclaration)&&(d->pParent))
+            {
+#ifdef STRICT_PARSING
+                pXML->error=eXMLErrorUnmatchedEndTag;
+#else
+                pXML->error=eXMLErrorMissingEndTag;
+#endif
+                pXML->nIndexMissigEndTag=pXML->nIndex;
+            }
+            maybeAddTxT(pXML,pXML->lpXML+pXML->nIndex);
+            return FALSE;
+        }
+    }
+}
+
+// Count the number of lines and columns in an XML string.
+static void CountLinesAndColumns(XMLCSTR lpXML, int nUpto, XMLResults *pResults)
+{
+    XMLCHAR ch;
+    assert(lpXML);
+    assert(pResults);
+
+    struct XML xml={ lpXML,lpXML, 0, 0, eXMLErrorNone, NULL, 0, NULL, 0, TRUE };
+
+    pResults->nLine = 1;
+    pResults->nColumn = 1;
+    while (xml.nIndex<nUpto)
+    {
+        ch = getNextChar(&xml);
+        if (ch != _CXML('\n')) pResults->nColumn++;
+        else
+        {
+            pResults->nLine++;
+            pResults->nColumn=1;
+        }
+    }
+}
+
+// Parse XML and return the root element.
+XMLNode XMLNode::parseString(XMLCSTR lpszXML, XMLCSTR tag, XMLResults *pResults)
+{
+    if (!lpszXML)
+    {
+        if (pResults)
+        {
+            pResults->error=eXMLErrorNoElements;
+            pResults->nLine=0;
+            pResults->nColumn=0;
+        }
+        return emptyXMLNode;
+    }
+
+    XMLNode xnode(NULL,NULL,FALSE);
+    struct XML xml={ lpszXML, lpszXML, 0, 0, eXMLErrorNone, NULL, 0, NULL, 0, TRUE };
+
+    // Create header element
+    xnode.ParseXMLElement(&xml);
+    enum XMLError error = xml.error;
+    if (!xnode.nChildNode()) error=eXMLErrorNoXMLTagFound;
+    if ((xnode.nChildNode()==1)&&(xnode.nElement()==1)) xnode=xnode.getChildNode(); // skip the empty node
+
+    // If no error occurred
+    if ((error==eXMLErrorNone)||(error==eXMLErrorMissingEndTag)||(error==eXMLErrorNoXMLTagFound))
+    {
+        XMLCSTR name=xnode.getName();
+        if (tag&&(*tag)&&((!name)||(xstricmp(name,tag))))
+        {
+            xnode=xnode.getChildNode(tag);
+            if (xnode.isEmpty())
+            {
+                if (pResults)
+                {
+                    pResults->error=eXMLErrorFirstTagNotFound;
+                    pResults->nLine=0;
+                    pResults->nColumn=0;
+                }
+                return emptyXMLNode;
+            }
+        }
+    } else
+    {
+        // Cleanup: this will destroy all the nodes
+        xnode = emptyXMLNode;
+    }
+
+
+    // If we have been given somewhere to place results
+    if (pResults)
+    {
+        pResults->error = error;
+
+        // If we have an error
+        if (error!=eXMLErrorNone)
+        {
+            if (error==eXMLErrorMissingEndTag) xml.nIndex=xml.nIndexMissigEndTag;
+            // Find which line and column it starts on.
+            CountLinesAndColumns(xml.lpXML, xml.nIndex, pResults);
+        }
+    }
+    return xnode;
+}
+
+XMLNode XMLNode::parseFile(XMLCSTR filename, XMLCSTR tag, XMLResults *pResults)
+{
+	if (pResults)
+	{
+		pResults->nLine=0;
+		pResults->nColumn=0;
+	}
+
+	FileDesc * file = FileMgr::getSystemFileMgr()->open(filename, FileMgr::RDONLY);
+
+    if (file->getFd() <= 0)
+	{
+		if (pResults) pResults->error=eXMLErrorFileNotFound;
+		return emptyXMLNode;
+	}
+
+    int l = file->seek(0, SEEK_END),headerSz = 0;
+
+    if (!l)
+	{
+		if (pResults) pResults->error=eXMLErrorEmpty;
+		FileMgr::getSystemFileMgr()->close(file);
+		return emptyXMLNode;
+	}
+
+	file->seek(0, SEEK_SET);
+    
+	unsigned char * buf = (unsigned char*)malloc(l+4);
+    
+	l = file->read(buf,l);
+
+    FileMgr::getSystemFileMgr()->close(file);
+    
+	buf[l]=0; buf[l+1]=0; buf[l+2]=0; buf[l+3]=0;
+
+#ifdef _XMLWIDECHAR
+    if (guessWideCharChars)
+    {
+        if (!myIsTextWideChar(buf,l))
+        {
+            XMLNode::XMLCharEncoding ce=XMLNode::char_encoding_legacy;
+            if ((buf[0]==0xef)&&(buf[1]==0xbb)&&(buf[2]==0xbf)) { headerSz=3; ce=XMLNode::char_encoding_UTF8; }
+            XMLSTR b2=myMultiByteToWideChar((const char*)(buf+headerSz),ce);
+            free(buf); buf=(unsigned char*)b2; headerSz=0;
+        } else
+        {
+            if ((buf[0]==0xef)&&(buf[1]==0xff)) headerSz=2;
+            if ((buf[0]==0xff)&&(buf[1]==0xfe)) headerSz=2;
+        }
+    }
+#else
+    if (guessWideCharChars)
+    {
+        if (myIsTextWideChar(buf,l))
+        {
+            if ((buf[0]==0xef)&&(buf[1]==0xff)) headerSz=2;
+            if ((buf[0]==0xff)&&(buf[1]==0xfe)) headerSz=2;
+            char *b2=myWideCharToMultiByte((const wchar_t*)(buf+headerSz));
+            free(buf); buf=(unsigned char*)b2; headerSz=0;
+        } else
+        {
+            if ((buf[0]==0xef)&&(buf[1]==0xbb)&&(buf[2]==0xbf)) headerSz=3;
+        }
+    }
+#endif
+
+    if (!buf) { if (pResults) pResults->error=eXMLErrorCharConversionError; return emptyXMLNode; }
+    XMLNode x = parseString((XMLSTR)(buf+headerSz),tag,pResults);
+    free(buf);
+    return x;
+}
+
+static inline void charmemset(XMLSTR dest,XMLCHAR c,int l) { while (l--) *(dest++)=c; }
+// private:
+// Creates an user friendly XML string from a given element with
+// appropriate white space and carriage returns.
+//
+// This recurses through all subnodes then adds contents of the nodes to the
+// string.
+int XMLNode::CreateXMLStringR(XMLNodeData *pEntry, XMLSTR lpszMarker, int nFormat)
+{
+    int nResult = 0;
+    int cb=nFormat<0?0:nFormat;
+    int cbElement;
+    int nChildFormat=-1;
+    int nElementI=pEntry->nChild+pEntry->nText+pEntry->nClear;
+    int i,j;
+    if ((nFormat>=0)&&(nElementI==1)&&(pEntry->nText==1)&&(!pEntry->isDeclaration)) nFormat=-2;
+
+    assert(pEntry);
+
+#define LENSTR(lpsz) (lpsz ? xstrlen(lpsz) : 0)
+
+    // If the element has no name then assume this is the head node.
+    cbElement = (int)LENSTR(pEntry->lpszName);
+
+    if (cbElement)
+    {
+        // "<elementname "
+        if (lpszMarker)
+        {
+            if (cb) charmemset(lpszMarker, INDENTCHAR, cb);
+            nResult = cb;
+            lpszMarker[nResult++]=_CXML('<');
+            if (pEntry->isDeclaration) lpszMarker[nResult++]=_CXML('?');
+            xstrcpy(&lpszMarker[nResult], pEntry->lpszName);
+            nResult+=cbElement;
+            lpszMarker[nResult++]=_CXML(' ');
+
+        } else
+        {
+            nResult+=cbElement+2+cb;
+            if (pEntry->isDeclaration) nResult++;
+        }
+
+        // Enumerate attributes and add them to the string
+        XMLAttribute *pAttr=pEntry->pAttribute;
+        for (i=0; i<pEntry->nAttribute; i++)
+        {
+            // "Attrib
+            cb = (int)LENSTR(pAttr->lpszName);
+            if (cb)
+            {
+                if (lpszMarker) xstrcpy(&lpszMarker[nResult], pAttr->lpszName);
+                nResult += cb;
+                // "Attrib=Value "
+                if (pAttr->lpszValue)
+                {
+                    cb=(int)ToXMLStringTool::lengthXMLString(pAttr->lpszValue);
+                    if (lpszMarker)
+                    {
+                        lpszMarker[nResult]=_CXML('=');
+                        lpszMarker[nResult+1]=_CXML('"');
+                        if (cb) ToXMLStringTool::toXMLUnSafe(&lpszMarker[nResult+2],pAttr->lpszValue);
+                        lpszMarker[nResult+cb+2]=_CXML('"');
+                    }
+                    nResult+=cb+3;
+                }
+                if (lpszMarker) lpszMarker[nResult] = _CXML(' ');
+                nResult++;
+            }
+            pAttr++;
+        }
+
+        if (pEntry->isDeclaration)
+        {
+            if (lpszMarker)
+            {
+                lpszMarker[nResult-1]=_CXML('?');
+                lpszMarker[nResult]=_CXML('>');
+            }
+            nResult++;
+            if (nFormat!=-1)
+            {
+                if (lpszMarker) lpszMarker[nResult]=_CXML('\n');
+                nResult++;
+            }
+        } else
+            // If there are child nodes we need to terminate the start tag
+            if (nElementI)
+            {
+                if (lpszMarker) lpszMarker[nResult-1]=_CXML('>');
+                if (nFormat>=0)
+                {
+                    if (lpszMarker) lpszMarker[nResult]=_CXML('\n');
+                    nResult++;
+                }
+            } else nResult--;
+    }
+
+    // Calculate the child format for when we recurse.  This is used to
+    // determine the number of spaces used for prefixes.
+    if (nFormat!=-1)
+    {
+        if (cbElement&&(!pEntry->isDeclaration)) nChildFormat=nFormat+1;
+        else nChildFormat=nFormat;
+    }
+
+    // Enumerate through remaining children
+    for (i=0; i<nElementI; i++)
+    {
+        j=pEntry->pOrder[i];
+        switch((XMLElementType)(j&3))
+        {
+        // Text nodes
+        case eNodeText:
+            {
+                // "Text"
+                XMLCSTR pChild=pEntry->pText[j>>2];
+                cb = (int)ToXMLStringTool::lengthXMLString(pChild);
+                if (cb)
+                {
+                    if (nFormat>=0)
+                    {
+                        if (lpszMarker)
+                        {
+                            charmemset(&lpszMarker[nResult],INDENTCHAR,nFormat+1);
+                            ToXMLStringTool::toXMLUnSafe(&lpszMarker[nResult+nFormat+1],pChild);
+                            lpszMarker[nResult+nFormat+1+cb]=_CXML('\n');
+                        }
+                        nResult+=cb+nFormat+2;
+                    } else
+                    {
+                        if (lpszMarker) ToXMLStringTool::toXMLUnSafe(&lpszMarker[nResult], pChild);
+                        nResult += cb;
+                    }
+                }
+                break;
+            }
+
+        // Clear type nodes
+        case eNodeClear:
+            {
+                XMLClear *pChild=pEntry->pClear+(j>>2);
+                // "OpenTag"
+                cb = (int)LENSTR(pChild->lpszOpenTag);
+                if (cb)
+                {
+                    if (nFormat!=-1)
+                    {
+                        if (lpszMarker)
+                        {
+                            charmemset(&lpszMarker[nResult], INDENTCHAR, nFormat+1);
+                            xstrcpy(&lpszMarker[nResult+nFormat+1], pChild->lpszOpenTag);
+                        }
+                        nResult+=cb+nFormat+1;
+                    }
+                    else
+                    {
+                        if (lpszMarker)xstrcpy(&lpszMarker[nResult], pChild->lpszOpenTag);
+                        nResult += cb;
+                    }
+                }
+
+                // "OpenTag Value"
+                cb = (int)LENSTR(pChild->lpszValue);
+                if (cb)
+                {
+                    if (lpszMarker) xstrcpy(&lpszMarker[nResult], pChild->lpszValue);
+                    nResult += cb;
+                }
+
+                // "OpenTag Value CloseTag"
+                cb = (int)LENSTR(pChild->lpszCloseTag);
+                if (cb)
+                {
+                    if (lpszMarker) xstrcpy(&lpszMarker[nResult], pChild->lpszCloseTag);
+                    nResult += cb;
+                }
+
+                if (nFormat!=-1)
+                {
+                    if (lpszMarker) lpszMarker[nResult] = _CXML('\n');
+                    nResult++;
+                }
+                break;
+            }
+
+        // Element nodes
+        case eNodeChild:
+            {
+                // Recursively add child nodes
+                nResult += CreateXMLStringR(pEntry->pChild[j>>2].d, lpszMarker ? lpszMarker + nResult : 0, nChildFormat);
+                break;
+            }
+        default: break;
+        }
+    }
+
+    if ((cbElement)&&(!pEntry->isDeclaration))
+    {
+        // If we have child entries we need to use long XML notation for
+        // closing the element - "<elementname>blah blah blah</elementname>"
+        if (nElementI)
+        {
+            // "</elementname>\0"
+            if (lpszMarker)
+            {
+                if (nFormat >=0)
+                {
+                    charmemset(&lpszMarker[nResult], INDENTCHAR,nFormat);
+                    nResult+=nFormat;
+                }
+
+                lpszMarker[nResult]=_CXML('<'); lpszMarker[nResult+1]=_CXML('/');
+                nResult += 2;
+                xstrcpy(&lpszMarker[nResult], pEntry->lpszName);
+                nResult += cbElement;
+
+                lpszMarker[nResult]=_CXML('>');
+                if (nFormat == -1) nResult++;
+                else
+                {
+                    lpszMarker[nResult+1]=_CXML('\n');
+                    nResult+=2;
+                }
+            } else
+            {
+                if (nFormat>=0) nResult+=cbElement+4+nFormat;
+                else if (nFormat==-1) nResult+=cbElement+3;
+                else nResult+=cbElement+4;
+            }
+        } else
+        {
+            // If there are no children we can use shorthand XML notation -
+            // "<elementname/>"
+            // "/>\0"
+            if (lpszMarker)
+            {
+                lpszMarker[nResult]=_CXML('/'); lpszMarker[nResult+1]=_CXML('>');
+                if (nFormat != -1) lpszMarker[nResult+2]=_CXML('\n');
+            }
+            nResult += nFormat == -1 ? 2 : 3;
+        }
+    }
+
+    return nResult;
+}
+
+#undef LENSTR
+
+// Create an XML string
+// @param       int nFormat             - 0 if no formatting is required
+//                                        otherwise nonzero for formatted text
+//                                        with carriage returns and indentation.
+// @param       int *pnSize             - [out] pointer to the size of the
+//                                        returned string not including the
+//                                        NULL terminator.
+// @return      XMLSTR                  - Allocated XML string, you must free
+//                                        this with free().
+XMLSTR XMLNode::createXMLString(int nFormat, int *pnSize) const
+{
+    if (!d) { if (pnSize) *pnSize=0; return NULL; }
+
+    XMLSTR lpszResult = NULL;
+    int cbStr;
+
+    // Recursively Calculate the size of the XML string
+    if (!dropWhiteSpace) nFormat=0;
+    nFormat = nFormat ? 0 : -1;
+    cbStr = CreateXMLStringR(d, 0, nFormat);
+    // Alllocate memory for the XML string + the NULL terminator and
+    // create the recursively XML string.
+    lpszResult=(XMLSTR)malloc((cbStr+1)*sizeof(XMLCHAR));
+    CreateXMLStringR(d, lpszResult, nFormat);
+    lpszResult[cbStr]=_CXML('\0');
+    if (pnSize) *pnSize = cbStr;
+    return lpszResult;
+}
+
+int XMLNode::detachFromParent(XMLNodeData *d)
+{
+    XMLNode *pa=d->pParent->pChild;
+    int i=0;
+    while (((void*)(pa[i].d))!=((void*)d)) i++;
+    d->pParent->nChild--;
+    if (d->pParent->nChild) memmove(pa+i,pa+i+1,(d->pParent->nChild-i)*sizeof(XMLNode));
+    else { free(pa); d->pParent->pChild=NULL; }
+    return removeOrderElement(d->pParent,eNodeChild,i);
+}
+
+XMLNode::~XMLNode()
+{
+    if (!d) return;
+    d->ref_count--;
+    emptyTheNode(0);
+}
+void XMLNode::deleteNodeContent()
+{
+    if (!d) return;
+    if (d->pParent) { detachFromParent(d); d->pParent=NULL; d->ref_count--; }
+    emptyTheNode(1);
+}
+void XMLNode::emptyTheNode(char force)
+{
+    XMLNodeData *dd=d; // warning: must stay this way!
+    if ((dd->ref_count==0)||force)
+    {
+        if (d->pParent) detachFromParent(d);
+        int i;
+        XMLNode *pc;
+        for(i=0; i<dd->nChild; i++)
+        {
+            pc=dd->pChild+i;
+            pc->d->pParent=NULL;
+            pc->d->ref_count--;
+            pc->emptyTheNode(force);
+        }
+        myFree(dd->pChild);
+        for(i=0; i<dd->nText; i++) free((void*)dd->pText[i]);
+        myFree(dd->pText);
+        for(i=0; i<dd->nClear; i++) free((void*)dd->pClear[i].lpszValue);
+        myFree(dd->pClear);
+        for(i=0; i<dd->nAttribute; i++)
+        {
+            free((void*)dd->pAttribute[i].lpszName);
+            if (dd->pAttribute[i].lpszValue) free((void*)dd->pAttribute[i].lpszValue);
+        }
+        myFree(dd->pAttribute);
+        myFree(dd->pOrder);
+        myFree((void*)dd->lpszName);
+        dd->nChild=0;    dd->nText=0;    dd->nClear=0;    dd->nAttribute=0;
+        dd->pChild=NULL; dd->pText=NULL; dd->pClear=NULL; dd->pAttribute=NULL;
+        dd->pOrder=NULL; dd->lpszName=NULL; dd->pParent=NULL;
+    }
+    if (dd->ref_count==0)
+    {
+        free(dd);
+        d=NULL;
+    }
+}
+
+XMLNode& XMLNode::operator=( const XMLNode& A )
+{
+    // shallow copy
+    if (this != &A)
+    {
+        if (d) { d->ref_count--; emptyTheNode(0); }
+        d=A.d;
+        if (d) (d->ref_count) ++ ;
+    }
+    return *this;
+}
+
+XMLNode::XMLNode(const XMLNode &A)
+{
+    // shallow copy
+    d=A.d;
+    if (d) (d->ref_count)++ ;
+}
+
+XMLNode XMLNode::deepCopy() const
+{
+    if (!d) return XMLNode::emptyXMLNode;
+    XMLNode x(NULL,stringDup(d->lpszName),d->isDeclaration);
+    XMLNodeData *p=x.d;
+    int n=d->nAttribute;
+    if (n)
+    {
+        p->nAttribute=n; p->pAttribute=(XMLAttribute*)malloc(n*sizeof(XMLAttribute));
+        while (n--)
+        {
+            p->pAttribute[n].lpszName=stringDup(d->pAttribute[n].lpszName);
+            p->pAttribute[n].lpszValue=stringDup(d->pAttribute[n].lpszValue);
+        }
+    }
+    if (d->pOrder)
+    {
+        n=(d->nChild+d->nText+d->nClear)*sizeof(int); p->pOrder=(int*)malloc(n); memcpy(p->pOrder,d->pOrder,n);
+    }
+    n=d->nText;
+    if (n)
+    {
+        p->nText=n; p->pText=(XMLCSTR*)malloc(n*sizeof(XMLCSTR));
+        while(n--) p->pText[n]=stringDup(d->pText[n]);
+    }
+    n=d->nClear;
+    if (n)
+    {
+        p->nClear=n; p->pClear=(XMLClear*)malloc(n*sizeof(XMLClear));
+        while (n--)
+        {
+            p->pClear[n].lpszCloseTag=d->pClear[n].lpszCloseTag;
+            p->pClear[n].lpszOpenTag=d->pClear[n].lpszOpenTag;
+            p->pClear[n].lpszValue=stringDup(d->pClear[n].lpszValue);
+        }
+    }
+    n=d->nChild;
+    if (n)
+    {
+        p->nChild=n; p->pChild=(XMLNode*)malloc(n*sizeof(XMLNode));
+        while (n--)
+        {
+            p->pChild[n].d=NULL;
+            p->pChild[n]=d->pChild[n].deepCopy();
+            p->pChild[n].d->pParent=p;
+        }
+    }
+    return x;
+}
+
+XMLNode XMLNode::addChild(XMLNode childNode, int pos)
+{
+    XMLNodeData *dc=childNode.d;
+    if ((!dc)||(!d)) return childNode;
+    if (!dc->lpszName)
+    {
+        // this is a root node: todo: correct fix
+        int j=pos;
+        while (dc->nChild)
+        {
+            addChild(dc->pChild[0],j);
+            if (pos>=0) j++;
+        }
+        return childNode;
+    }
+    if (dc->pParent) { if ((detachFromParent(dc)<=pos)&&(dc->pParent==d)) pos--; } else dc->ref_count++;
+    dc->pParent=d;
+//     int nc=d->nChild;
+//     d->pChild=(XMLNode*)myRealloc(d->pChild,(nc+1),memoryIncrease,sizeof(XMLNode));
+    d->pChild=(XMLNode*)addToOrder(0,&pos,d->nChild,d->pChild,sizeof(XMLNode),eNodeChild);
+    d->pChild[pos].d=dc;
+    d->nChild++;
+    return childNode;
+}
+
+void XMLNode::deleteAttribute(int i)
+{
+    if ((!d)||(i<0)||(i>=d->nAttribute)) return;
+    d->nAttribute--;
+    XMLAttribute *p=d->pAttribute+i;
+    free((void*)p->lpszName);
+    if (p->lpszValue) free((void*)p->lpszValue);
+    if (d->nAttribute) memmove(p,p+1,(d->nAttribute-i)*sizeof(XMLAttribute)); else { free(p); d->pAttribute=NULL; }
+}
+
+void XMLNode::deleteAttribute(XMLAttribute *a){ if (a) deleteAttribute(a->lpszName); }
+void XMLNode::deleteAttribute(XMLCSTR lpszName)
+{
+    int j=0;
+    getAttribute(lpszName,&j);
+    if (j) deleteAttribute(j-1);
+}
+
+XMLAttribute *XMLNode::updateAttribute_WOSD(XMLSTR lpszNewValue, XMLSTR lpszNewName,int i)
+{
+    if (!d) { if (lpszNewValue) free(lpszNewValue); if (lpszNewName) free(lpszNewName); return NULL; }
+    if (i>=d->nAttribute)
+    {
+        if (lpszNewName) return addAttribute_WOSD(lpszNewName,lpszNewValue);
+        return NULL;
+    }
+    XMLAttribute *p=d->pAttribute+i;
+    if (p->lpszValue&&p->lpszValue!=lpszNewValue) free((void*)p->lpszValue);
+    p->lpszValue=lpszNewValue;
+    if (lpszNewName&&p->lpszName!=lpszNewName) { free((void*)p->lpszName); p->lpszName=lpszNewName; };
+    return p;
+}
+
+XMLAttribute *XMLNode::updateAttribute_WOSD(XMLAttribute *newAttribute, XMLAttribute *oldAttribute)
+{
+    if (oldAttribute) return updateAttribute_WOSD((XMLSTR)newAttribute->lpszValue,(XMLSTR)newAttribute->lpszName,oldAttribute->lpszName);
+    return addAttribute_WOSD((XMLSTR)newAttribute->lpszName,(XMLSTR)newAttribute->lpszValue);
+}
+
+XMLAttribute *XMLNode::updateAttribute_WOSD(XMLSTR lpszNewValue, XMLSTR lpszNewName,XMLCSTR lpszOldName)
+{
+    int j=0;
+    getAttribute(lpszOldName,&j);
+    if (j) return updateAttribute_WOSD(lpszNewValue,lpszNewName,j-1);
+    else
+    {
+        if (lpszNewName) return addAttribute_WOSD(lpszNewName,lpszNewValue);
+        else             return addAttribute_WOSD(stringDup(lpszOldName),lpszNewValue);
+    }
+}
+
+int XMLNode::indexText(XMLCSTR lpszValue) const
+{
+    if (!d) return -1;
+    int i,l=d->nText;
+    if (!lpszValue) { if (l) return 0; return -1; }
+    XMLCSTR *p=d->pText;
+    for (i=0; i<l; i++) if (lpszValue==p[i]) return i;
+    return -1;
+}
+
+void XMLNode::deleteText(int i)
+{
+    if ((!d)||(i<0)||(i>=d->nText)) return;
+    d->nText--;
+    XMLCSTR *p=d->pText+i;
+    free((void*)*p);
+    if (d->nText) memmove(p,p+1,(d->nText-i)*sizeof(XMLCSTR)); else { free(p); d->pText=NULL; }
+    removeOrderElement(d,eNodeText,i);
+}
+
+void XMLNode::deleteText(XMLCSTR lpszValue) { deleteText(indexText(lpszValue)); }
+
+XMLCSTR XMLNode::updateText_WOSD(XMLSTR lpszNewValue, int i)
+{
+    if (!d) { if (lpszNewValue) free(lpszNewValue); return NULL; }
+    if (i>=d->nText) return addText_WOSD(lpszNewValue);
+    XMLCSTR *p=d->pText+i;
+    if (*p!=lpszNewValue) { free((void*)*p); *p=lpszNewValue; }
+    return lpszNewValue;
+}
+
+XMLCSTR XMLNode::updateText_WOSD(XMLSTR lpszNewValue, XMLCSTR lpszOldValue)
+{
+    if (!d) { if (lpszNewValue) free(lpszNewValue); return NULL; }
+    int i=indexText(lpszOldValue);
+    if (i>=0) return updateText_WOSD(lpszNewValue,i);
+    return addText_WOSD(lpszNewValue);
+}
+
+void XMLNode::deleteClear(int i)
+{
+    if ((!d)||(i<0)||(i>=d->nClear)) return;
+    d->nClear--;
+    XMLClear *p=d->pClear+i;
+    free((void*)p->lpszValue);
+    if (d->nClear) memmove(p,p+1,(d->nClear-i)*sizeof(XMLClear)); else { free(p); d->pClear=NULL; }
+    removeOrderElement(d,eNodeClear,i);
+}
+
+int XMLNode::indexClear(XMLCSTR lpszValue) const
+{
+    if (!d) return -1;
+    int i,l=d->nClear;
+    if (!lpszValue) { if (l) return 0; return -1; }
+    XMLClear *p=d->pClear;
+    for (i=0; i<l; i++) if (lpszValue==p[i].lpszValue) return i;
+    return -1;
+}
+
+void XMLNode::deleteClear(XMLCSTR lpszValue) { deleteClear(indexClear(lpszValue)); }
+void XMLNode::deleteClear(XMLClear *a) { if (a) deleteClear(a->lpszValue); }
+
+XMLClear *XMLNode::updateClear_WOSD(XMLSTR lpszNewContent, int i)
+{
+    if (!d) { if (lpszNewContent) free(lpszNewContent); return NULL; }
+    if (i>=d->nClear) return addClear_WOSD(lpszNewContent);
+    XMLClear *p=d->pClear+i;
+    if (lpszNewContent!=p->lpszValue) { free((void*)p->lpszValue); p->lpszValue=lpszNewContent; }
+    return p;
+}
+
+XMLClear *XMLNode::updateClear_WOSD(XMLSTR lpszNewContent, XMLCSTR lpszOldValue)
+{
+    if (!d) { if (lpszNewContent) free(lpszNewContent); return NULL; }
+    int i=indexClear(lpszOldValue);
+    if (i>=0) return updateClear_WOSD(lpszNewContent,i);
+    return addClear_WOSD(lpszNewContent);
+}
+
+XMLClear *XMLNode::updateClear_WOSD(XMLClear *newP,XMLClear *oldP)
+{
+    if (oldP) return updateClear_WOSD((XMLSTR)newP->lpszValue,(XMLSTR)oldP->lpszValue);
+    return NULL;
+}
+
+int XMLNode::nChildNode(XMLCSTR name) const
+{
+    if (!d) return 0;
+    int i,j=0,n=d->nChild;
+    XMLNode *pc=d->pChild;
+    for (i=0; i<n; i++)
+    {
+        if (xstricmp(pc->d->lpszName, name)==0) j++;
+        pc++;
+    }
+    return j;
+}
+
+XMLNode XMLNode::getChildNode(XMLCSTR name, int *j) const
+{
+    if (!d) return emptyXMLNode;
+    int i=0,n=d->nChild;
+    if (j) i=*j;
+    XMLNode *pc=d->pChild+i;
+    for (; i<n; i++)
+    {
+        if (!xstricmp(pc->d->lpszName, name))
+        {
+            if (j) *j=i+1;
+            return *pc;
+        }
+        pc++;
+    }
+    return emptyXMLNode;
+}
+
+XMLNode XMLNode::getChildNode(XMLCSTR name, int j) const
+{
+    if (!d) return emptyXMLNode;
+    if (j>=0)
+    {
+        int i=0;
+        while (j-->0) getChildNode(name,&i);
+        return getChildNode(name,&i);
+    }
+    int i=d->nChild;
+    while (i--) if (!xstricmp(name,d->pChild[i].d->lpszName)) break;
+    if (i<0) return emptyXMLNode;
+    return getChildNode(i);
+}
+
+XMLNode XMLNode::getChildNodeByPath (XMLCSTR _path, XMLCSTR createNode, XMLCHAR sep)
+{
+    XMLSTR path=stringDup(_path);
+    XMLNode x=getChildNodeByPathNonConst(path,createNode,sep);
+    if (path) free(path);
+    return x;
+}
+
+XMLNode XMLNode::getChildNodeByPathNonConst(XMLSTR path, XMLCSTR createNode, XMLCHAR sep)
+{
+    if ((!path)||(!(*path))) return *this;
+
+    XMLNode xn, xbase = *this;
+    XMLCHAR *tend1,sepString[2]; sepString[0]=sep; sepString[1]=0;
+    
+	tend1=xstrstr(path,sepString);
+
+    while(tend1)
+    {
+        *tend1=0;
+        xn=xbase.getChildNode(path);
+        if (xn.isEmpty())
+        {
+            if (createNode)
+			{
+				xn = xbase.addChild(path);
+			}
+            else
+			{
+				*tend1=sep;
+				return XMLNode::emptyXMLNode;
+			}
+        }
+        *tend1=sep;
+        xbase=xn;
+        path=tend1+1;
+        tend1=xstrstr(path,sepString);
+    }
+
+    xn = xbase.getChildNode(path);
+
+    if (xn.isEmpty() && createNode)
+	{
+		xn = xbase.addChild(path);
+		xn = parseString(createNode);
+	}
+
+    return xn;
+}
+
+XMLElementPosition XMLNode::positionOfText     (int i) const { if (i>=d->nText ) i=d->nText-1;  return findPosition(d,i,eNodeText ); }
+XMLElementPosition XMLNode::positionOfClear    (int i) const { if (i>=d->nClear) i=d->nClear-1; return findPosition(d,i,eNodeClear); }
+XMLElementPosition XMLNode::positionOfChildNode(int i) const { if (i>=d->nChild) i=d->nChild-1; return findPosition(d,i,eNodeChild); }
+XMLElementPosition XMLNode::positionOfText (XMLCSTR lpszValue) const { return positionOfText (indexText (lpszValue)); }
+XMLElementPosition XMLNode::positionOfClear(XMLCSTR lpszValue) const { return positionOfClear(indexClear(lpszValue)); }
+XMLElementPosition XMLNode::positionOfClear(XMLClear *a) const { if (a) return positionOfClear(a->lpszValue); return positionOfClear(); }
+XMLElementPosition XMLNode::positionOfChildNode(XMLNode x)  const
+{
+    if ((!d)||(!x.d)) return -1;
+    XMLNodeData *dd=x.d;
+    XMLNode *pc=d->pChild;
+    int i=d->nChild;
+    while (i--) if (pc[i].d==dd) return findPosition(d,i,eNodeChild);
+    return -1;
+}
+XMLElementPosition XMLNode::positionOfChildNode(XMLCSTR name, int count) const
+{
+    if (!name) return positionOfChildNode(count);
+    int j=0;
+    do { getChildNode(name,&j); if (j<0) return -1; } while (count--);
+    return findPosition(d,j-1,eNodeChild);
+}
+
+XMLNode XMLNode::getChildNodeWithAttribute(XMLCSTR name,XMLCSTR attributeName,XMLCSTR attributeValue, int *k) const
+{
+     int i=0,j;
+     if (k) i=*k;
+     XMLNode x;
+     XMLCSTR t;
+     do
+     {
+         x=getChildNode(name,&i);
+         if (!x.isEmpty())
+         {
+             if (attributeValue)
+             {
+                 j=0;
+                 do
+                 {
+                     t=x.getAttribute(attributeName,&j);
+                     if (t&&(xstricmp(attributeValue,t)==0)) { if (k) *k=i; return x; }
+                 } while (t);
+             } else
+             {
+                 if (x.isAttributeSet(attributeName)) { if (k) *k=i; return x; }
+             }
+         }
+     } while (!x.isEmpty());
+     return emptyXMLNode;
+}
+
+// Find an attribute on an node.
+XMLCSTR XMLNode::getAttribute(XMLCSTR lpszAttrib, int *j) const
+{
+    if (!d) return NULL;
+    int i=0,n=d->nAttribute;
+    if (j) i=*j;
+    XMLAttribute *pAttr=d->pAttribute+i;
+    for (; i<n; i++)
+    {
+        if (xstricmp(pAttr->lpszName, lpszAttrib)==0)
+        {
+            if (j) *j=i+1;
+            return pAttr->lpszValue;
+        }
+        pAttr++;
+    }
+    return NULL;
+}
+
+char XMLNode::isAttributeSet(XMLCSTR lpszAttrib) const
+{
+    if (!d) return FALSE;
+    int i,n=d->nAttribute;
+    XMLAttribute *pAttr=d->pAttribute;
+    for (i=0; i<n; i++)
+    {
+        if (xstricmp(pAttr->lpszName, lpszAttrib)==0)
+        {
+            return TRUE;
+        }
+        pAttr++;
+    }
+    return FALSE;
+}
+
+XMLCSTR XMLNode::getAttribute(XMLCSTR name, int j) const
+{
+    if (!d) return NULL;
+    int i=0;
+    while (j-->0) getAttribute(name,&i);
+    return getAttribute(name,&i);
+}
+
+XMLCSTR XMLNode::getAttribute(XMLCSTR name, XMLCSTR defaultValue, int * j) const
+{
+	if (!d) return defaultValue;
+	int i=0;
+	while (j-->0) getAttribute(name,&i);
+	XMLCSTR c = getAttribute(name,&i);
+	return c == NULL ? defaultValue : c;
+}
+
+XMLNodeContents XMLNode::enumContents(int i) const
+{
+    XMLNodeContents c;
+    if (!d) { c.etype=eNodeNULL; return c; }
+    if (i<d->nAttribute)
+    {
+        c.etype=eNodeAttribute;
+        c.attrib=d->pAttribute[i];
+        return c;
+    }
+    i-=d->nAttribute;
+    c.etype=(XMLElementType)(d->pOrder[i]&3);
+    i=(d->pOrder[i])>>2;
+    switch (c.etype)
+    {
+    case eNodeChild:     c.child = d->pChild[i];      break;
+    case eNodeText:      c.text  = d->pText[i];       break;
+    case eNodeClear:     c.clear = d->pClear[i];      break;
+    default: break;
+    }
+    return c;
+}
+
+XMLCSTR XMLNode::getName() const { if (!d) return NULL; return d->lpszName;   }
+int XMLNode::nText()       const { if (!d) return 0;    return d->nText;      }
+int XMLNode::nChildNode()  const { if (!d) return 0;    return d->nChild;     }
+int XMLNode::nAttribute()  const { if (!d) return 0;    return d->nAttribute; }
+int XMLNode::nClear()      const { if (!d) return 0;    return d->nClear;     }
+int XMLNode::nElement()    const { if (!d) return 0;    return d->nAttribute+d->nChild+d->nText+d->nClear; }
+XMLClear     XMLNode::getClear         (int i) const { if ((!d)||(i>=d->nClear    )) return emptyXMLClear;     return d->pClear[i];     }
+XMLAttribute XMLNode::getAttribute     (int i) const { if ((!d)||(i>=d->nAttribute)) return emptyXMLAttribute; return d->pAttribute[i]; }
+XMLCSTR      XMLNode::getAttributeName (int i) const { if ((!d)||(i>=d->nAttribute)) return NULL;              return d->pAttribute[i].lpszName;  }
+XMLCSTR      XMLNode::getAttributeValue(int i) const { if ((!d)||(i>=d->nAttribute)) return NULL;              return d->pAttribute[i].lpszValue; }
+XMLCSTR      XMLNode::getText          (int i) const { if ((!d)||(i>=d->nText     )) return NULL;              return d->pText[i];      }
+XMLNode      XMLNode::getChildNode     (int i) const { if ((!d)||(i>=d->nChild    )) return emptyXMLNode;      return d->pChild[i];     }
+XMLNode      XMLNode::getParentNode    (     ) const { if ((!d)||(!d->pParent     )) return emptyXMLNode;      return XMLNode(d->pParent); }
+char         XMLNode::isDeclaration    (     ) const { if (!d) return 0;             return d->isDeclaration; }
+char         XMLNode::isEmpty          (     ) const { return (d==NULL); }
+XMLNode       XMLNode::emptyNode       (     )       { return XMLNode::emptyXMLNode; }
+
+XMLNode       XMLNode::addChild(XMLCSTR lpszName, char isDeclaration, XMLElementPosition pos)
+              { return addChild_priv(0,stringDup(lpszName),isDeclaration,pos); }
+XMLNode       XMLNode::addChild_WOSD(XMLSTR lpszName, char isDeclaration, XMLElementPosition pos)
+              { return addChild_priv(0,lpszName,isDeclaration,pos); }
+XMLAttribute *XMLNode::addAttribute(XMLCSTR lpszName, XMLCSTR lpszValue)
+              { return addAttribute_priv(0,stringDup(lpszName),stringDup(lpszValue)); }
+XMLAttribute *XMLNode::addAttribute_WOSD(XMLSTR lpszName, XMLSTR lpszValuev)
+              { return addAttribute_priv(0,lpszName,lpszValuev); }
+XMLCSTR       XMLNode::addText(XMLCSTR lpszValue, XMLElementPosition pos)
+              { return addText_priv(0,stringDup(lpszValue),pos); }
+XMLCSTR       XMLNode::addText_WOSD(XMLSTR lpszValue, XMLElementPosition pos)
+              { return addText_priv(0,lpszValue,pos); }
+XMLClear     *XMLNode::addClear(XMLCSTR lpszValue, XMLCSTR lpszOpen, XMLCSTR lpszClose, XMLElementPosition pos)
+              { return addClear_priv(0,stringDup(lpszValue),lpszOpen,lpszClose,pos); }
+XMLClear     *XMLNode::addClear_WOSD(XMLSTR lpszValue, XMLCSTR lpszOpen, XMLCSTR lpszClose, XMLElementPosition pos)
+              { return addClear_priv(0,lpszValue,lpszOpen,lpszClose,pos); }
+XMLCSTR       XMLNode::updateName(XMLCSTR lpszName)
+              { return updateName_WOSD(stringDup(lpszName)); }
+XMLAttribute *XMLNode::updateAttribute(XMLAttribute *newAttribute, XMLAttribute *oldAttribute)
+              { return updateAttribute_WOSD(stringDup(newAttribute->lpszValue),stringDup(newAttribute->lpszName),oldAttribute->lpszName); }
+XMLAttribute *XMLNode::updateAttribute(XMLCSTR lpszNewValue, XMLCSTR lpszNewName,int i)
+              { return updateAttribute_WOSD(stringDup(lpszNewValue),stringDup(lpszNewName),i); }
+XMLAttribute *XMLNode::updateAttribute(XMLCSTR lpszNewValue, XMLCSTR lpszNewName,XMLCSTR lpszOldName)
+              { return updateAttribute_WOSD(stringDup(lpszNewValue),stringDup(lpszNewName),lpszOldName); }
+XMLCSTR       XMLNode::updateText(XMLCSTR lpszNewValue, int i)
+              { return updateText_WOSD(stringDup(lpszNewValue),i); }
+XMLCSTR       XMLNode::updateText(XMLCSTR lpszNewValue, XMLCSTR lpszOldValue)
+              { return updateText_WOSD(stringDup(lpszNewValue),lpszOldValue); }
+XMLClear     *XMLNode::updateClear(XMLCSTR lpszNewContent, int i)
+              { return updateClear_WOSD(stringDup(lpszNewContent),i); }
+XMLClear     *XMLNode::updateClear(XMLCSTR lpszNewValue, XMLCSTR lpszOldValue)
+              { return updateClear_WOSD(stringDup(lpszNewValue),lpszOldValue); }
+XMLClear     *XMLNode::updateClear(XMLClear *newP,XMLClear *oldP)
+              { return updateClear_WOSD(stringDup(newP->lpszValue),oldP->lpszValue); }
+
+char XMLNode::setGlobalOptions(XMLCharEncoding _characterEncoding, char _guessWideCharChars,
+                               char _dropWhiteSpace, char _removeCommentsInMiddleOfText)
+{
+    guessWideCharChars=_guessWideCharChars; dropWhiteSpace=_dropWhiteSpace; removeCommentsInMiddleOfText=_removeCommentsInMiddleOfText;
+#ifdef _XMLWIDECHAR
+    if (_characterEncoding) characterEncoding=_characterEncoding;
+#else
+    switch(_characterEncoding)
+    {
+    case char_encoding_UTF8:     characterEncoding=_characterEncoding; XML_ByteTable=XML_utf8ByteTable; break;
+    case char_encoding_legacy:   characterEncoding=_characterEncoding; XML_ByteTable=XML_legacyByteTable; break;
+    case char_encoding_ShiftJIS: characterEncoding=_characterEncoding; XML_ByteTable=XML_sjisByteTable; break;
+    case char_encoding_GB2312:   characterEncoding=_characterEncoding; XML_ByteTable=XML_gb2312ByteTable; break;
+    case char_encoding_Big5:
+    case char_encoding_GBK:      characterEncoding=_characterEncoding; XML_ByteTable=XML_gbk_big5_ByteTable; break;
+    default: return 1;
+    }
+#endif
+    return 0;
+}
+
+XMLNode::XMLCharEncoding XMLNode::guessCharEncoding(void *buf,int l, char useXMLEncodingAttribute)
+{
+#ifdef _XMLWIDECHAR
+    return (XMLCharEncoding)0;
+#else
+    if (l<25) return (XMLCharEncoding)0;
+    if (guessWideCharChars&&(myIsTextWideChar(buf,l))) return (XMLCharEncoding)0;
+    unsigned char *b=(unsigned char*)buf;
+    if ((b[0]==0xef)&&(b[1]==0xbb)&&(b[2]==0xbf)) return char_encoding_UTF8;
+
+    // Match utf-8 model ?
+    XMLCharEncoding bestGuess=char_encoding_UTF8;
+    int i=0;
+    while (i<l)
+        switch (XML_utf8ByteTable[b[i]])
+        {
+        case 4: i++; if ((i<l)&&(b[i]& 0xC0)!=0x80) { bestGuess=char_encoding_legacy; i=l; } // 10bbbbbb ?
+        case 3: i++; if ((i<l)&&(b[i]& 0xC0)!=0x80) { bestGuess=char_encoding_legacy; i=l; } // 10bbbbbb ?
+        case 2: i++; if ((i<l)&&(b[i]& 0xC0)!=0x80) { bestGuess=char_encoding_legacy; i=l; } // 10bbbbbb ?
+        case 1: i++; break;
+        case 0: i=l;
+        }
+    if (!useXMLEncodingAttribute) return bestGuess;
+    // if encoding is specified and different from utf-8 than it's non-utf8
+    // otherwise it's utf-8
+    char bb[201];
+    l=mmin(l,200);
+    memcpy(bb,buf,l); // copy buf into bb to be able to do "bb[l]=0"
+    bb[l]=0;
+    b=(unsigned char*)strstr(bb,"encoding");
+    if (!b) return bestGuess;
+    b+=8; while XML_isSPACECHAR(*b) b++; if (*b!='=') return bestGuess;
+    b++;  while XML_isSPACECHAR(*b) b++; if ((*b!='\'')&&(*b!='"')) return bestGuess;
+    b++;  while XML_isSPACECHAR(*b) b++;
+
+    if ((xstrnicmp((char*)b,"utf-8",5)==0)||
+        (xstrnicmp((char*)b,"utf8",4)==0))
+    {
+        if (bestGuess==char_encoding_legacy) return char_encoding_error;
+        return char_encoding_UTF8;
+    }
+
+    if ((xstrnicmp((char*)b,"shiftjis",8)==0)||
+        (xstrnicmp((char*)b,"shift-jis",9)==0)||
+        (xstrnicmp((char*)b,"sjis",4)==0)) return char_encoding_ShiftJIS;
+
+    if (xstrnicmp((char*)b,"GB2312",6)==0) return char_encoding_GB2312;
+    if (xstrnicmp((char*)b,"Big5",4)==0) return char_encoding_Big5;
+    if (xstrnicmp((char*)b,"GBK",3)==0) return char_encoding_GBK;
+
+    return char_encoding_legacy;
+#endif
+}
+#undef XML_isSPACECHAR
+
+//////////////////////////////////////////////////////////
+//      Here starts the base64 conversion functions.    //
+//////////////////////////////////////////////////////////
+
+static const char base64Fillchar = _CXML('='); // used to mark partial words at the end
+
+// this lookup table defines the base64 encoding
+XMLCSTR base64EncodeTable=_CXML("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
+
+// Decode Table gives the index of any valid base64 character in the Base64 table]
+// 96: '='  -   97: space char   -   98: illegal char   -   99: end of string
+const unsigned char base64DecodeTable[] = {
+    99,98,98,98,98,98,98,98,98,97,  97,98,98,97,98,98,98,98,98,98,  98,98,98,98,98,98,98,98,98,98,  //00 -29
+    98,98,97,98,98,98,98,98,98,98,  98,98,98,62,98,98,98,63,52,53,  54,55,56,57,58,59,60,61,98,98,  //30 -59
+    98,96,98,98,98, 0, 1, 2, 3, 4,   5, 6, 7, 8, 9,10,11,12,13,14,  15,16,17,18,19,20,21,22,23,24,  //60 -89
+    25,98,98,98,98,98,98,26,27,28,  29,30,31,32,33,34,35,36,37,38,  39,40,41,42,43,44,45,46,47,48,  //90 -119
+    49,50,51,98,98,98,98,98,98,98,  98,98,98,98,98,98,98,98,98,98,  98,98,98,98,98,98,98,98,98,98,  //120 -149
+    98,98,98,98,98,98,98,98,98,98,  98,98,98,98,98,98,98,98,98,98,  98,98,98,98,98,98,98,98,98,98,  //150 -179
+    98,98,98,98,98,98,98,98,98,98,  98,98,98,98,98,98,98,98,98,98,  98,98,98,98,98,98,98,98,98,98,  //180 -209
+    98,98,98,98,98,98,98,98,98,98,  98,98,98,98,98,98,98,98,98,98,  98,98,98,98,98,98,98,98,98,98,  //210 -239
+    98,98,98,98,98,98,98,98,98,98,  98,98,98,98,98,98                                               //240 -255
+};
+
+XMLParserBase64Tool::~XMLParserBase64Tool(){ freeBuffer(); }
+
+void XMLParserBase64Tool::freeBuffer(){ if (buf) free(buf); buf=NULL; buflen=0; }
+
+int XMLParserBase64Tool::encodeLength(int inlen, char formatted)
+{
+    unsigned int i=((inlen-1)/3*4+4+1);
+    if (formatted) i+=inlen/54;
+    return i;
+}
+
+XMLSTR XMLParserBase64Tool::encode(unsigned char *inbuf, unsigned int inlen, char formatted)
+{
+    int i=encodeLength(inlen,formatted),k=17,eLen=inlen/3,j;
+    alloc(i*sizeof(XMLCHAR));
+    XMLSTR curr=(XMLSTR)buf;
+    for(i=0;i<eLen;i++)
+    {
+        // Copy next three bytes into lower 24 bits of int, paying attention to sign.
+        j=(inbuf[0]<<16)|(inbuf[1]<<8)|inbuf[2]; inbuf+=3;
+        // Encode the int into four chars
+        *(curr++)=base64EncodeTable[ j>>18      ];
+        *(curr++)=base64EncodeTable[(j>>12)&0x3f];
+        *(curr++)=base64EncodeTable[(j>> 6)&0x3f];
+        *(curr++)=base64EncodeTable[(j    )&0x3f];
+        if (formatted) { if (!k) { *(curr++)=_CXML('\n'); k=18; } k--; }
+    }
+    eLen=inlen-eLen*3; // 0 - 2.
+    if (eLen==1)
+    {
+        *(curr++)=base64EncodeTable[ inbuf[0]>>2      ];
+        *(curr++)=base64EncodeTable[(inbuf[0]<<4)&0x3F];
+        *(curr++)=base64Fillchar;
+        *(curr++)=base64Fillchar;
+    } else if (eLen==2)
+    {
+        j=(inbuf[0]<<8)|inbuf[1];
+        *(curr++)=base64EncodeTable[ j>>10      ];
+        *(curr++)=base64EncodeTable[(j>> 4)&0x3f];
+        *(curr++)=base64EncodeTable[(j<< 2)&0x3f];
+        *(curr++)=base64Fillchar;
+    }
+    *(curr++)=0;
+    return (XMLSTR)buf;
+}
+
+unsigned int XMLParserBase64Tool::decodeSize(XMLCSTR data,XMLError *xe)
+{
+    if (!data) return 0;
+    if (xe) *xe=eXMLErrorNone;
+    int size=0;
+    unsigned char c;
+    //skip any extra characters (e.g. newlines or spaces)
+    while (*data)
+    {
+#ifdef _XMLWIDECHAR
+        if (*data>255) { if (xe) *xe=eXMLErrorBase64DecodeIllegalCharacter; return 0; }
+#endif
+        c=base64DecodeTable[(unsigned char)(*data)];
+        if (c<97) size++;
+        else if (c==98) { if (xe) *xe=eXMLErrorBase64DecodeIllegalCharacter; return 0; }
+        data++;
+    }
+    if (xe&&(size%4!=0)) *xe=eXMLErrorBase64DataSizeIsNotMultipleOf4;
+    if (size==0) return 0;
+    do { data--; size--; } while(*data==base64Fillchar); size++;
+    return (unsigned int)((size*3)/4);
+}
+
+unsigned char XMLParserBase64Tool::decode(XMLCSTR data, unsigned char *buf, int len, XMLError *xe)
+{
+    if (!data) return 0;
+    if (xe) *xe=eXMLErrorNone;
+    int i=0,p=0;
+    unsigned char d,c;
+    for(;;)
+    {
+
+#ifdef _XMLWIDECHAR
+#define BASE64DECODE_READ_NEXT_CHAR(c)                                              \
+        do {                                                                        \
+            if (data[i]>255){ c=98; break; }                                        \
+            c=base64DecodeTable[(unsigned char)data[i++]];                       \
+        }while (c==97);                                                             \
+        if(c==98){ if(xe)*xe=eXMLErrorBase64DecodeIllegalCharacter; return 0; }
+#else
+#define BASE64DECODE_READ_NEXT_CHAR(c)                                           \
+        do { c=base64DecodeTable[(unsigned char)data[i++]]; }while (c==97);   \
+        if(c==98){ if(xe)*xe=eXMLErrorBase64DecodeIllegalCharacter; return 0; }
+#endif
+
+        BASE64DECODE_READ_NEXT_CHAR(c)
+        if (c==99) { return 2; }
+        if (c==96)
+        {
+            if (p==(int)len) return 2;
+            if (xe) *xe=eXMLErrorBase64DecodeTruncatedData;
+            return 1;
+        }
+
+        BASE64DECODE_READ_NEXT_CHAR(d)
+        if ((d==99)||(d==96)) { if (xe) *xe=eXMLErrorBase64DecodeTruncatedData;  return 1; }
+        if (p==(int)len) {      if (xe) *xe=eXMLErrorBase64DecodeBufferTooSmall; return 0; }
+        buf[p++]=(unsigned char)((c<<2)|((d>>4)&0x3));
+
+        BASE64DECODE_READ_NEXT_CHAR(c)
+        if (c==99) { if (xe) *xe=eXMLErrorBase64DecodeTruncatedData;  return 1; }
+        if (p==(int)len)
+        {
+            if (c==96) return 2;
+            if (xe) *xe=eXMLErrorBase64DecodeBufferTooSmall;
+            return 0;
+        }
+        if (c==96) { if (xe) *xe=eXMLErrorBase64DecodeTruncatedData;  return 1; }
+        buf[p++]=(unsigned char)(((d<<4)&0xf0)|((c>>2)&0xf));
+
+        BASE64DECODE_READ_NEXT_CHAR(d)
+        if (d==99 ) { if (xe) *xe=eXMLErrorBase64DecodeTruncatedData;  return 1; }
+        if (p==(int)len)
+        {
+            if (d==96) return 2;
+            if (xe) *xe=eXMLErrorBase64DecodeBufferTooSmall;
+            return 0;
+        }
+        if (d==96) { if (xe) *xe=eXMLErrorBase64DecodeTruncatedData;  return 1; }
+        buf[p++]=(unsigned char)(((c<<6)&0xc0)|d);
+    }
+}
+#undef BASE64DECODE_READ_NEXT_CHAR
+
+void XMLParserBase64Tool::alloc(int newsize)
+{
+    if ((!buf)&&(newsize)) { buf=malloc(newsize); buflen=newsize; return; }
+    if (newsize>buflen) { buf=realloc(buf,newsize); buflen=newsize; }
+}
+
+unsigned char *XMLParserBase64Tool::decode(XMLCSTR data, int *outlen, XMLError *xe)
+{
+    if (xe) *xe=eXMLErrorNone;
+    if (!data) { *outlen=0; return (unsigned char*)""; }
+    unsigned int len=decodeSize(data,xe);
+    if (outlen) *outlen=len;
+    if (!len) return NULL;
+    alloc(len+1);
+    if(!decode(data,(unsigned char*)buf,len,xe)){ return NULL; }
+    return (unsigned char*)buf;
+}
+

Modified: trunk/src/SlideBible/platform/xmlParser.h
===================================================================
--- trunk/src/SlideBible/platform/xmlParser.h	2010-04-09 17:38:27 UTC (rev 231)
+++ trunk/src/SlideBible/platform/xmlParser.h	2010-04-09 17:44:00 UTC (rev 232)
@@ -322,9 +322,9 @@
                                       XMLCSTR attributeName,
                                       XMLCSTR attributeValue=NULL,
                                       int *i=NULL)  const;         ///< return child node with specific name/attribute (return an empty node if failing)
-    XMLNode getChildNodeByPath(XMLCSTR path, char createNodeIfMissing=0, XMLCHAR sep='/');
+    XMLNode getChildNodeByPath(XMLCSTR path, XMLCSTR createNode = NULL, XMLCHAR sep='/');
                                                                    ///< return the first child node with specific path
-    XMLNode getChildNodeByPathNonConst(XMLSTR  path, char createNodeIfMissing=0, XMLCHAR sep='/');
+    XMLNode getChildNodeByPathNonConst(XMLSTR  path, XMLCSTR createNode = NULL, XMLCHAR sep='/');
                                                                    ///< return the first child node with specific path.
 
     int nChildNode(XMLCSTR name) const;                            ///< return the number of child node with specific name
@@ -335,6 +335,7 @@
     char  isAttributeSet(XMLCSTR name) const;                      ///< test if an attribute with a specific name is given
     XMLCSTR getAttribute(XMLCSTR name, int i) const;               ///< return ith attribute content with specific name (return a NULL if failing)
     XMLCSTR getAttribute(XMLCSTR name, int *i=NULL) const;         ///< return next attribute content with specific name (return a NULL if failing)
+	XMLCSTR getAttribute(XMLCSTR name, XMLCSTR defaultValue, int *i=NULL) const; ///< return attribute content with specific name (return a defaultValue if failing)
     int nAttribute() const;                                        ///< nbr of attribute
     XMLClear getClear(int i=0) const;                              ///< return ith clear field (comments)
     int nClear() const;                                            ///< nbr of clear field

Modified: trunk/src/SlideBible/sbBase.h
===================================================================
--- trunk/src/SlideBible/sbBase.h	2010-04-09 17:38:27 UTC (rev 231)
+++ trunk/src/SlideBible/sbBase.h	2010-04-09 17:44:00 UTC (rev 232)
@@ -47,8 +47,8 @@
 {
 	sbRect (int _left_ = 0, int _top_ = 0, int _right_ = 0, int _bottom_ = 0) : left (_left_) , top (_top_) , right (_right_) , bottom (_bottom_) { ; }
 
-	inline int width  () const { return (right - left); }
-	inline int height () const { return (bottom - top); }
+	inline int  width  () const { return (right - left); }
+	inline int  height () const { return (bottom - top); }
 
 	inline bool inRect (int x, int y) const { return (x >= left && x < right && y >= top && y < bottom); }
 
@@ -87,26 +87,27 @@
 
 sbThread        sbThreadCreate         ( void (*executor) (bool *) );
 void            sbThreadDestroy        ( sbThread threadData );
-void            sbFillRect             ( sbSurface rc, const sbRect * rect, sbColor color );
-void            sbDrawGradient         ( sbSurface rc, const sbRect * rect, sbColor startColor, sbColor endColor, bool vertical );
-void            sbDrawBitmap           ( sbSurface rc, const sbRect * rect, sbBitmap bitmap, bool stretch = false );
+void            sbFillRect             ( sbSurface, const sbRect * rect, sbColor color );
+void            sbDrawGradient         ( sbSurface, const sbRect * rect, sbColor startColor, sbColor endColor, bool vertical );
+void            sbDrawBitmap           ( sbSurface, const sbRect * rect, sbBitmap bitmap, bool stretch = false );
 void            sbGetScreenRect        ( sbRect & rect );
 sbBitmap        sbLoadBitmap           ( const TCHAR * filename );
 sbSurface       sbSurfaceCreate        ( int width, int height );
-void            sbSurfaceDestroy       ( sbSurface surface );
-int             sbGetLastError         (); /* sbGetError */ // cut
+void            sbSurfaceDestroy       ( sbSurface );
 sbFont          sbMakeFont             ( int size, const TCHAR *face, bool bold, bool italic );
-sbPoint         sbGetTextExtent        ( sbFont font, const TCHAR * text, int count );
-void            sbDeleteFont           ( sbFont font );
+sbPoint         sbGetTextExtent        ( sbFont, const TCHAR * text, int count );
+void            sbDeleteFont           ( sbFont );
 void            sbDeleteBitmap         ( sbBitmap bitmap );
-sbFont          sbSelectFont           ( sbSurface rc, sbFont font );
-sbColor         sbSelectColor          ( sbSurface rc, sbColor color );
-void            sbDrawText             ( sbSurface rc, int x, int y, const TCHAR * text, int count );
+sbFont          sbSelectFont           ( sbSurface, sbFont );
+sbColor         sbSelectColor          ( sbSurface, sbColor );
+void            sbDrawText             ( sbSurface, int x, int y, const TCHAR * text, int count );
+void            sbDrawLine             ( sbSurface, sbPoint from, sbPoint to, sbColor, int thickness );
 void            sbSleep                ( int milliseconds );
 const char *    sbGetLocale            ();
 void            sbSetTimer             ( const int timer, int refreshRate );
 void            sbKillTimer            ( const int timer );
-void            sbBitBlt               ( sbSurface toRc, int left, int top, int width, int height, sbSurface fromRc, int x, int y);
+void            sbBitBlt               ( sbSurface, sbRect toRect , sbSurface fromRc, sbPoint fromXy );
+void            sbStretchBlt           ( sbSurface, sbRect toRect , sbSurface fromRc, sbRect fromRect );
 void            sbUpdateScreen         ();
 void            sbSetSip               ( bool on );
 long            sbGetTickCount         ();

Modified: trunk/src/SlideBible/sbControl.cpp
===================================================================
--- trunk/src/SlideBible/sbControl.cpp	2010-04-09 17:38:27 UTC (rev 231)
+++ trunk/src/SlideBible/sbControl.cpp	2010-04-09 17:44:00 UTC (rev 232)
@@ -20,34 +20,32 @@
 
 sbRect layout (int scheme, int num, int start, int end = 0)
 {
-	const int themeSize = Core->getTheme()->scale;
-	const sbRect * screenRect = &Core->getSurface(sbCore::SURFACE::TYPE_WHOLE)->rect;
-
+	const int themeSize = Core->getTheme()->size;
 	sbRect rect;
 
 	if (scheme == 1) // bottom bar
 	{
 		if (end > 0)
 		{
-			rect.left   = screenRect->right*start/num;
-			rect.top    = screenRect->bottom-(themeSize*20/100);
-			rect.right  = screenRect->right*end/num;
-			rect.bottom = screenRect->bottom;
+			rect.left   = Core->getRect().right*start/num;
+			rect.top    = Core->getRect().bottom-Core->getTheme()->PanelSize;
+			rect.right  = Core->getRect().right*end/num;
+			rect.bottom = Core->getRect().bottom;
 		}
 		else
 		{
-			rect.left   = screenRect->right*(start-1)/num;
-			rect.top    = screenRect->bottom-(themeSize*20/100);
-			rect.right  = screenRect->right*start/num;
-			rect.bottom = screenRect->bottom;
+			rect.left   = Core->getRect().right*(start-1)/num;
+			rect.top    = Core->getRect().bottom-Core->getTheme()->PanelSize;
+			rect.right  = Core->getRect().right*start/num;
+			rect.bottom = Core->getRect().bottom;
 		}
 	}
 	else if (scheme == 2) // can switch
 	{
-		rect.left   = screenRect->right*(start-1)/num;
-		rect.top    = screenRect->bottom-(themeSize*40/100);
-		rect.right  = screenRect->right*start/num;
-		rect.bottom = screenRect->bottom-(themeSize*20/100);
+		rect.left   = Core->getRect().right*(start-1)/num;
+		rect.top    = Core->getRect().bottom-(themeSize*40/100);
+		rect.right  = Core->getRect().right*start/num;
+		rect.bottom = Core->getRect().bottom-(themeSize*20/100);
 	}
 	else if (scheme == 0) // screen matrix
 	{
@@ -59,10 +57,10 @@
 		pv = start%columns == 0 ? columns : start%columns;
 		ph = ((start-pv)/columns)+1;
 
-		rect.left   = indent+((screenRect->right-(indent*2)+sep)*(pv-1)/columns);
-		rect.top    = (themeSize*10/100)+indent+((screenRect->bottom-(themeSize*30/100)-(indent*2)+sep)*(ph-1)/rows);
-		rect.right  = indent+((screenRect->right-(indent*2)+sep)*pv/columns)-sep;
-		rect.bottom = (themeSize*10/100)+indent+((screenRect->bottom-(themeSize*30/100)-(indent*2)+sep)*ph/rows)-sep;
+		rect.left   = indent+((Core->getRect().right-(indent*2)+sep)*(pv-1)/columns);
+		rect.top    = (themeSize*10/100)+indent+((Core->getRect().bottom-(themeSize*30/100)-(indent*2)+sep)*(ph-1)/rows);
+		rect.right  = indent+((Core->getRect().right-(indent*2)+sep)*pv/columns)-sep;
+		rect.bottom = (themeSize*10/100)+indent+((Core->getRect().bottom-(themeSize*30/100)-(indent*2)+sep)*ph/rows)-sep;
 
 		int w = rect.width();
 		int h = rect.height();
@@ -83,23 +81,23 @@
 : type ( _type_ )
 , text ( L"" )
 {
-	const int themeSize = Core->getTheme()->scale;
-	const sbRect * screenRect = & Core->getSurface( sbCore::SURFACE::TYPE_WHOLE )->rect;
+	const int themeSize = Core->getTheme()->size;
+	//const sbRect * screenRect = & Core->getSurface( sbCore::SURFACE::TYPE_WHOLE )->rect;
 
 	switch (type)
 	{
 	// navigation
-	case TYPE_OPEN_BOOK_SELECTION:   rect = layout(1,16, 0, 6);  setText(L"Book");    break;
-	case TYPE_OPEN_MODULE_SELECTION: rect = layout(1,16, 6,13);  setText(L"Module");  break;
+	case TYPE_OPEN_BOOK_SELECTION:   rect = layout(1,16,0,6);    setText(L"Book");    break;
+	case TYPE_OPEN_MODULE_SELECTION: rect = layout(1,16,6,13);   setText(L"Module");  break;
 	case TYPE_CLOSE:                 rect = layout(1,16,13,16);  setText(L"X");       break;
 	// list
-	case TYPE_OPEN_NAVIGATION_LIST:  rect = layout(1,16, 0, 7);  setText(L"Goto");    break;
-	case TYPE_LIST_SPACE:            rect = layout(1,16, 7,13);  setText(L" ");       break;
-	case TYPE_OPEN_HOME:             rect = layout(1,16,13,16);  setText(L"X");       break;
+	case TYPE_OPEN_NAVIGATION_LIST:  rect = layout(1,16,0,6);    setText(L"Goto");    break;
+	case TYPE_LIST_SPACE:            rect = layout(1,16,6,10);   setText(L" ");       break;
+	case TYPE_OPEN_HOME:             rect = layout(1,16,10,16);  setText(L"Home");    break;
 	// home
-	case TYPE_OPEN_NAVIGATION:       rect = layout(1,16,0,5);    setText(L"Goto");    break;
-	case TYPE_OPEN_HISTORY:          rect = layout(1,16,5,12);   setText(L"History"); break;
-	case TYPE_EXIT:                  rect = layout(1,16,12,16);  setText(L"Exit");    break;
+	case TYPE_OPEN_NAVIGATION:       rect = layout(1,16,0,6);    setText(L"Goto");    break;
+	case TYPE_OPEN_HISTORY:          rect = layout(1,16,6,11);   setText(L"History"); break;
+	case TYPE_EXIT:                  rect = layout(1,16,11,16);  setText(L"Exit");    break;
 	// other
 	case TYPE_MODE_ADD_STAR:         rect = layout(1,4,2);       setText(L"*");       break;
 	case TYPE_OPEN_SEARCH:           rect = layout(1,4,3);       setText(L"S");       break;
@@ -112,7 +110,7 @@
 	case TYPE_OPEN_READINGS:         rect = layout(1,4,3);       setText(L"R");       break;
 	case TYPE_MENU_EXIT:
 		{
-			rect = *screenRect;
+			rect = Core->getRect();
 		
 			childrens.push_back(new sbControl (sbControl::TYPE_MENU_EXIT_YES, layout(0,2,1), L"Yes"));
 			childrens.push_back(new sbControl (sbControl::TYPE_MENU_EXIT_NO,  layout(0,2,2), L"No"));
@@ -123,7 +121,7 @@
 
 	case TYPE_MENU_VERSE:
 		{
-			rect = *screenRect;
+			rect = Core->getRect();
 
 			// get verse state
 
@@ -148,7 +146,7 @@
 			int step = count / max + 1;
 			count = count / step;
 
-			rect = * screenRect;
+			rect = Core->getRect();
 
 			for ( int i = 1; i <= count; i++ )
 			{
@@ -192,32 +190,52 @@
 void sbControl::onPaint ( sbSurface hdc ) const
 {
 	sbFont font = sbSelectFont(hdc, Core->getTheme()->styles[style].font);
-	sbColor color = sbSelectColor(hdc, Core->getTheme()->ControlsColor);
+	sbColor color = sbSelectColor(hdc, Core->getTheme()->fadeColor(Core->getTheme()->ControlsColor,textPos.x,textPos.y));
 	
 	switch (type)
 	{
+	case TYPE_OPEN_BOOK_SELECTION:
+	case TYPE_OPEN_MODULE_SELECTION:
+	case TYPE_CLOSE:
+	case TYPE_OPEN_NAVIGATION_LIST:
+	case TYPE_LIST_SPACE:
+	case TYPE_OPEN_HOME:
+	case TYPE_OPEN_NAVIGATION:
+	case TYPE_OPEN_HISTORY:
+	case TYPE_EXIT:
+	case TYPE_WIDE_CLOSE:
+	case TYPE_MENU_CANCEL:
+		{
+			Core->getTheme()->drawElement(hdc, &rect, sbTheme::ELEMENT::PANEL);
+			sbDrawText(hdc, textPos.x, textPos.y, text, _tcslen(text));
+		}
+		break;
+
 	case TYPE_CAN_SWITCH_LEFT:
 	case TYPE_CAN_SWITCH_RIGHT:
-		sbSelectColor ( hdc, Core->getTheme()->ItemSubTextColor  );
-		sbDrawText ( hdc, textPos.x, textPos.y, text, _tcslen(text));
+		{
+			sbSelectColor ( hdc, Core->getTheme()->fadeColor(Core->getTheme()->ItemSubTextColor,textPos.x,textPos.y));
+			sbDrawText ( hdc, textPos.x, textPos.y, text, _tcslen(text));
+		}
 		break;
+
 	default:
 		if (isMenu())
 		{
-			sbAssert(Core->getSurface(sbCore::SURFACE::TYPE_WHOLE)->fade != true);
+			sbAssert(Core->fadeSurface != true);
 
-			Core->getSurface(sbCore::SURFACE::TYPE_WHOLE)->fade = false;
+			Core->fadeSurface = false;
 			
 			for (int i=0; i < childrens.size(); i++) childrens[i]->onPaint( hdc );
 
 			sbSelectColor(hdc, Core->getTheme()->ItemMenuTextColor);
 			sbDrawText(hdc, textPos.x, textPos.y, text, _tcslen(text));
 
-			Core->getSurface(sbCore::SURFACE::TYPE_WHOLE)->fade = true;
+			Core->fadeSurface = true;
 		}
 		else
 		{
-			Core->getTheme()->drawElement(hdc, &rect, sbTheme::ELEMENT::CONTROL);
+			Core->getTheme()->drawElement(hdc, &rect, sbTheme::ELEMENT::MENU);
 			sbDrawText(hdc, textPos.x, textPos.y, text, _tcslen(text));
 		}
 	}
@@ -269,7 +287,6 @@
 void sbControl::setText ( const TCHAR * _text_ )
 {
 	sbPoint sz;
-	//HDC hdc = CreateCompatibleDC ( NULL );
 
 	text = (TCHAR*)_text_;
 
@@ -279,8 +296,8 @@
 
 	if (h < Core->getTheme()->styles[sbTheme::STYLE::BUTTON_SMALL].size)
 		style = sbTheme::STYLE::BUTTON_SMALL;
-	else if (h < Core->getTheme()->styles[sbTheme::STYLE::TEXT].size)
-		style = sbTheme::STYLE::TEXT;
+	//else if (h < Core->getTheme()->styles[sbTheme::STYLE::TEXT].size)
+	//	style = sbTheme::STYLE::TEXT;
 	else if (h < Core->getTheme()->styles[sbTheme::STYLE::BUTTON].size)
 		style = sbTheme::STYLE::BUTTON;
 	else

Modified: trunk/src/SlideBible/sbControl.h
===================================================================
--- trunk/src/SlideBible/sbControl.h	2010-04-09 17:38:27 UTC (rev 231)
+++ trunk/src/SlideBible/sbControl.h	2010-04-09 17:44:00 UTC (rev 232)
@@ -84,7 +84,9 @@
 
 	void                         setText           ( const TCHAR * text );
 
-	inline bool                  isMenu            ( ) const {return (childrens.size()>0);}
+	inline bool                  isMenu            () const { return (childrens.size()>0); }
+
+	const sbRect &               getRect           () const { return rect; }
 	
 private:
 	sbRect                       rect;

Modified: trunk/src/SlideBible/sbCore.cpp
===================================================================
--- trunk/src/SlideBible/sbCore.cpp	2010-04-09 17:38:27 UTC (rev 231)
+++ trunk/src/SlideBible/sbCore.cpp	2010-04-09 17:44:00 UTC (rev 232)
@@ -21,6 +21,7 @@
 #include "sbCore.h"
 
 #pragma warning(disable : 4018) // signed/unsigned mismatch
+#pragma warning(disable : 4244) // signed/unsigned mismatch
 
 // Globals
 sbCore * Core;
@@ -34,6 +35,8 @@
 
 	Core = this;
 
+	time(&systemStarted);
+
 	// init data
 	currentList         = sbList::TYPE_HOME;
 	redrawTimerOn       = false;
@@ -41,7 +44,7 @@
 
 	listShift           = 0;
 
-	showBanner      = false;
+	showBanner          = false;
 
 	backgroundThread    = NULL;
 	
@@ -50,15 +53,44 @@
 
 	currentModule       = NULL;
 
+	fadeSurface         = false;
+	bScrollTimer        = false;
+
+	sword::SWLog::getSystemLog()->setLogLevel(5);
+
+	// load options
+	options = new sword::SWConfig(".\\options.conf");
+	sbAssert ( options == NULL );
+	options->Load();
+
+	cineticDamping    = atof((*options)["Ui"].getWithDefault("CineticDamping", "0.95"));
+	cineticFactor     = atof((*options)["Ui"].getWithDefault("CineticFactor", "0.5"));
+	refreshRate       = 1000/atoi((*options)["Ui"].getWithDefault("RefreshRate", "30"));
+	scrollStep        = atoi((*options)["Ui"].getWithDefault("scrollStep", "1"));
+	versesMax         = atoi((*options)["Ui"].getWithDefault("versesMax", "500"));
+	versesOptimal     = atoi((*options)["Ui"].getWithDefault("versesOptimal", "50"));
+
+	showFps           = atoi((*options)["Ui"].getWithDefault("showFps", "1"));
+
+	stretchSurface    = atoi((*options)["Ui"].getWithDefault("stretchSurface", "0"));
+	stretchVertical   = atof((*options)["Ui"].getWithDefault("stretchVertical", "1.0"));
+	stretchHorizontal = atof((*options)["Ui"].getWithDefault("stretchHorizontal", "1.0"));
+
 	// init surfaces
 	sbGetScreenRect (rClient);
 
-	surfaces[SURFACE::TYPE_WHOLE].rect = rClient;
+	if (stretchSurface)
+	{
+		rClient.bottom = rClient.height() * stretchVertical + rClient.top;
+		rClient.right  = rClient.width() * stretchHorizontal + rClient.left;
+	}
 
+	//surfaces[SURFACE::TYPE_WHOLE].rect = rClient;
+
 	theme.init(); // this must be after init SURFACE::TYPE_WHOLE, but before SURFACE::TYPE_LIST
 
-	surfaces[SURFACE::TYPE_LIST].rect = rClient;
-	surfaces[SURFACE::TYPE_LIST].rect.bottom -= theme.scale/5;
+	/*surfaces[SURFACE::TYPE_LIST].rect = rClient;
+	surfaces[SURFACE::TYPE_LIST].rect.bottom -= theme.PanelSize;
 
 	surfaces[SURFACE::TYPE_BUFFER].rect = surfaces[SURFACE::TYPE_LIST].rect;
 
@@ -66,22 +98,12 @@
 	{
 		surfaces[i].hdc = sbSurfaceCreate(surfaces[i].rect.width(), surfaces[i].rect.height());
 		surfaces[i].needRedraw = true;
-	}
+	}*/
+
+	drawSurface = sbSurfaceCreate (rClient.width(), rClient.height());
 	
 	sbUpdateScreen();
 
-	sword::SWLog::getSystemLog()->setLogLevel(5);
-
-	// load options
-	options = new sword::SWConfig(".\\options.conf");   sbAssert ( options == NULL );   options->Load();
-	
-	cineticDamping = (float)atof((*options)["Ui"].getWithDefault("CineticDamping", "0.95"));
-	cineticFactor  = (float)atof((*options)["Ui"].getWithDefault("CineticFactor", "0.5"));
-	refreshRate    = 1000/atoi((*options)["Ui"].getWithDefault("RefreshRate", "30"));
-	scrollStep     = atoi((*options)["Ui"].getWithDefault("scrollStep", "1"));
-	versesMax      = atoi((*options)["Ui"].getWithDefault("versesMax", "500"));
-	versesOptimal  = atoi((*options)["Ui"].getWithDefault("versesOptimal", "50"));
-
 	// user locale
 	sword::LocaleMgr::getSystemLocaleMgr()->setDefaultLocaleName((*options)["General"].getWithDefault("Locale", sbGetLocale()));
 
@@ -90,19 +112,22 @@
 	
 	sbAssert(swordMgr == NULL);
 
-	sbMessage ("Sword init finished.\n");
-
 	defaultModule = swordMgr->getModule((*options)["General"].getWithDefault("DefaultModule", "KJV"));
 
-	if (defaultModule == NULL && swordMgr->Modules.size() != 0) defaultModule = swordMgr->Modules.begin()->second;
+	if (defaultModule == NULL ) for (int i=0; i<swordMgr->Modules.size(); i++)
+	{
+		if (!strcmp(swordMgr->Modules[i]->Type(), "Biblical Texts"))
+		{
+			defaultModule = swordMgr->Modules.begin()->second;
+			break;
+		}
+	}
 
-	//currentModule = defaultModule;
-
 	// restore features
 	features.load();
 
 	sbSetTimer( TIMER_SAVE_CONFIG, 5*60*1000 );
-	
+
 	// create ui
 	switchList ( sbList::TYPE_HOME );
 
@@ -128,65 +153,44 @@
 	if (swordMgr != NULL) delete swordMgr;
 	if (options  != NULL) delete options;
 
-	for (int i=0; i<SURFACE::COUNT; i++)
-	{
-		sbSurfaceDestroy(surfaces[i].hdc);
-	}
+	//for (int i=0; i<SURFACE::COUNT; i++)
+	//{
+	//	sbSurfaceDestroy(surfaces[i].hdc);
+	//}
 
+	sbSurfaceDestroy(drawSurface);
+
 	sbMessage ("Shutdown SlideBible Core.\n");
 }
 
 void sbCore::onPaint ( sbSurface hdc )
 {
+	long startTicks = sbGetTickCount();
+
 	if (lists[currentList] != NULL)
 	{
 		if (listShift == 0)
 		{
-			lists[currentList]->render(surfaces[SURFACE::TYPE_WHOLE].hdc,showBanner);
+			lists[currentList]->render(drawSurface,showBanner);
 		}
 		else
 		{
-			if (surfaces[SURFACE::TYPE_LIST].needRedraw)
-			{
-				lists[currentList]->render(surfaces[SURFACE::TYPE_LIST].hdc,true);
-				surfaces[SURFACE::TYPE_LIST].needRedraw = false;
-			}
+			lists[currentList]->render(drawSurface,true,-listShift);
 
 			if (listShift > 0)
-			{
-				if (surfaces[SURFACE::TYPE_BUFFER].needRedraw)
-				{
-					if (lists[currentList]->getNext() != NULL)
-						lists[currentList]->getNext()->render(surfaces[SURFACE::TYPE_BUFFER].hdc,true);
-					else
-						Core->getTheme()->drawElement(surfaces[SURFACE::TYPE_BUFFER].hdc, &surfaces[SURFACE::TYPE_BUFFER].rect, sbTheme::ELEMENT::BACKGROUND);
-
-					surfaces[SURFACE::TYPE_BUFFER].needRedraw = false;
-				}
-
-				sbBitBlt(surfaces[SURFACE::TYPE_WHOLE].hdc, rClient.left, rClient.top, rClient.width()-listShift, rClient.height(), surfaces[SURFACE::TYPE_LIST].hdc, listShift, 0);
-				sbBitBlt(surfaces[SURFACE::TYPE_WHOLE].hdc, rClient.right-listShift, rClient.top, listShift, rClient.height(), surfaces[SURFACE::TYPE_BUFFER].hdc, 0, 0);
-			}
+				lists[currentList]->getNext()->render(drawSurface,true,-listShift+rClient.width());
 			else
-			{
-				if (surfaces[SURFACE::TYPE_BUFFER].needRedraw)
-				{
-					if (lists[currentList]->getPrev() != NULL)
-						lists[currentList]->getPrev()->render(surfaces[SURFACE::TYPE_BUFFER].hdc,true);
-					else
-						Core->getTheme()->drawElement(surfaces[SURFACE::TYPE_BUFFER].hdc, &surfaces[SURFACE::TYPE_BUFFER].rect, sbTheme::ELEMENT::BACKGROUND);
+				lists[currentList]->getPrev()->render(drawSurface,true,-listShift-rClient.width());
+		}
 
-					surfaces[SURFACE::TYPE_BUFFER].needRedraw = false;
-				}
+		for (std::vector<sbControl*>::const_iterator it=lists[currentList]->getControls()->begin(); it != lists[currentList]->getControls()->end(); it++)
+			(*it)->onPaint(drawSurface);
 
-				sbBitBlt(surfaces[SURFACE::TYPE_WHOLE].hdc, surfaces[SURFACE::TYPE_LIST].rect.left-listShift,  surfaces[SURFACE::TYPE_LIST].rect.top, surfaces[SURFACE::TYPE_LIST].rect.width()+listShift, surfaces[SURFACE::TYPE_LIST].rect.height(), surfaces[SURFACE::TYPE_LIST].hdc, 0, 0);
-				sbBitBlt(surfaces[SURFACE::TYPE_WHOLE].hdc, surfaces[SURFACE::TYPE_LIST].rect.left, surfaces[SURFACE::TYPE_LIST].rect.top, surfaces[SURFACE::TYPE_LIST].rect.left-listShift, surfaces[SURFACE::TYPE_LIST].rect.height(), surfaces[SURFACE::TYPE_BUFFER].hdc, surfaces[SURFACE::TYPE_BUFFER].rect.right+listShift, 0);
-			}
+		if (lists[currentList]->controlSelected >= 0)
+		{
+			theme.drawFrame(drawSurface,&(lists[currentList]->getControls()->at(lists[currentList]->controlSelected))->getRect());
 		}
 
-		for (std::vector<sbControl*>::const_iterator it=lists[currentList]->getControls()->begin(); it != lists[currentList]->getControls()->end(); it++)
-			(*it)->onPaint(surfaces[SURFACE::TYPE_WHOLE].hdc);
-
 		if (lists[currentList]->needScroll != 0)
 		{
 			if (!bScrollTimer)
@@ -217,18 +221,37 @@
 	}
 	else
 	{
-		Core->getTheme()->drawElement(surfaces[SURFACE::TYPE_WHOLE].hdc, &surfaces[SURFACE::TYPE_WHOLE].rect, sbTheme::ELEMENT::BACKGROUND);
+		Core->getTheme()->drawElement(drawSurface, &rClient, sbTheme::ELEMENT::BACKGROUND);
 	}
 
 	if (input.tapCounter > 0)
 	{
 		sbRect rect (input.start.x-(input.tapCounter*4), input.start.y-(input.tapCounter*4), input.start.x+(input.tapCounter*4), input.start.y+(input.tapCounter*4));
-		Core->getTheme()->drawElement(surfaces[SURFACE::TYPE_WHOLE].hdc, &rect, sbTheme::ELEMENT::TAPPED, input.tapCounter);
+		Core->getTheme()->drawElement(drawSurface, &rect, sbTheme::ELEMENT::TAPPED);
 	}
 
-	const SURFACE * whole = & surfaces[SURFACE::TYPE_WHOLE];
+	{
+		TCHAR text [16];
+		long delta = sbGetTickCount() - startTicks;
+		static long lastDelta = delta;
+		
+		lastDelta = max(lastDelta-1,max(delta,1));
+		
+		_sntprintf(text,16,L"%i fps",1000/lastDelta);
 
-	sbBitBlt(hdc, whole->rect.left, whole->rect.top, whole->rect.width(), whole->rect.height(), whole->hdc, 0, 0);
+		sbSelectFont(drawSurface,theme.styles[sbTheme::STYLE::BUTTON_SMALL].font);
+		sbSelectColor(drawSurface,sbColor(255,255,255));
+		sbDrawText(drawSurface, 4, 3, text, _tcslen(text));
+	}
+
+	if (stretchSurface)
+	{
+		sbRect rect;
+		sbGetScreenRect(rect);
+		sbStretchBlt(hdc, rect, drawSurface, rClient);
+	}
+	else
+		sbBitBlt(hdc, rClient, drawSurface, sbPoint(0,0));
 }
 
 void sbCore::onMouse ( int x, int y, const int state )
@@ -236,6 +259,17 @@
 	static int scrolldatay [2];
 	static int scrolldataticks [2];
 
+	keypadController = false;
+
+	if (stretchSurface)
+	{
+		sbRect rect;
+		sbGetScreenRect(rect);
+
+		x = x * rClient.width()  / rect.width();
+		y = y * rClient.height() / rect.height();
+	}
+
 	if ( state == MSG_MOUSE_L_DOWN )
 	{
 		if (listShift != 0) return;
@@ -246,13 +280,12 @@
 		input.leaveZone = false;
 		input.mousePressed = true;
 
-		if (lists[currentList] != NULL)
-			lists[currentList]->onPressed(x,y);
+		if (lists[currentList] != NULL) lists[currentList]->onPressed(x,y);
 		
+		cineticPower     = 0.0f;
 		input.tapCounter = 0;
+
 		sbSetTimer(TIMER_TAP, 1000/10);
-		
-		//sbMessage ("start click ================= \n");
 
 		scrolldatay[0]     = y;
 		scrolldataticks[0] = sbGetTickCount();
@@ -261,12 +294,12 @@
 	{
 		if (!input.mousePressed) return;
 
-		const int max = theme.scale/20;
+		const int max = theme.size / 20;
 
 		int dx = x - input.last.x;
 		int dy = y - input.last.y;
 
-		if (abs(input.start.x-x) > max || abs(input.start.y-y) > max)
+		if ( abs(input.start.x-x) > max || abs(input.start.y-y) > max )
 		{
 			input.leaveZone = true;
 			sbKillTimer(TIMER_TAP);
@@ -278,7 +311,7 @@
 
 		if (scrolldataticks[1] - scrolldataticks[0] > 200)
 		{
-			scrolldatay[0]     = scrolldatay[1] + ((scrolldatay[0]-scrolldatay[1]) * (200.0f/(scrolldataticks[1]-scrolldataticks[0])));
+			scrolldatay[0]     = scrolldatay[1] + (int)((scrolldatay[0]-scrolldatay[1]) * (200.0f/(scrolldataticks[1]-scrolldataticks[0])));
 			scrolldataticks[0] = scrolldataticks[1] - 200;
 		}
 
@@ -295,7 +328,7 @@
 				if (listShift > 0 && lists[currentList]->getNext() == NULL) listShift = 0;
 			}
 
-			if (dy != 0 && listShift == 0)
+			//if (dy != 0 && listShift == 0)
 				lists[currentList]->scroll((float)dy);
 
 			redraw();
@@ -319,7 +352,7 @@
 
 		float speed = (scrolldatay[1]-scrolldatay[0])/(float)max((scrolldataticks[1]-scrolldataticks[0]),120);
 		
-		cineticPower = (speed*50.0f) + (cineticPower*min(fabs(speed)*200.0f/Core->getTheme()->scale,1.0f));
+		cineticPower = (speed*50.0f) + (cineticPower*min(fabs(speed)*200.0f/Core->getTheme()->size,1.0f));
 		
 		//sbMessage ("Ticks %i\t Y %i\t cineticPower %f\n", scrolldataticks[0], scrolldatay[0], cineticPower);
 		//sbMessage ("Ticks %i\t Y %i\t Duration %i\t Speed %f\n", scrolldataticks[1], scrolldatay[1],scrolldataticks[1]-scrolldataticks[0],speed);
@@ -423,8 +456,8 @@
 
 				// reset information for slide
 				listShift = 0;
-				surfaces[SURFACE::TYPE_LIST  ].needRedraw = true;
-				surfaces[SURFACE::TYPE_BUFFER].needRedraw = true;
+				//surfaces[SURFACE::TYPE_LIST  ].needRedraw = true;
+				//surfaces[SURFACE::TYPE_BUFFER].needRedraw = true;
 
 				sbKillTimer(TIMER_SLIDE);
 			}
@@ -594,6 +627,8 @@
 
 void sbCore::onKey ( int key , bool down )
 {
+	keypadController = true;
+
 	if ( lists[currentList] != NULL && down ) lists[currentList]->onKey ( key );
 }
 

Modified: trunk/src/SlideBible/sbCore.h
===================================================================
--- trunk/src/SlideBible/sbCore.h	2010-04-09 17:38:27 UTC (rev 231)
+++ trunk/src/SlideBible/sbCore.h	2010-04-09 17:44:00 UTC (rev 232)
@@ -26,7 +26,7 @@
 class sbCore
 {
 public:
-	struct SURFACE
+	/*struct SURFACE
 	{
 		SURFACE () : fade ( false ) , needRedraw ( false ) { ; }
 
@@ -39,12 +39,11 @@
 		};
 		
 		sbSurface          hdc;
-		//sbBitmap                 bitmap;
 		sbRect                   rect;
 		
 		bool                     needRedraw;
 		mutable bool             fade;
-	};
+	};*/
 	
 	struct INPUT
 	{
@@ -80,13 +79,14 @@
 	void                         onChar           ( TCHAR c );
 	void                         onKey            ( int key , bool down );
 
-	void                         redraw           ( );
+	void                         redraw           ();
 
-	const sbTheme *              getTheme         ( )                    {return &theme;}
-	sword::SWMgr *               getSword         ( )                    {return swordMgr;}
-	sword::SWConfig *            getOptions       ( )                    {return options;}
-	const SURFACE *              getSurface       ( SURFACE::TYPE type ) {return &surfaces[type];}
-	const INPUT *                getInput         ( )                    {return &input;}
+	const sbTheme *              getTheme         ()                     {return &theme;}
+	sword::SWMgr *               getSword         ()                     {return swordMgr;}
+	sword::SWConfig *            getOptions       ()                     {return options;}
+	//const SURFACE *              getSurface       ( SURFACE::TYPE type ) {return &surfaces[type];}
+	const INPUT *                getInput         ()                     {return &input;}
+	const sbRect &               getRect          ()                     {return rClient;}
 	
 	void                         switchList       ( sbList::TYPE to );
 
@@ -121,8 +121,14 @@
 	sbTheme                      theme;
 
 	sbRect                       rClient;
+
+	sbSurface                    drawSurface;
+
+	bool                         stretchSurface;
+	float                        stretchVertical;
+	float                        stretchHorizontal;
 	
-	SURFACE                      surfaces[SURFACE::COUNT]; // CUT
+	//SURFACE                      surfaces[SURFACE::COUNT]; // CUT
 
 	sword::SWMgr                *swordMgr;
 	sword::SWConfig             *options;
@@ -132,11 +138,13 @@
 	int                          refreshRate;
 
 	bool                         showBanner;
+	bool                         showFps;
 
 public:
 
 	sbFeatures                   features;
 
+	bool                         fadeSurface;
 
 	unsigned int                 scrollStep;
 	unsigned int                 versesMax;
@@ -151,7 +159,8 @@
 	bool                         goVerse;           // necessity of transition, with currentVerse and currentModule
 	int                          goReading;         // need attach reading on activate, default -1
 
-	//int                          readingRemoved;    // should be broadcast message for all lists, default -1
+	time_t                       systemStarted;
+	bool                         keypadController;  // whether user control with keypad / touchscreen
 };
 
 extern sbCore * Core;

Modified: trunk/src/SlideBible/sbFeatures.cpp
===================================================================
--- trunk/src/SlideBible/sbFeatures.cpp	2010-04-09 17:38:27 UTC (rev 231)
+++ trunk/src/SlideBible/sbFeatures.cpp	2010-04-09 17:44:00 UTC (rev 232)
@@ -50,53 +50,25 @@
 {
 	if (Core->defaultModule == NULL) return;
 
-	bool   firstRun = false;
-	FILE * file     = fopen (".\\features.xml","rb");
+	XMLNode xml = XMLNode::openFileHelper(".\\features.xml");
 
-	if (file != NULL)
+	if (!xml.isEmpty())
 	{
-		fclose(file);
-
 		int loadRevision = 0;
-		XMLNode xml = XMLNode::openFileHelper(".\\features.xml");
-		
+				
 		if (!xml.getChildNode("Features").isEmpty())
 		{
 			const char * text = xml.getChildNode("Features").getAttribute("revision");
 			loadRevision = atoi(text);
 		}
 
-		if (loadRevision == revision)
+		if (loadRevision >= revision)
 		{
-			XMLNode xr = xml.getChildNode("Features").getChildNode("Readings");
-
-			if (!xr.isEmpty())
-			{
-				readings.reserve(xr.nChildNode("reading")+8);
-
-				for (int i = 0; i < xr.nChildNode("reading"); i++)
-				{
-					XMLNode n = xr.getChildNode("reading",i);
-					Reading r;
-
-					//const char * cp = n.getAttribute("created");
-					//long lp         = atol(n.getAttribute("created"));
-					//time_t tp       = atol(n.getAttribute("created"));
-
-					r.created = atol(n.getAttribute("created"));
-					r.visited = atol(n.getAttribute("visited"));
-					r.module  = holdString(n.getAttribute("module"));
-					r.place   = atol(n.getAttribute("place"));
-
-					readings.push_back(r);
-				}
-			}
-
 			XMLNode xh = xml.getChildNode("Features").getChildNode("History");
 
 			if (!xh.isEmpty())
 			{
-				history.reserve(xh.nChildNode("history")+64);
+				history.reserve(xh.nChildNode("history"));
 
 				for (int i = 0; i < xh.nChildNode("history"); i++)
 				{
@@ -104,49 +76,16 @@
 					History h;
 
 					h.module     = holdString(n.getAttribute("module"));
-					h.placeStart = atol(n.getAttribute("placeStart"));
-					h.placeEnd   = atol(n.getAttribute("placeEnd"));
 					h.visitStart = atol(n.getAttribute("visitStart"));
 					h.visitEnd   = atol(n.getAttribute("visitEnd"));
-
+					h.placeStart = atol(n.getAttribute("placeStart"));
+					h.placeEnd   = atol(n.getAttribute("placeEnd"));
+					
 					history.push_back(h);
 				}
 			}
 		}
-		else
-		{
-			firstRun = true;
-		}
 	}
-	else
-	{
-		firstRun = true;
-	}
-
-	if ( firstRun )
-	{
-		sword::VerseKey workKey = Core->defaultModule->getKey();
-
-		readings.resize(2);
-
-		time(&readings[0].created);
-		time(&readings[0].visited);
-		readings[0].module = Core->defaultModule->Name();
-		workKey = "Gen 1:1";
-		readings[0].place = workKey.Index();
-		
-		time(&readings[1].created);
-		time(&readings[1].visited);
-		readings[1].module = Core->defaultModule->Name();
-		workKey = "Matt 1:1";
-		readings[1].place = workKey.Index();
-	}
-
-	// delete history for unknown modules
-	/*for (int i=history.size()-1; i>=0; i--)
-	{
-		if (Core->getSword()->getModule(history[i].module) == NULL) history.erase(history.begin()+i);
-	}*/
 }
 
 void sbFeatures::save()
@@ -164,32 +103,17 @@
 	_itoa(revision,buf,10);
 	xf.addAttribute("revision",buf);
 
-	if (readings.size() > 0)
+	XMLNode xh = xf.addChild("History");
+
+	for (int i=0; i < history.size(); i++)
 	{
-		XMLNode xr = xf.addChild("Readings");
+		XMLNode n = xh.addChild("history");
 
-		for (int i=0; i < readings.size(); i++)
-		{
-			XMLNode n = xr.addChild("reading");
-
-			_ltoa(readings[i].created,buf,10);                n.addAttribute("created",buf);
-			_ltoa(readings[i].visited,buf,10);                n.addAttribute("visited",buf);
-			_ltoa(readings[i].place,buf,10);                  n.addAttribute("place",buf);
-			n.addAttribute("module",readings[i].module);
-		}
-
-		XMLNode xh = xf.addChild("History");
-
-		for (int i=0; i < history.size(); i++)
-		{
-			XMLNode n = xh.addChild("history");
-
-			_ltoa(history[i].placeStart,buf,10);              n.addAttribute("placeStart",buf);
-			_ltoa(history[i].placeEnd,buf,10);                n.addAttribute("placeEnd",buf);
-			_ltoa(history[i].visitStart,buf,10);              n.addAttribute("visitStart",buf);
-			_ltoa(history[i].visitEnd,buf,10);                n.addAttribute("visitEnd",buf);
-			n.addAttribute("module",history[i].module);
-		}
+		_ltoa(history[i].placeStart,buf,10);              n.addAttribute("placeStart",buf);
+		_ltoa(history[i].placeEnd,buf,10);                n.addAttribute("placeEnd",buf);
+		_ltoa(history[i].visitStart,buf,10);              n.addAttribute("visitStart",buf);
+		_ltoa(history[i].visitEnd,buf,10);                n.addAttribute("visitEnd",buf);
+		n.addAttribute("module",history[i].module);
 	}
 
 	xml.writeToFile(".\\features.xml");
@@ -199,9 +123,8 @@
 // todo, check for previous history item
 int sbFeatures::addHistory ( const char * module, long place )
 {
-	//sbMessage ("sbFeatures::addHistory module %s place %i\n",module,place);
-
 	History h;
+
 	time(&h.visitStart);
 	h.visitEnd   = h.visitStart;
 	h.module     = module;
@@ -227,20 +150,3 @@
 
 	time(&history[id].visitEnd);
 }
-
-void sbFeatures::updateReading( int id, const char * module, long place )
-{
-	//sbMessage ("sbFeatures::updateReading id %i module %s place %i\n",id,module,place);
-
-	if (module != readings[id].module)
-	{
-		readings[id].place = place;
-		time(&readings[id].visited);
-		readings[id].module = module;
-	}
-	else if (place > readings[id].place)
-	{
-		readings[id].place = place;
-		time(&readings[id].visited);
-	}
-}
\ No newline at end of file

Modified: trunk/src/SlideBible/sbFeatures.h
===================================================================
--- trunk/src/SlideBible/sbFeatures.h	2010-04-09 17:38:27 UTC (rev 231)
+++ trunk/src/SlideBible/sbFeatures.h	2010-04-09 17:44:00 UTC (rev 232)
@@ -25,15 +25,15 @@
 	sbFeatures ();
 	~sbFeatures();
 
-	typedef struct Reading
+	/*struct Reading
 	{
 		const char               * module;
 		long                       place;
 		time_t                     created;
 		time_t                     visited;
-	};
+	};*/
 
-	typedef struct Bookmark
+	struct Bookmark
 	{
 		//const TCHAR              * name;
 		const char               * module;
@@ -42,7 +42,7 @@
 //		time_t                     visited;
 	};
 
-	typedef struct History
+	struct History
 	{
 		const char               * module;
 		long                       placeStart;
@@ -53,16 +53,17 @@
 
 	int                       addHistory     ( const char * module, long place );
 	void                      updateHistory  ( int id, long place );
-	void                      updateReading  ( int id, const char * module, long place );
 
 	void                      save ();
 	void                      load ();
 
+	void                      dump ();
+
 	const char *              holdString     ( const char * string );
 
 	static const int          revision;
 
-	std::vector<Reading>      readings;
+	//std::vector<Reading>      readings;
 	std::vector<History>      history;
 
 private:

Modified: trunk/src/SlideBible/sbItem.cpp
===================================================================
--- trunk/src/SlideBible/sbItem.cpp	2010-04-09 17:38:27 UTC (rev 231)
+++ trunk/src/SlideBible/sbItem.cpp	2010-04-09 17:44:00 UTC (rev 232)
@@ -45,11 +45,12 @@
 	case TYPE_BUTTON_CHAPTER_NEXT:
 	case TYPE_BUTTON_CHAPTER_PREV:
 		style = sbTheme::STYLE::DESCRIPTION;
-		lines.reserve(2);
+		lines.reserve(1);
 		break;
 
 	case TYPE_CHECKBOX:
 		center = true;
+
 	case TYPE_BUTTON_BOOKMARK:
 	case TYPE_BUTTON_SELECTION_BOOK:
 	case TYPE_BUTTON_SELECTION_CHAPTER:
@@ -58,10 +59,15 @@
 		lines.reserve(2);
 		break;
 
+	case TYPE_BUTTON_BOOKMARK_SMALL:
+		style = sbTheme::STYLE::BUTTON_SMALL;
+		lines.reserve(2);
+		break;
+
 	case TYPE_HEADER:
 		style = sbTheme::STYLE::CAPTION;
 		center = true;
-		lines.reserve(2);
+		lines.reserve(1);
 		break;
 
 	default:
@@ -69,7 +75,7 @@
 	}
 
 	highlighted = false;
-	height      = Core->getTheme()->styles[style].size + Core->getTheme()->itemTopMargin + Core->getTheme()->itemBottomMargin;
+	height      = Core->getTheme()->styles[style].size + Core->getTheme()->itemMargins.top + Core->getTheme()->itemMargins.bottom;
 	expanding   = 0;
 
 	next  = NULL;
@@ -167,109 +173,233 @@
 	bool skip = false,  italic = false;
 	sbFont font = Core->getTheme()->styles[style].font;
 
+	char changeStyle = style;
+
+	LINE currentLine;
+
+	currentLine.style   = style;
+	currentLine.pos     = 0;
+	currentLine.count   = 0;
+	currentLine.width   = 0;
+	currentLine.height  = 0;     // only last line, with newLine = true, contains most large height
+	currentLine.newLine = false; // should be false always
+
 	sbAssert( _text_ == NULL );
 	
 	if ( ! lines.empty() ) lines.clear();
 
-	lines.push_back( LINE (style) );
-
 	for(int i=0; i<length; i++)
 	{
 		TCHAR c = *(_text_+i);
 
 		if (c == L'<')
 		{
+			if (currentLine.count > 0)
+			{
+				// finish current
+				lines.push_back(currentLine);
+				currentLine.count = currentLine.width = 0;
+			}
+
+			// and begin new
 			skip = true;
 
 			if (_tcsncmp(_text_+i+1,L"transChange type=\"added\"",24) == 0)
 			{
-				italic = true;
+				//italic = true;
+				currentLine.style = sbTheme::STYLE::TEXT_ITALIC;
 			}
-			else if (_tcsncmp(_text_+i+1,L"/transChange", 12) == 0)
+			else if (_tcsncmp(_text_+i+1,L"/transChange",12) == 0)
 			{
-				italic = false;
+				// TODO push from stack
+				currentLine.style = style;
 			}
-			/*if (_tcsncmp(_text+i+1,L"styleChange ",12) == 0){}
-			else if (_tcsncmp(_text+i+1,L"/styleChange", 12) == 0){}
-			else if (_tcsncmp(text+i+1,L"verse",5) == 0){}
-			else if (_tcsncmp(text+i+1,L"/verse",6) == 0){}
-			else if (_tcsncmp(text+i+1,L"w ",2) == 0){}
-			else if (_tcsncmp(text+i+1,L"w>",2) == 0){}
-			else if (_tcsncmp(text+i+1,L"/w",2) == 0){}
-			else {sbMessage("Unknown tag at %S\n",text+i+1);}*/
+			else if (_tcsncmp(_text_+i+1,L"s ",2) == 0)
+			{
+				if (_tcsncmp(_text_+i+1,L"s t=\"6\"",7) == 0)
+					currentLine.style = sbTheme::STYLE::DESCRIPTION;
+				else if (_tcsncmp(_text_+i+1,L"s t=\"5\"",7) == 0)
+					currentLine.style = sbTheme::STYLE::CAPTION;
+				else
+					sbAssert( true );
+			}
+			else if (_tcsncmp(_text_+i+1,L"/s>",3) == 0)
+			{
+				// TODO push from stack
+				currentLine.style = style;
+			}
 		}
 		else if (skip && c == L'>')
 		{
 			skip = false;
-			
-			lines.push_back(lines.back());
-			lines.back().width = lines.back().count = 0;
-			lines.back().pos = i+1;
-			lines.back().newLine = false;
-
-			lines.back().style = italic == true ? sbTheme::STYLE::TEXT_ITALIC : style;
-
-			font = Core->getTheme()->styles[lines.back().style].font;
 		}
-		else if (c == L'\t')
-		{
-			;
-		}
 		else if (c == L'\n')
 		{
-			lines.back().newLine = true;
 			lineWidth = 0;
 
-			lines.push_back(lines.back());
-			lines.back().width = lines.back().height = lines.back().count = 0;
-			lines.back().pos = i+1;
-			lines.back().newLine = false;
+			lines.push_back(currentLine);
+			lines.back().newLine = true;
+
+			currentLine.count = currentLine.width = currentLine.height = 0;
 		}
 		else if (!skip)
 		{
 			// add character
-			sz = sbGetTextExtent(font,&c,1);
+			sz = sbGetTextExtent(Core->getTheme()->styles[currentLine.style].font,&c,1);
+
+			if (currentLine.count == 0)
+			{
+				if (c == L'\t') continue;
+
+				currentLine.pos = i;
+			}
 			
-			// begin new line
-			if ((lineWidth + sz.x > width-Core->getTheme()->itemLeftMargin-Core->getTheme()->itemRightMargin) \
+			// line will be too long, divide lines
+			if ((lineWidth + sz.x > width-Core->getTheme()->itemMargins.left-Core->getTheme()->itemMargins.right) \
 				&& c != L'.' && c != L',' && c != L' ')
 			{
-				lines.back().newLine = true;
 				lineWidth = 0;
 
-				lines.push_back(lines.back());
-				lines.back().width = lines.back().height = lines.back().count = 0;
-				lines.back().pos = i;
-				lines.back().newLine = false;
+				lines.push_back(currentLine);
+				lines.back().newLine = true;
+
+				currentLine.count = currentLine.width = currentLine.height = 0;
 			}
 
-			if (lines.back().count == 0) lines.back().pos = i;
+			if (currentLine.count == 0) currentLine.pos = i;
 
-			lines.back().width += (unsigned short) sz.x;
+			currentLine.width += (unsigned short) sz.x;
 			
-			if (sz.y > lines.back().height)
+			if (sz.y > currentLine.height)
 			{
-				sbAssert ((sz.y >= Core->getTheme()->scale/8) && (type == TYPE_VERSE));
-				lines.back().height = (unsigned short) sz.y;
+				sbAssert ((sz.y >= Core->getTheme()->size/8) && (type == TYPE_VERSE));
+				currentLine.height = (unsigned short) sz.y;
 			}
 			
-			lines.back().count++;
+			currentLine.count++;
 
 			lineWidth += (unsigned short) sz.x;
 		}
 	}
 
-	lines.back().newLine = true;
+	if (currentLine.count > 0)
+	{
+		lines.push_back(currentLine);
+		lines.back().newLine = true;
+	}
+	else if (lines.size() > 0)
+	{
+		lines.back().newLine = true;
+	}
 
-	height = Core->getTheme()->itemTopMargin + Core->getTheme()->itemBottomMargin;
+	height = Core->getTheme()->itemMargins.top + Core->getTheme()->itemMargins.bottom;
 
-	for (int i=0; i<lines.size(); i++) if (lines[i].newLine) height += lines[i].height;
+	if (type == sbItem::TYPE_HISTORY)
+	{
+		height += max (Core->getTheme()->styles[sbTheme::STYLE::CAPTION].size,Core->getTheme()->styles[sbTheme::STYLE::TEXT].size+Core->getTheme()->styles[sbTheme::STYLE::DESCRIPTION].size);
+	}
+	else
+	{
+		for (int i=0; i<lines.size(); i++) if (lines[i].newLine) height += lines[i].height;
+	}
 
-	if (style == sbTheme::STYLE::BUTTON && height < Core->getTheme()->fingerSize)
+	// hack to make space for buttons
+	if ((style == sbTheme::STYLE::BUTTON || style == sbTheme::STYLE::BUTTON_SMALL) && height < Core->getTheme()->size/6)
 	{
-		lines.insert(lines.begin(),LINE(style,true,0,(Core->getTheme()->fingerSize-height)/2));
-		height = Core->getTheme()->fingerSize;
+		lines.insert(lines.begin(),LINE(style,true,0,((Core->getTheme()->size/6)-height)/2));
+		height = Core->getTheme()->size/6;
 	}
 	
 	text = _text_;    // need to be set last
 }
+
+void sbItem::render ( sbSurface surface, const sbRect & rect, sbTheme::ELEMENT::TYPE element ) const
+{
+	Core->getTheme()->drawElement( surface, &rect, element );
+
+	if (type == sbItem::TYPE_HISTORY)
+	{
+		sbAssert (lines.size() != 3);
+
+		sbSelectFont (surface, Core->getTheme()->styles[lines[0].style].font);
+		sbSelectColor(surface, Core->getTheme()->fadeColor(Core->getTheme()->ItemTextColor,rect.left,rect.top));
+		sbDrawText   (surface, rect.left + Core->getTheme()->itemMargins.left, rect.top + Core->getTheme()->itemMargins.top, text.c_str() + lines[0].pos, lines[0].count);
+
+		sbSelectFont (surface, Core->getTheme()->styles[lines[1].style].font);
+		sbDrawText   (surface, rect.right - Core->getTheme()->itemMargins.right - lines[1].width, rect.top + Core->getTheme()->itemMargins.top, text.c_str() + lines[1].pos, lines[1].count);
+
+		sbSelectFont (surface, Core->getTheme()->styles[lines[2].style].font);
+		sbDrawText   (surface, rect.left + Core->getTheme()->itemMargins.left, rect.top + Core->getTheme()->itemMargins.top + lines[0].height, text.c_str() + lines[2].pos, lines[2].count);
+	}
+	else
+	{
+		if ( text.size() > 0 )
+		{
+			if ( subtext.size() > 0 )
+			{
+				sbPoint pos = sbGetTextExtent(Core->getTheme()->styles[sbTheme::STYLE::STANZA].font,subtext.c_str(), subtext.size());
+
+				pos.x = rect.left+((Core->getTheme()->itemMargins.left-pos.x)/2);
+				pos.y = rect.top;
+
+				sbSelectFont(surface, Core->getTheme()->styles[sbTheme::STYLE::STANZA].font);
+				sbSelectColor(surface, Core->getTheme()->fadeColor(Core->getTheme()->ItemSubTextColor, pos.x, pos.y));
+
+				sbDrawText(surface, pos.x, pos.y, subtext.c_str(), subtext.size());
+			}
+
+			int lx = 0;
+			int ly = rect.top + Core->getTheme()->itemMargins.top;
+
+			for (int i=0; i < lines.size(); i++)
+			{
+				int x = lx + Core->getTheme()->itemMargins.left + rect.left;
+				int y = ly;
+
+				// possible BUG with center alignment and many text parts
+				if (center)
+				{
+					x += (rect.width()-Core->getTheme()->itemMargins.left-Core->getTheme()->itemMargins.right-lines[i].width)/2;
+				}
+
+				if (lines[i].newLine)
+				{
+					lx = 0;
+					ly += lines[i].height;
+				}
+				else
+					lx += lines[i].width;
+
+				if (lines[i].count == 0) continue;
+
+				if (y + Core->getTheme()->styles[lines[i].style].size >= rect.top + height) break;  // item expansion
+				if (y < -Core->getTheme()->styles[lines[i].style].size) continue;                   // clip top
+				if (y >= rect.bottom) break;                                                        // clip bottom
+
+				sbSelectFont(surface, Core->getTheme()->styles[lines[i].style].font);
+				sbSelectColor(surface, Core->getTheme()->fadeColor(Core->getTheme()->ItemTextColor,x,y));
+
+				sbDrawText (surface, x, y, text.c_str() + lines[i].pos, lines[i].count);
+			}
+		}
+		else
+		{
+			if (subtext.size() > 0)
+			{
+				sbPoint pos = sbGetTextExtent(Core->getTheme()->styles[sbTheme::STYLE::BUTTON].font, subtext.c_str(), subtext.size());
+
+				pos.x = rect.left+((rect.width()-pos.x)/2);
+				pos.y = rect.top+((rect.height()-pos.y)/2);
+
+				sbSelectFont(surface, Core->getTheme()->styles[sbTheme::STYLE::BUTTON].font);
+				sbSelectColor(surface, Core->getTheme()->fadeColor(Core->getTheme()->ItemSubTextColor,pos.x,pos.y));
+
+				sbDrawText (surface, pos.x, pos.y, subtext.c_str(), subtext.size());
+			}
+			else if ( type != sbItem::TYPE_SPACE )
+			{
+				sbAssert(true);
+			}
+		}
+	}
+}

Modified: trunk/src/SlideBible/sbItem.h
===================================================================
--- trunk/src/SlideBible/sbItem.h	2010-04-09 17:38:27 UTC (rev 231)
+++ trunk/src/SlideBible/sbItem.h	2010-04-09 17:44:00 UTC (rev 232)
@@ -22,7 +22,7 @@
 #include "sbBase.h"
 
 /*
-	sbItem should have type,                    content, and parameter
+	sbItem should have type,                  content, and parameter
 		verse                                 verse_id (indicates its position in Bible)
 		goVerse                               verse_id
 		title                                 no
@@ -32,7 +32,7 @@
 		book_select                           verse_id
 		text_field
 		goView                                view_type
-		chapterTitle, bookTitle            verse_id
+		chapterTitle, bookTitle               verse_id
 
 	Examples of items:
 
@@ -78,6 +78,7 @@
 		TYPE_BUTTON_OPEN_SELECT_CHAPTER,
 		TYPE_BUTTON_OPEN_SELECT_VERSE,
 		TYPE_BUTTON_BOOKMARK,
+		TYPE_BUTTON_BOOKMARK_SMALL,
 		TYPE_BUTTON_BOOKMARK_GO,
 		TYPE_BUTTON_BOOKMARK_DELETE,
 		TYPE_BUTTON_BOOKMARK_POSITION,
@@ -85,12 +86,15 @@
 		TYPE_BUTTON_ADD_FAVORITE,
 		TYPE_GOTO_MODULES,
 		TYPE_GO_HISTORY,
+		TYPE_HISTORY,
 		TYPE_GO_READING
 	};
 	
 	sbItem( sbItem::TYPE type, const TCHAR * text, int width, long index = -1, int number = -1 );
 	~sbItem();
 
+	void                          render ( sbSurface surface, const sbRect & rect, sbTheme::ELEMENT::TYPE element ) const;
+
 	const TYPE                    type;
 
 	char                          style;

Modified: trunk/src/SlideBible/sbList.cpp
===================================================================
--- trunk/src/SlideBible/sbList.cpp	2010-04-09 17:38:27 UTC (rev 231)
+++ trunk/src/SlideBible/sbList.cpp	2010-04-09 17:44:00 UTC (rev 232)
@@ -13,13 +13,11 @@
  * General Public License for more details.
  ************************************************************************/
 
+#include "sbCore.h"
+#include <swversion.h>
 #include <time.h>
 
-#include <swversion.h>
 
-#include "sbCore.h"
-#include "sbList.h"
-
 #pragma warning ( disable : 4018 )
 #pragma warning ( disable : 4996 )
 
@@ -27,21 +25,22 @@
 {
 	itemCurrent = itemHover = itemEdit = itemSelected = NULL;
 
-	displace     = 0.0f;
-	
+	next = prev = NULL;
+
+	displace           = 0.0f;
 	module             = NULL;
 
-	next = prev = NULL;
+	attachedReading    = attachedHistory = -1;
 
-	attachedReading = attachedHistory = -1;
+	rect               = &Core->getRect();
 
-	rect = &Core->getSurface(sbCore::SURFACE::TYPE_LIST)->rect;
+	verseFirst         = verseLast      = NULL;
+	versesForward      = versesBackward = 0;
 
-	verseFirst    = verseLast      = NULL;
-	versesForward = versesBackward = 0;
-
 	listEndConstructed = listStartConstructed = true;
 
+	controlSelected    = -1;
+
 	switch(type)
 	{
 	case TYPE_SELECT_BOOK:
@@ -66,6 +65,7 @@
 	case TYPE_READINGS:
 	case TYPE_HISTORY:
 	case TYPE_BOOKMARKS:
+	case TYPE_SELECT_VERSE:
 		{
 			addControl(sbControl::TYPE_WIDE_CLOSE);
 		}
@@ -164,17 +164,20 @@
 	}
 }
 
-/*   sbList::render
-*   draw list
-*/
-void sbList::render ( sbSurface hdc , bool showPlace )
+/*  sbList::render
+ *  draw list
+ */
+void sbList::render ( sbSurface hdc , bool showPlace , int sideDisplacement )
 {
 	sbItem *oldItem , *workItem = itemCurrent;
-	sbRect workRect;
-	int screenHeight = displace;
+	sbRect workRect = *rect, selectedRect;
+	int screenHeight = (int)displace;
 
-	Core->getTheme()->drawElement ( hdc, rect, sbTheme::ELEMENT::BACKGROUND );
+	workRect.left  += sideDisplacement;
+	workRect.right += sideDisplacement;
 
+	Core->getTheme()->drawElement ( hdc, &workRect, sbTheme::ELEMENT::BACKGROUND );
+
 	while ( true )
 	{
 		if (workItem == NULL) break;
@@ -183,16 +186,8 @@
 
 		oldItem = workItem;
 
-		if (Core->getTheme()->ListSeparatorHeight > 0 && workItem->prev == NULL)
-		{
-			workRect        = *rect;
-			workRect.bottom = screenHeight;
-			workRect.top    = workRect.bottom - Core->getTheme()->ListSeparatorHeight;
-			Core->getTheme()->drawElement(hdc, &workRect, sbTheme::ELEMENT::SEPARATOR);
-		}
-
 		workRect       = *rect;
-		workRect.right = 0;
+		workRect.right = sideDisplacement;
 
 		// horizontal parse
 		while (workItem != NULL)
@@ -204,112 +199,67 @@
 			workRect.left   = workRect.right;
 			workRect.right  = workRect.left + workItem->width;
 
-			if ( workItem == itemHover )       element = sbTheme::ELEMENT::ITEM_HOVER;
-			else if (workItem == itemSelected) element = sbTheme::ELEMENT::ITEM_SELECTED;
-			else if (workItem->highlighted)    element = sbTheme::ELEMENT::ITEM_HIGHLIGHTED;
+			if ( workItem == itemHover )         element = sbTheme::ELEMENT::ITEM_PRESSED;
+			else if ( workItem->highlighted )    element = sbTheme::ELEMENT::ITEM_HIGHLIGHTED;
 
-			Core->getTheme()->drawElement( hdc, &workRect, element );
+			workItem->render(hdc,workRect,element);
 
-			if ( workItem->text.size() > 0 )
-			{
-				if ( workItem->subtext.size() > 0 )
-				{
-					sbPoint size = sbGetTextExtent(Core->getTheme()->styles[sbTheme::STYLE::STANZA].font,workItem->subtext.c_str(), workItem->subtext.size());
+			if ( workItem == itemSelected ) selectedRect = workRect;
 
-					sbSelectFont(hdc, Core->getTheme()->styles[sbTheme::STYLE::STANZA].font);
-					sbSelectColor(hdc, Core->getTheme()->ItemSubTextColor);
-
-					sbDrawText(hdc, workRect.left+((Core->getTheme()->itemLeftMargin-size.x)/2), workRect.top, workItem->subtext.c_str(), workItem->subtext.size());
-				}
-
-				sbSelectColor(hdc, Core->getTheme()->ItemTextColor);
-
-				int lx = 0;
-				int ly = workRect.top + Core->getTheme()->itemTopMargin;
-
-				for (int i=0; i < workItem->lines.size(); i++)
-				{
-					int x = lx + Core->getTheme()->itemLeftMargin + workRect.left;
-					int y = ly;
-
-					// possible BUG with center alignment and many text parts
-					if (workItem->center)
-						x += (workRect.width()-Core->getTheme()->itemLeftMargin-Core->getTheme()->itemRightMargin-workItem->lines[i].width)/2;
-
-					if (workItem->lines[i].newLine)
-					{lx = 0; ly += workItem->lines[i].height;}
-					else
-						lx += workItem->lines[i].width;
-
-					if (workItem->lines[i].count == 0) continue;
-
-					if (y + Core->getTheme()->styles[workItem->style].size >= workRect.bottom)
-						break;
-
-					if (y < rect->top - Core->getTheme()->styles[workItem->style].size)
-						continue;
-
-					sbSelectFont (hdc, Core->getTheme()->styles[workItem->lines[i].style].font);
-					sbDrawText (hdc, x, y, i == 0 ? workItem->text.c_str() : workItem->text.c_str() + workItem->lines[i].pos, workItem->lines[i].count);
-				}
-			}
-			else
-			{
-				if (workItem->subtext.size() > 0)
-				{
-					sbSelectFont(hdc, Core->getTheme()->styles[sbTheme::STYLE::BUTTON].font);
-					sbSelectColor(hdc, Core->getTheme()->ItemSubTextColor);
-
-					sbPoint sz = sbGetTextExtent(Core->getTheme()->styles[sbTheme::STYLE::BUTTON].font, workItem->subtext.c_str(), workItem->subtext.size());
-
-					sbDrawText (hdc, workRect.left+((workRect.width()-sz.x)/2), workRect.top+((workRect.height()-sz.y)/2), workItem->subtext.c_str(), workItem->subtext.size());
-				}
-				else if (workItem->type != sbItem::TYPE_SPACE)
-					sbAssert(true);
-			}
-
-			if (Core->getTheme()->ListSeparatorHeight > 0)
-			{
-				workRect.top    = workRect.bottom;
-				workRect.bottom = workRect.top + Core->getTheme()->ListSeparatorHeight;
-				Core->getTheme()->drawElement(hdc, &workRect, sbTheme::ELEMENT::SEPARATOR);
-			}
-
-			// TODO vertical separator
-
 			workItem = workItem->right;
 		}
 
 		workItem = oldItem;
 
-		if (Core->getTheme()->ListSeparatorHeight > 0)
+		if (Core->getTheme()->ListSeparatorHeight > 0 && workItem->next != NULL)
+		{
+			workRect.top    = workRect.bottom;
+			workRect.bottom = workRect.top + Core->getTheme()->ListSeparatorHeight;
+			workRect.left   = sideDisplacement;
+			workRect.right  = sideDisplacement+rect->width();
+
+			Core->getTheme()->drawElement(hdc, &workRect, sbTheme::ELEMENT::SEPARATOR);
+			
 			screenHeight += Core->getTheme()->ListSeparatorHeight;
+		}
 
 		screenHeight += workItem->height;
 
 		workItem = workItem->next;
 	}
 
-	//if (true)
-	//{
-	//	// debug redraw
-	//	static char frame = 0;
-	//	static int time = GetTickCount();
+	// scrolling
+	if (itemSelected == NULL)
+	{
+		if (displace >= 0)
+		{
+			needScroll = (int)-displace;
+			needFill = displace != 0 || screenHeight < rect->height();
+		}
+		else if (screenHeight < rect->height())
+		{
+			needScroll = rect->height() - screenHeight;
+			needFill = true;
+		}
+		else
+		{
+			needScroll = 0;
+			needFill = false;
+		}
 
-	//	/*workRect.top = 16+(frame*32);
-	//	workRect.bottom = 48+(frame*32);
-	//	workRect.left = 0;
-	//	workRect.right = 32;
-	//	FillRect(hdc, &workRect, Core->getTheme()->ListBackgroundBrush);
+		if ((needScroll > 0 && !listEndConstructed) || (needScroll < 0 && !listStartConstructed)) needScroll = 0;
+	}
+	else
+	{
+		// selection
+		if (selectedRect.width() > 0)
+		{
+			Core->getTheme()->drawFrame(hdc,&selectedRect);
+			needScroll = ((rect->height()/2)-((selectedRect.height()/2)+selectedRect.top));
+		}
+	}
 
-	//	if (++frame > 6) frame = 0;*/
-
-	//	printf ("Redraw:%03.03f\n", (GetTickCount()-time));
-
-	//	frame++;
-	//	time = GetTickCount();
-	//}
-
+	// banner
 	if ( showPlace && module != NULL )
 	{
 		sbPoint      ks;
@@ -327,7 +277,7 @@
 		sbSelectFont (hdc, Core->getTheme()->styles[sbTheme::STYLE::CAPTION].font );
 		ks = sbGetTextExtent (Core->getTheme()->styles[sbTheme::STYLE::CAPTION].font, kw, kl);
 
-		sbRect tempRect ((rect->right-ks.x)/2, (Core->getTheme()->scale/6)-(ks.y/2), (rect->right-ks.x)/2+ks.x, (Core->getTheme()->scale/6)-(ks.y/2)+ks.y);
+		sbRect tempRect ((rect->right-ks.x)/2+sideDisplacement, (Core->getTheme()->size/6)-(ks.y/2), (rect->right-ks.x)/2+ks.x+sideDisplacement, (Core->getTheme()->size/6)-(ks.y/2)+ks.y);
 
 		sbSelectFont ( hdc, Core->getTheme()->styles[sbTheme::STYLE::DESCRIPTION].font );
 
@@ -362,25 +312,6 @@
 		delete [] kw;
 		delete [] mw;
 	}
-
-	if (displace >= 0)
-	{
-		needScroll = -displace;
-		needFill = displace != 0 || screenHeight < rect->height();
-	}
-	else if (screenHeight < rect->height())
-	{
-		needScroll = rect->height() - screenHeight;
-		needFill = true;
-	}
-	else
-	{
-		needScroll = 0;
-		needFill = false;
-	}
-
-	if ((needScroll > 0 && !listEndConstructed) || (needScroll < 0 && !listStartConstructed))
-		needScroll = 0;
 }
 
 /*   sbList::scroll
@@ -389,9 +320,11 @@
  */
 bool sbList::scroll (float amount)
 {
+	//sbMessage("sbList scroll %f\n",amount);
+
 	if (itemCurrent == NULL) return false;
 
-	int oldDisplace = displace;
+	int oldDisplace = (int)displace;
 
 	// don't allow scroll further then list is
 	if (amount < 0 && itemCurrent->next == NULL && itemCurrent->height+Core->getTheme()->ListSeparatorHeight+displace+amount < 0)
@@ -407,7 +340,7 @@
 
 	if ( fabs(amount) > rect->height()/3 )
 	{
-		amount = amount > 0 ? rect->height()/3 : -rect->height()/3;
+		amount = amount > 0.0f ? rect->height()/3.0f : -rect->height()/3.0f;
 	}
 	
 	displace += amount;
@@ -425,7 +358,7 @@
 	if (itemCurrent == NULL) return NULL;
 
 	sbItem* i = itemCurrent;
-	int top = displace;
+	int top = (int)displace;
 
 	while (i != NULL && top < rect->height())
 	{
@@ -466,6 +399,8 @@
 
 	itemHover = getItem(x,y);
 
+	if (itemSelected != NULL) itemSelected = NULL;
+
 	if (itemHover != NULL)
 	{
 		if (itemHover->type == sbItem::TYPE_VERSE)
@@ -475,7 +410,7 @@
 
 			Core->currentVerse.copyFrom ( place );
 
-			if (attachedReading >= 0) Core->features.updateReading(attachedReading,module->Name(),place.Index());
+			//if (attachedReading >= 0) Core->features.updateReading(attachedReading,module->Name(),place.Index());
 			if (attachedHistory >= 0) Core->features.updateHistory(attachedHistory,place.Index());
 		}
 
@@ -519,6 +454,11 @@
 
 	if (itemEdit != NULL && item != itemEdit) setEditMode (false);
 
+	onItem(item);
+}
+
+void sbList::onItem ( sbItem * item )
+{
 	switch (item->type)
 	{
 	case sbItem::TYPE_GOTO_MODULES:
@@ -527,6 +467,7 @@
 		}
 		break;
 
+	case sbItem::TYPE_HISTORY:
 	case sbItem::TYPE_GO_HISTORY:
 		{
 			Core->goVerse       = true;
@@ -539,6 +480,7 @@
 		break;
 
 	case sbItem::TYPE_BUTTON_BOOKMARK:
+	case sbItem::TYPE_BUTTON_BOOKMARK_SMALL:
 		{
 			Core->goVerse       = true;
 			Core->currentModule = Core->defaultModule;
@@ -561,7 +503,7 @@
 			{
 				// add chapters
 				sbItem *tmpItem = item;
-				sword::VerseKey workKey ( Core->currentModule->getKey() );
+				sword::VerseKey workKey ( Core->currentVerse );
 				workKey.Index( item->index );
 
 				for (int i=0; i < workKey.getChapterMax(); i++)
@@ -603,8 +545,13 @@
 	case sbItem::TYPE_BUTTON_SELECTION_CHAPTER:
 		{
 			Core->currentVerse.Index ( item->index );
+
+			sbMessage ("Core->keypadController %i\n",Core->keypadController);
 			
-			addControl((sbControl::TYPE)(sbControl::TYPE_MENU_SET_VERSE+Core->currentVerse.getVerseMax()));
+			if (Core->keypadController)
+				Core->switchList(sbList::TYPE_SELECT_VERSE);
+			else
+				addControl((sbControl::TYPE)(sbControl::TYPE_MENU_SET_VERSE+Core->currentVerse.getVerseMax()));
 		}
 		break;
 
@@ -623,6 +570,9 @@
 			Core->goVerse       = true;
 			Core->currentModule = setModule;
 
+			Core->currentModule->setKey ( Core->currentVerse );
+			Core->currentVerse.copyFrom ( Core->currentModule->getKey() );
+
 			Core->redraw();
 		}
 		break;
@@ -661,11 +611,11 @@
 
 	while ( ! * abort )
 	{
-		int      displace  = sbList::displace;
+		int      displace  = (int)sbList::displace;
 		sbItem * item      = itemCurrent;
 		bool     atEnd     = false;
 		
-		// delete unnecessary items
+		// delete unnecessary items, it should be in background thread ...
 		if ( versesForward + versesBackward > Core->versesOptimal )
 		{
 			int countDeleted = 0;
@@ -717,22 +667,16 @@
 
 				TCHAR * text = (TCHAR*) module->RenderText();
 
-				int length = _tcslen ( text );
+				if ( _tcslen ( text ) == 0 ) break;
 
-				if ( length == 0 ) break;
-				
-				TCHAR * add = new TCHAR [ length + 1 ];
-
-				for ( int i=0; i <= length; i++ ) add[i] = text[i];
-
 				int oldHeight = item->height;
 
-				item->setText ( add );
+				item->setText ( text );
 
-				delete [] add;
-
 				item->expanding = item->height;
 				item->height    = oldHeight;
+
+				break; // start again
 			}
 
 			if (atEnd && last->next != NULL)
@@ -749,7 +693,7 @@
 			}
 			else
 			{
-				sbSleep(50);
+				sbSleep(50); // there should be sleep in thread, so thread will not grab all system resources
 				break;
 			}
 
@@ -805,9 +749,12 @@
 		{
 			sbAssert ( this->type != sbList::TYPE_SELECT_BOOK );
 			
+			Core->goVerse = true;
 			Core->currentVerse.setVerse ( type - sbControl::TYPE_SET_VERSE );
-			Core->goVerse = true;
 
+			if (Core->currentModule == NULL)
+				Core->currentModule = Core->defaultModule;
+
 			removeControl ( sbControl::TYPE_MENU_CURRENT );
 			Core->switchList ( sbList::TYPE_MODULE_VIEW );
 		}
@@ -825,9 +772,9 @@
 
 	if ( controls.back()->isMenu() )
 	{
-		sbAssert(Core->getSurface(sbCore::SURFACE::TYPE_WHOLE)->fade || Core->getInput()->block);
+		sbAssert(Core->fadeSurface || Core->getInput()->block);
 
-		Core->getSurface(sbCore::SURFACE::TYPE_WHOLE)->fade = true;
+		Core->fadeSurface = true;
 		Core->getInput()->block = true;
 	}
 }
@@ -840,9 +787,9 @@
 		{
 			if ((*it)->isMenu())
 			{
-				sbAssert(!Core->getSurface(sbCore::SURFACE::TYPE_WHOLE)->fade || !Core->getInput()->block);
+				sbAssert(!Core->fadeSurface || !Core->getInput()->block);
 
-				Core->getSurface(sbCore::SURFACE::TYPE_WHOLE)->fade = false;
+				Core->fadeSurface = false;
 				Core->getInput()->block = false;
 			}
 
@@ -858,57 +805,70 @@
 	{
 	case sbCore::TIMER_REDRAW:
 		{
+			//static int c = 0; if (c++ < 20) return; c = 0;
+
 			// Expand items heights
-			if (itemCurrent != NULL && type == sbList::TYPE_MODULE_VIEW)
+			if ( itemCurrent != NULL && type == sbList::TYPE_MODULE_VIEW )
 			{
 				const int halfscreen = rect->height()/2;
 
-				for ( int dir=0; dir < 2; dir++ )
+				for ( int direction = 0; direction < 2; direction++ )
 				{
-					sbItem* item = itemCurrent;
-					int displace = sbList::displace;
+					sbItem * item = itemCurrent;
+					int y = (int)displace;
 
 					while ( item != NULL )
 					{
-						if (item->expanding != 0 && !( dir == 1 && item == itemCurrent ) )
+						if ( item->expanding != 0 && !( direction == 1 && item == itemCurrent ) )
 						{
-							if (displace < -item->height || displace > rect->height())
+							// out of screen
+							if ( y < -(item->height+Core->getTheme()->ListSeparatorHeight) || y > rect->height() )
 							{
 								item->height = item->expanding;
 								item->expanding = 0;
 							}
 							else
 							{
-								const int add = min((int)ceil((item->expanding-item->height)*0.3f)+(Core->getTheme()->scale/100),item->expanding-item->height);
+								const int add = min((int)ceil((item->expanding-item->height)*0.2f),item->expanding-item->height);
 
 								item->height += add;
 
 								Core->redraw();
 
-								if (item->height >= item->expanding)
+								if ( item->height >= item->expanding )
 								{
-									item->height = item->expanding;
+									sbAssert(item->height > item->expanding);
+
+									item->height    = item->expanding;
 									item->expanding = 0;
 								}
 
-								if (displace < halfscreen)
+								if ( y < halfscreen )
 								{
-									const float cadd = add*((halfscreen-displace)/(float)halfscreen);
-									scroll(-cadd);
-									displace -= (int)cadd;
+									if ( y + item->height < halfscreen )
+									{
+										scroll ( -add );
+										y -= add;
+									}
+									else
+									{
+										const float cd = add * ((halfscreen-y)/(float)halfscreen);
+										scroll ( -cd );
+										y -= (int)cd;
+									}
 								}
 							}
 						}
 
-						if (dir > 0)
+						if ( direction > 0 )
 						{
-							displace += item->height;
+							y += item->height;
 							item = item->next;
 						}
 						else
 						{
 							item = item->prev;
-							if (item != NULL) displace -= item->height;
+							if ( item != NULL ) y -= item->height;
 						}
 					}
 				}
@@ -1081,10 +1041,64 @@
  */
 void sbList::onActivate ( )
 {
+	static TCHAR tempText [128];
+
 	sbSetSip ( itemEdit != NULL );
 
+	itemSelected = NULL;
+
 	switch (type)
 	{
+	case TYPE_SELECT_VERSE:
+		{
+			clear ();
+
+			_sntprintf(tempText,128,L"%S %i",Core->currentVerse.getBookName(),Core->currentVerse.getChapter());
+
+			itemCurrent = new sbItem (sbItem::TYPE_HEADER, tempText, rect->width(), Core->currentVerse.Index());
+
+			// add verses
+			sbItem * tempItem = itemCurrent;
+
+			sword::VerseKey workKey ( Core->currentVerse );
+
+			for (int i=0; i < workKey.getVerseMax(); i++)
+			{
+				workKey.setVerse(i+1);
+				TCHAR text[8];
+				_itot(workKey.getVerse(), text, 10);
+
+				sbItem * item = new sbItem (sbItem::TYPE_BUTTON_BOOKMARK_SMALL, text, rect->width()/4, workKey.Index());
+
+				item->center = true;
+
+				if (tempItem->type == sbItem::TYPE_BUTTON_BOOKMARK_SMALL &&
+					(tempItem->right == NULL || tempItem->right->right == NULL || tempItem->right->right->right == NULL))
+				{
+					sbItem *last = tempItem;
+					while(last->right != NULL) last = last->right;
+					last->attach(item, sbItem::RIGHT);
+				}
+				else
+				{
+					tempItem->attach (item, sbItem::NEXT);
+					tempItem = tempItem->next;
+				}
+			}
+
+			// add space
+			if  (tempItem->type == sbItem::TYPE_BUTTON_BOOKMARK_SMALL)
+			{
+				if (tempItem->right == NULL)
+					tempItem->attach(new sbItem (sbItem::TYPE_SPACE, L"", rect->width()/4*3), sbItem::RIGHT);
+				else if (tempItem->right->right == NULL)
+					tempItem->right->attach(new sbItem (sbItem::TYPE_SPACE, L"", rect->width()/4*2), sbItem::RIGHT);
+				else if (tempItem->right->right->right == NULL)
+					tempItem->right->right->attach(new sbItem (sbItem::TYPE_SPACE, L"", rect->width()/4), sbItem::RIGHT);
+			}
+		}
+		break;
+
 	case TYPE_HOME:
 		{
 			float saveDisplacement = 0;
@@ -1166,10 +1180,8 @@
 				itemCurrent = itemCurrent->next;
 			}
 
-			TCHAR text [128];
-
-			_sntprintf(text,128,L"About :\nVersion built on %S\n Using SWORD version %S",__DATE__,sword::SWVersion::currentVersion.getText());
-			itemCurrent->attach(new sbItem (sbItem::TYPE_DESCRIPTION, text, rect->width()), sbItem::NEXT);
+			_sntprintf(tempText,128,L"About :\nVersion built on %S\n Using SWORD version %S",__DATE__,sword::SWVersion::currentVersion.getText());
+			itemCurrent->attach(new sbItem (sbItem::TYPE_DESCRIPTION, tempText, rect->width()), sbItem::NEXT);
 			itemCurrent = itemCurrent->next;
 			itemCurrent->center = true;
 
@@ -1194,7 +1206,7 @@
 				displace = rect->height()*2.0f/5.0f;
 
 				// adding blank verses starts automatically in sbList::onTimer(sbCore::TIMER_BEFORE_REDRAW)
-				// filling with text occurs in sbList::updateVerses
+				// filling with text occurs in sbList::process in another thread
 
 				// update history
 				attachedHistory = Core->features.addHistory(module->Name(),place.Index());
@@ -1347,74 +1359,116 @@
 
 	case TYPE_HISTORY:
 		{
-			clear();
+			TCHAR tempText [128];
 
-			for (int i=Core->features.history.size()-1; i >= 0 ; i--)
-			{
-				sword::VerseKey workKey ( Core->getSword()->getModule(Core->features.history[i].module)->getKey() );
-				workKey.Index (Core->features.history[i].placeEnd);
+			bool createdNow = false;
+			bool createdToday = false;
+			bool createdYesterday = false;
+			bool createdWeek = false;
+			bool createdOlder = false;
 
-				TCHAR * text = new TCHAR [strlen(workKey.getText())+1];
-				mbstowcs (text, workKey.getText() , strlen(workKey.getText())+1);
+			time_t startedToday;
+			time_t startedYesterday;
+			time_t startedWeek;
 
-				sbItem * item = new sbItem (sbItem::TYPE_GO_HISTORY, text, rect->width(), i);
+			time(&startedToday);
 
-				if ( itemCurrent == NULL )
-				{
-					itemCurrent = item;
-				}
-				else
-				{
-					itemCurrent->attach(item,sbItem::PIN::NEXT);
-					itemCurrent = itemCurrent->next;
-				}
+			tm date = *localtime(&startedToday);
 
-				delete [] text;
-			}
+			date.tm_hour = 0;
+			date.tm_min  = 0;
+			date.tm_sec  = 0;
 
-			if ( itemCurrent != NULL ) while ( itemCurrent->prev != NULL ) itemCurrent = itemCurrent->prev;
-		}
-		break;
+			startedToday = mktime(&date);
 
-	case TYPE_BOOKMARKS:
-	case TYPE_READINGS:
-		{
-			/*sbCollection * collection = Core->getCollection ( type == TYPE_BOOKMARKS ? "bookmarks" : type == TYPE_HISTORY ? "history" : "readings" );
+			date.tm_mday -= 1;
 
-			if ( collection != NULL )
+			startedYesterday = mktime(&date);
+
+			date.tm_mday -= 6;
+
+			startedWeek = mktime(&date);
+
+			clear();
+			
+			for (int h = Core->features.history.size()-1; h >= 0 ; h--)
 			{
-				sword::VerseKey workKey ( Core->defaultModule->getKey() );
+				sbFeatures::History * hi = &Core->features.history[h];
 
-				clear();
+				sword::VerseKey workKey ( Core->getSword()->getModule(hi->module)->getKey() );
+				workKey.Index (hi->placeEnd);
 
-				for (int i=0; i < collection->size(); i++)
-				{
-					const char * verse = collection->get(i).verse;
+				_sntprintf(tempText,128,L"%S\n<s t=\"5\">%i:%i\n</s><s t=\"6\">%S</s>",workKey.getBookName(),workKey.getChapter(),workKey.getVerse(),hi->module);
 
-					workKey.setText ( verse );
+				sbItem * timeHeader = NULL;
 
-					TCHAR * text = new TCHAR [strlen(verse)+1];
-					mbstowcs (text, verse , strlen(verse)+1);
+				if (hi->visitStart > Core->systemStarted)
+				{
+					if(!createdNow)
+					{
+						timeHeader = new sbItem (sbItem::TYPE_DESCRIPTION, L"Now", rect->width());
+						createdNow = true;
+					}
+				}
+				else if (hi->visitStart > startedToday)
+				{
+					if(!createdToday)
+					{
+						timeHeader = new sbItem (sbItem::TYPE_DESCRIPTION, L"Today", rect->width());
+						createdToday = true;
+					}
+				}
+				else if (hi->visitStart > startedYesterday)
+				{
+					if(!createdYesterday)
+					{
+						timeHeader = new sbItem (sbItem::TYPE_DESCRIPTION, L"Yesterday", rect->width());
+						createdYesterday = true;
+					}
+				}
+				else if (hi->visitStart > startedWeek)
+				{
+					if(!createdWeek)
+					{
+						timeHeader = new sbItem (sbItem::TYPE_DESCRIPTION, L"Last Week", rect->width());
+						createdWeek = true;
+					}
+				}
+				else if (!createdOlder)
+				{
+					timeHeader = new sbItem (sbItem::TYPE_DESCRIPTION, L"Older", rect->width());
+					createdOlder = true;
+				}
 
-					sbItem * item = new sbItem (sbItem::TYPE_BUTTON_BOOKMARK, text, rect->width(), workKey.Index());
+				if (timeHeader != NULL)
+				{
+					timeHeader->center = true;
 
-					delete [] text;
-
 					if ( itemCurrent == NULL )
 					{
-						itemCurrent = item;
+						itemCurrent = timeHeader;
 					}
 					else
 					{
-						itemCurrent->attach (item,sbItem::PIN::NEXT);
+						itemCurrent->attach(timeHeader,sbItem::PIN::NEXT);
 						itemCurrent = itemCurrent->next;
 					}
+				}
+				
+				sbItem * item = new sbItem (sbItem::TYPE_HISTORY, tempText, rect->width(), h);
 
+				if ( itemCurrent == NULL )
+				{
+					itemCurrent = item;
 				}
+				else
+				{
+					itemCurrent->attach(item,sbItem::PIN::NEXT);
+					itemCurrent = itemCurrent->next;
+				}
+			}
 
-				while ( itemCurrent->prev != NULL ) itemCurrent = itemCurrent->prev;
-			}*/
-
+			if ( itemCurrent != NULL ) while ( itemCurrent->prev != NULL ) itemCurrent = itemCurrent->prev;
 		}
 		break;
 
@@ -1476,27 +1530,95 @@
 {
 	switch ( key )
 	{
+	case 0x0D: //VK_RETURN
+		if (itemSelected != NULL)
+		{
+			onItem(itemSelected);
+			Core->redraw();
+		}
+
+		if (controlSelected != -1)
+		{
+			controls[controlSelected]->onPressed();
+		}
+
+		break;
+
 	case 0x25: // VK_LEFT
-		Core->switchList(PIN_PREV);
+		if (itemSelected == NULL && controlSelected == 0 && type == sbList::TYPE_MODULE_VIEW)
+		{
+			Core->switchList(PIN_PREV);
+		}
+		else
+		{
+			if (itemSelected != NULL && itemSelected->left != NULL)
+			{
+				itemSelected = itemSelected->left;
+			}
+			else
+			{
+				itemSelected = NULL;
+
+				if (controlSelected == -1)
+					controlSelected = controls.size()-1;
+				else if (controlSelected > 0)
+					controlSelected--;
+			}
+
+			Core->redraw();
+		}
 		return true;
 
 	case 0x27: // VK_RIGHT
-		Core->switchList(PIN_NEXT);
-		return true;
+		if (itemSelected == NULL && controlSelected == controls.size()-1 && type == sbList::TYPE_MODULE_VIEW)
+		{
+			Core->switchList(PIN_NEXT);
+		}
+		else
+		{
+			if (itemSelected != NULL && itemSelected->right != NULL)
+			{
+				itemSelected = itemSelected->right;
+			}
+			else
+			{
+				itemSelected = NULL;
 
+				if (controlSelected == -1)
+					controlSelected = controls.size()-1;
+				else if (controlSelected < controls.size()-1)
+					controlSelected++;
+			}
+
+			Core->redraw();
+		}
+		break;
+
 	case 0x28: // VK_DOWN
 		if ( itemSelected == NULL )
 			itemSelected = itemCurrent;
 		else if ( itemSelected->next != NULL )
 			itemSelected = itemSelected->next;
-		return true;
+		controlSelected = -1;
+		Core->redraw();
+		break;
 
 	case 0x26: // VK_UP
 		if ( itemSelected == NULL )
 			itemSelected = itemCurrent;
 		else if ( itemSelected->prev != NULL )
 			itemSelected = itemSelected->prev;
-		return true;
+		controlSelected = -1;
+		Core->redraw();
+		break;
+
+	case 0x1B: //VK_ESCAPE
+		sbExit(1);
+		break;
+
+	default:
+		return false;
 	}
-	return false;
+
+	return true;
 }

Modified: trunk/src/SlideBible/sbList.h
===================================================================
--- trunk/src/SlideBible/sbList.h	2010-04-09 17:38:27 UTC (rev 231)
+++ trunk/src/SlideBible/sbList.h	2010-04-09 17:44:00 UTC (rev 232)
@@ -39,6 +39,7 @@
 		TYPE_MODULE_VIEW,
 		TYPE_SELECT_MODULE,
 		TYPE_SELECT_BOOK,
+		TYPE_SELECT_VERSE,
 		TYPE_FOLDER_VIEW,
 		TYPE_FILE_VIEW,               // html / txt / rtf / doc
 		TYPE_HOME,
@@ -50,6 +51,9 @@
 		TYPE_SEARCH_OPTIONS,
 		TYPE_SEARCH_RESULTS,
 		//TYPE_NAVIGATION,              // virtual
+		TYPE_MENU_EXIT,
+		TYPE_MENU_SELECT_VERSE,
+		TYPE_MENU_SELECT_CHAPTER,
 		TYPES_COUNT
 	};
 	
@@ -68,11 +72,12 @@
 	void                      onTimer             ( const int timer );
 	void                      onActivate          ( );
 	bool                      onControl           ( sbControl::TYPE type );
+	void                      onItem              ( sbItem * item );
 
 	// methods
 	void                      attach              ( sbList * list, sbList::TYPE pin );
 	bool                      scroll              ( float amount );
-	void                      render              ( sbSurface rc , bool showPlace = false );
+	void                      render              ( sbSurface rc , bool showPlace = false , int sideDisplacement = 0 );
 
 	float                     displace;
 	//float                     displacePart;
@@ -98,6 +103,7 @@
 	sbItem                   *itemHover;
 	sbItem                   *itemSelected;
 
+
 	void                      setEditMode         ( sbItem * item );
 	sbItem                   *itemEdit;
 	int                       itemEditCursor;
@@ -121,9 +127,12 @@
 
 	std::vector<sbControl*>   controls;
 
+
 	const sbRect             *rect;
 
 public:
+	int                       controlSelected;
+
 	sword::SWModule          *module;
 	sword::VerseKey           place;
 

Modified: trunk/src/SlideBible/sbTheme.cpp
===================================================================
--- trunk/src/SlideBible/sbTheme.cpp	2010-04-09 17:38:27 UTC (rev 231)
+++ trunk/src/SlideBible/sbTheme.cpp	2010-04-09 17:44:00 UTC (rev 232)
@@ -23,68 +23,67 @@
 
 void sbTheme::init()
 {
-	sword::SWConfig config (".\\theme.conf");
-	config.Load();
+	XMLNode xml = XMLNode::openFileHelper(".\\theme.xml");
 
-	const sbRect * screenRect = &Core->getSurface(sbCore::SURFACE::TYPE_WHOLE)->rect;
-	scale = min(screenRect->height(), screenRect->width());
+	//const sbRect * screenRect = &Core->Surface(sbCore::SURFACE::TYPE_WHOLE)->rect;
+	size = min(Core->getRect().height(), Core->getRect().width());
 
-	// colors
-	ItemTextColor        = sbColor(config["Color"].getWithDefault("ItemText", "14141400"));
-	ControlsColor        = sbColor(config["Color"].getWithDefault("ControlsText", "14141400"));
-	ItemMenuTextColor    = sbColor(config["Color"].getWithDefault("MenuText", "E0E0E000"));
-	ItemSubTextColor     = sbColor(config["Color"].getWithDefault("ItemSubText", "AAAAAA00"));
+	ItemTextColor       = sbColor(xml.getChildNodeByPath("List/Item/Text"   ).getAttribute("color","141414FF"));
+	ItemSubTextColor    = sbColor(xml.getChildNodeByPath("List/Item/SubText").getAttribute("color","AAAAAAFF"));
+	ControlsColor       = sbColor(xml.getChildNodeByPath("Panel/Text"       ).getAttribute("color","F4F4F4FF"));
+	ItemMenuTextColor   = sbColor(xml.getChildNodeByPath("Menu/Text"        ).getAttribute("color","E0E0E0FF"));
+	SelectionFrameColor = sbColor(xml.getChildNodeByPath("Selection"        ).getAttribute("color","FFE020FF"));
+	FadingColor         = sbColor(xml.getChildNodeByPath("Background/Fade"  ).getAttribute("color","00000050"));
+	
+	itemMargins.top     = size*atof(xml.getChildNodeByPath("List/Item/Margins").getAttribute("top",   "0.01"));
+	itemMargins.left    = size*atof(xml.getChildNodeByPath("List/Item/Margins").getAttribute("left",  "0.1"));
+	itemMargins.bottom  = size*atof(xml.getChildNodeByPath("List/Item/Margins").getAttribute("bottom","0.02"));
+	itemMargins.right   = size*atof(xml.getChildNodeByPath("List/Item/Margins").getAttribute("right", "0.08"));
 
-	itemTopMargin        = scale/atof(config["Size"].getWithDefault("itemTopMarginDiv",    "200.0"));
-	itemLeftMargin       = scale/atof(config["Size"].getWithDefault("itemLeftMarginDiv",   "10.0"));
-	itemBottomMargin     = scale/atof(config["Size"].getWithDefault("itemBottomMarginDiv", "100.0"));
-	itemRightMargin      = scale/atof(config["Size"].getWithDefault("itemRightMarginDiv",  "14.0"));
+	ListSeparatorHeight = size*atof(xml.getChildNodeByPath("List/Separator").getAttribute("height","0.01"));
+	BannerBorderSize    = size*atof(xml.getChildNodeByPath("List/Banner"   ).getAttribute("border","0.04"));
+	PanelSize           = size*atof(xml.getChildNodeByPath("Panel"         ).getAttribute("size","0.15"));
+	SelectionFrameWidth = size*atof(xml.getChildNodeByPath("Selection"     ).getAttribute("width","0.012"));
 
-	fingerSize           = scale/atof(config["Size"].getWithDefault("fingerSizeDiv",       "6.0"));
-
-	ListSeparatorHeight  = scale*atof(config["Element.Separator"].getWithDefault("SizeDiv", "0.0"));
-	BannerBorderSize     = scale/atof(config["Element.Banner"].getWithDefault("BorderDiv", "25.0"));
-
-	// elements
 	for (int i=0; i<ELEMENT::COUNT; i++)
 	{
-		const char * data;
+		XMLNode e;
 
 		if (i == ELEMENT::ITEM)
-			data   = config["Element"].getWithDefault("Item",            "<e><s c=\"FFFFFFFF\"/></e>");
-		else if (i == ELEMENT::ITEM_SELECTED)
-			data   = config["Element"].getWithDefault("ItemSelected",    "<e><s c=\"AAFFFF00\"/></e>");
+			e = xml.getChildNodeByPath("List/Item/e",           "<e><s c=\"FFFFFF00\"/></e>");
 		else if (i == ELEMENT::ITEM_HIGHLIGHTED)
-			data   = config["Element"].getWithDefault("ItemHighlighted", "<e gradient=\"1\" vertical=\"1\"><s c=\"FFFFFFFF\"/><s c=\"FF55AA00\"/><s c=\"FFFFFFFF\"/></e>");
-		else if (i == ELEMENT::ITEM_HOVER)
-			data   = config["Element"].getWithDefault("ItemHover",       "<e gradient=\"1\" vertical=\"1\"><s c=\"FFFFFFFF\"/><s c=\"FFFF0000\"/><s c=\"FFFFFFFF\"/></e>");
+			e = xml.getChildNodeByPath("List/ItemHighlighted/e","<e gradient=\"1\" vertical=\"1\"><s c=\"FF55AA30\"/><s c=\"FF55AA60\"/><s c=\"FF55AA30\"/></e>");
+		else if (i == ELEMENT::ITEM_PRESSED)
+			e = xml.getChildNodeByPath("List/ItemHover/e",      "<e gradient=\"1\" vertical=\"1\"><s c=\"FFFF0030\"/><s c=\"FFFF0060\"/><s c=\"FFFF0030\"/></e>");
 		else if (i == ELEMENT::SEPARATOR)
-			data   = config["Element"].getWithDefault("Separator",       "<e><s c=\"CDCDCD00\"/></e>");
+			e = xml.getChildNodeByPath("List/Separator/e",      "<e gradient=\"1\" vertical=\"0\"><s c=\"D8D8D880\"/><s c=\"FFFFFF80\"/><s c=\"D8D8D880\"/></e>");
 		else if (i == ELEMENT::BACKGROUND)
-			data   = config["Element"].getWithDefault("Background",      "<e gradient=\"1\" vertical=\"1\"><s c=\"CBDADD00\"/><s c=\"FFFFFF00\"/></e>");
-		else if (i == ELEMENT::CONTROL)
-			data   = config["Element"].getWithDefault("Control",         "<e gradient=\"1\" vertical=\"1\"><s c=\"FFFFFF00\"/><s c=\"CBDADD00\"/></e>");
-		else if (i == ELEMENT::CONTROL_PRESSED)
-			data   = config["Element"].getWithDefault("ControlPressed",  "<e gradient=\"1\" vertical=\"1\"><s c=\"CBDADD00\"/><s c=\"FFFFFF00\"/></e>");
+			e = xml.getChildNodeByPath("Background/e",          "<e gradient=\"1\" vertical=\"1\"><s c=\"CFCFCFFF\"/><s c=\"FFFFFFFF\"/></e>");
+		else if (i == ELEMENT::MENU)
+			e = xml.getChildNodeByPath("Menu/Button/e",         "<e gradient=\"1\" vertical=\"1\"><s c=\"D0D0D0FF\"/><s c=\"969696FF\"/></e>");
+		else if (i == ELEMENT::MENU_PRESSED)
+			e = xml.getChildNodeByPath("Menu/ButtonPressed/e",  "<e gradient=\"1\" vertical=\"1\"><s c=\"CBDADDFF\"/><s c=\"FFFFFFFF\"/></e>");
+		else if (i == ELEMENT::PANEL)
+			e = xml.getChildNodeByPath("Panel/e",               "<e gradient=\"1\" vertical=\"1\"><s c=\"A9A9A9FF\"/><s c=\"A9A9A9FF\" p=\"16\"/><s c=\"D0D0D0FF\" p=\"50\"/><s c=\"969696FF\"/></e>");
+		else if (i == ELEMENT::PANEL_PRESSED)
+			e = xml.getChildNodeByPath("Panel/Pressed/e",       "<e gradient=\"1\" vertical=\"1\"><s c=\"A9A9A9FF\"/><s c=\"A9A9A9FF\" p=\"16\"/><s c=\"969696FF\" p=\"50\"/><s c=\"D0D0D0FF\"/></e>");
 		else if (i == ELEMENT::TAPPED)
-			data   = config["Element"].getWithDefault("Tapped",          "<e><s c=\"FF660000\"/></e>");
+			e = xml.getChildNodeByPath("Mouse/LongPress/e",     "<e><s c=\"FF6600FF\"/></e>");
 		else if (i == ELEMENT::BANNER)
-			data   = config["Element"].getWithDefault("Banner",          "<e gradient=\"1\" vertical=\"1\"><s c=\"CBDADD00\"/><s c=\"B4CFD600\"/><s c=\"CBDADD00\"/></e>");
+			e = xml.getChildNodeByPath("List/Banner/e",         "<e><s c=\"B6B6B6FF\"/></e>");
 		else
 			sbAssert ( true );
 
-		XMLNode xml = XMLNode::parseString(data);
+		if (e.getAttribute("gradient") != NULL && !strcmp(e.getAttribute("gradient"),"1")) elements[i].gradient = true; else elements[i].gradient = false;
+		if (e.getAttribute("vertical") != NULL && !strcmp(e.getAttribute("vertical"),"1")) elements[i].vertical = true; else elements[i].vertical = false;
 
-		if (xml.getAttribute("gradient") != NULL && !strcmp(xml.getAttribute("gradient"),"1")) elements[i].gradient = true; else elements[i].gradient = false;
-		if (xml.getAttribute("vertical") != NULL && !strcmp(xml.getAttribute("vertical"),"1")) elements[i].vertical = true; else elements[i].vertical = false;
-
-		for (int p = 0; p < xml.nChildNode("s"); p++)
+		for (int p = 0; p < e.nChildNode("s"); p++)
 		{
-			XMLNode n = xml.getChildNode("s",p);
+			XMLNode n = e.getChildNode("s",p);
 
-			sbColor color ( n.getAttribute("c") == NULL ? "00000000" : n.getAttribute("c") );
+			sbColor color (n.getAttribute("c","000000FF"));
 
-			int pos = 1000*p/max(xml.nChildNode("s")-(elements[i].gradient ? 1 : 0),1);
+			int pos = 1000*p/max(e.nChildNode("s")-(elements[i].gradient ? 1 : 0),1);
 
 			if (n.getAttribute("p") != NULL) pos = atoi(n.getAttribute("p"));
 
@@ -92,64 +91,65 @@
 		}
 	}
 
-	// fonts
-	const char * fontName = config["Font"].getWithDefault("Item", "Tahoma");
+	const char * cfont = xml.getChildNodeByPath("List/Item/Text").getAttribute("face","Tahoma");
+	
+	TCHAR * tfont = new TCHAR [strlen(cfont)+1];
 
-	TCHAR *fontNameT = new TCHAR [strlen(fontName)+1];
+	for (int i = 0; i <= strlen ( cfont ); i++) tfont [i] = cfont[i];
 
-	for (int i = 0; i <= strlen ( fontName ); i++) fontNameT[i] = fontName[i];
-
-	styles[STYLE::TEXT].size          = scale/(atof(config["Size"].getWithDefault("TextDiv", "12.0")));
-	styles[STYLE::TEXT].font          = sbMakeFont(styles[STYLE::TEXT].size,         fontNameT, false, false);
+	styles[STYLE::TEXT].size          = size*(atof(xml.getChildNodeByPath("List/Item/Text").getAttribute("fontSize","0.08")));
+	styles[STYLE::TEXT].font          = sbMakeFont(styles[STYLE::TEXT].size,         tfont, false, false);
 	
 	styles[STYLE::TEXT_ITALIC].size   = styles[STYLE::TEXT].size;
-	styles[STYLE::TEXT_ITALIC].font   = sbMakeFont(styles[STYLE::TEXT_ITALIC].size,  fontNameT, false, true);
+	styles[STYLE::TEXT_ITALIC].font   = sbMakeFont(styles[STYLE::TEXT_ITALIC].size,  tfont, false, true);
 	
-	styles[STYLE::BUTTON].size        = scale/(atof(config["Size"].getWithDefault("ButtonTextDiv", "11.0")));
-	styles[STYLE::BUTTON].font        = sbMakeFont(styles[STYLE::BUTTON].size,       fontNameT, false, false);
+	styles[STYLE::BUTTON].size        = size*(atof(xml.getChildNodeByPath("Menu").getAttribute("fontSize","0.093")));
+	styles[STYLE::BUTTON].font        = sbMakeFont(styles[STYLE::BUTTON].size,       tfont, true, false);
 	
-	styles[STYLE::BUTTON_SMALL].size  = scale/(atof(config["Size"].getWithDefault("ButtonSmallTextDiv", "15.0")));
-	styles[STYLE::BUTTON_SMALL].font  = sbMakeFont(styles[STYLE::BUTTON_SMALL].size, fontNameT, false, false);
+	styles[STYLE::BUTTON_SMALL].size  = styles[STYLE::BUTTON].size*2/3;
+	styles[STYLE::BUTTON_SMALL].font  = sbMakeFont(styles[STYLE::BUTTON_SMALL].size, tfont, true, false);
 	
-	styles[STYLE::STANZA].size        = scale/(atof(config["Size"].getWithDefault("SubTextDiv",     "16.0")));
-	styles[STYLE::STANZA].font        = sbMakeFont(styles[STYLE::STANZA].size,       fontNameT, true, false);
+	styles[STYLE::STANZA].size        = size*(atof(xml.getChildNodeByPath("List/Item/SubText").getAttribute("fontSize","0.06")));
+	styles[STYLE::STANZA].font        = sbMakeFont(styles[STYLE::STANZA].size,       tfont, true, false);
 	
-	styles[STYLE::DESCRIPTION].size   = scale/(atof(config["Size"].getWithDefault("DescriptionDiv", "14.0")));
-	styles[STYLE::DESCRIPTION].font   = sbMakeFont(styles[STYLE::DESCRIPTION].size,  fontNameT, false, false);
+	styles[STYLE::DESCRIPTION].size   = styles[STYLE::TEXT].size*2/3;
+	styles[STYLE::DESCRIPTION].font   = sbMakeFont(styles[STYLE::DESCRIPTION].size,  tfont, false, false);
 	
-	styles[STYLE::CAPTION].size       = scale/(atof(config["Size"].getWithDefault("HeaderDiv",      "9.0")));
-	styles[STYLE::CAPTION].font       = sbMakeFont(styles[STYLE::CAPTION].size,      fontNameT, true, false);
+	styles[STYLE::CAPTION].size       = styles[STYLE::TEXT].size/2*3;
+	styles[STYLE::CAPTION].font       = sbMakeFont(styles[STYLE::CAPTION].size,      tfont, true, false);
 
-	// clear
-	delete [] fontNameT;
+	delete [] tfont;
+
+	// cache background
+	listBackground = sbSurfaceCreate(max(Core->getRect().width(),Core->getRect().height()),max(Core->getRect().width(),Core->getRect().height()));
+
+	drawElement(listBackground,&sbRect(Core->getRect().left,Core->getRect().top,Core->getRect().right,Core->getRect().bottom-PanelSize),ELEMENT::BACKGROUND);
+	drawElement(listBackground,&sbRect(Core->getRect().left,Core->getRect().bottom-PanelSize,Core->getRect().right,Core->getRect().bottom),ELEMENT::PANEL);
 }
 
 sbTheme::~sbTheme()
 {
-	for (int i=0; i<STYLE::COUNT; i++) sbDeleteFont (styles[i].font);
+	for (int i=0; i < STYLE::COUNT; i++) sbDeleteFont (styles[i].font);
+
+	if (listBackground != NULL) sbSurfaceDestroy(listBackground);
 }
 
-void sbTheme::drawElement (sbSurface rc, const sbRect * rect, sbTheme::ELEMENT::TYPE type, const int animFrame) const
+void sbTheme::drawElement ( sbSurface rc , const sbRect * rect , sbTheme::ELEMENT::TYPE type ) const
 {
+	if (rc != listBackground && !Core->fadeSurface && (type == ELEMENT::BACKGROUND || type == ELEMENT::PANEL))
+	{
+		sbBitBlt(rc,*rect,listBackground,sbPoint(rect->left,rect->top));
+		return;
+	}
+
 	for (int i = 0; i < elements[type].fill.size(); i++)
 	{
 		sbColor start = elements[type].fill[i].first;
 		sbColor end   = elements[type].fill.size()-1 == i ? start : elements[type].fill[i+1].first;
 		sbRect  fill  = *rect;
 
-		if (start.alpha >= 255 && (elements[type].gradient == false || end.alpha >= 255)) continue;
+		if (start.alpha == 0 && (elements[type].gradient == false || end.alpha == 0)) continue;
 
-		if (Core->getSurface(sbCore::SURFACE::TYPE_WHOLE)->fade)
-		{
-			start.red   = start.red*2/3;
-			start.green = start.green*2/3;
-			start.blue  = start.blue*2/3;
-
-			end.red     = end.red*2/3;
-			end.green   = end.green*2/3;
-			end.blue    = end.blue*2/3;
-		}
-
 		if (elements[type].vertical)
 		{
 			fill.top    = fill.height()*elements[type].fill[i].second/1000+fill.top;
@@ -157,12 +157,12 @@
 		}
 		else
 		{
-			fill.right  = fill.width()*elements[type].fill[i].second/1000+fill.right;
-			fill.left   = (elements[type].fill.size()-1 == i ? fill.width() : fill.width()*elements[type].fill[i+1].second/1000)+fill.left;
+			fill.left  = fill.width()*elements[type].fill[i].second/1000+fill.left;
+			fill.right   = (elements[type].fill.size()-1 == i ? fill.width() : fill.width()*elements[type].fill[i+1].second/1000)+fill.left;
 		}
 
-		checkTransparentColor ( start, fill.left,  fill.top );
-		checkTransparentColor ( end,   fill.right, fill.bottom );
+		start = fadeColor ( start, fill.left,  fill.top );
+		end   = fadeColor ( end,   fill.right, fill.bottom );
 
 		if (elements[type].gradient)
 			sbDrawGradient ( rc, &fill, start, end, elements[type].vertical );
@@ -171,13 +171,15 @@
 	}
 }
 
-void sbTheme::checkTransparentColor ( sbColor & color , int x , int y ) const
+sbColor sbTheme::fadeColor ( const sbColor & color , int x , int y ) const
 {
-	if ( color.alpha != 0 )
+	sbColor newColor = color;
+
+	if ( color.alpha < 255 )
 	{
 		if (elements[sbTheme::ELEMENT::BACKGROUND].fill.size() == 2)
 		{
-			const sbRect rect = Core->getSurface(sbCore::SURFACE::TYPE_WHOLE)->rect;
+			const sbRect rect = Core->getRect();
 
 			unsigned char r1 = elements[sbTheme::ELEMENT::BACKGROUND].fill[0].first.red;
 			unsigned char g1 = elements[sbTheme::ELEMENT::BACKGROUND].fill[0].first.green;
@@ -188,11 +190,46 @@
 
 			int v = min(1000,((y-rect.top)*1000)/rect.height());
 
-			color = sbColor (r1+((r2-r1)*v/1000),g1+((g2-g1)*v/1000),b1+((b2-b1)*v/1000));
+			sbColor backColor (r1+((r2-r1)*v/1000),g1+((g2-g1)*v/1000),b1+((b2-b1)*v/1000));
+
+			newColor.red   = backColor.red   + (color.red   - backColor.red)   * color.alpha / 255;
+			newColor.green = backColor.green + (color.green - backColor.green) * color.alpha / 255;
+			newColor.blue  = backColor.blue  + (color.blue  - backColor.blue)  * color.alpha / 255;
 		}
 		else
 		{
-			color = elements[sbTheme::ELEMENT::BACKGROUND].fill[0].first;
+			newColor = elements[sbTheme::ELEMENT::BACKGROUND].fill[0].first;
 		}
 	}
+
+	if (Core->fadeSurface)
+	{
+		newColor.red     = newColor.red   + ((FadingColor.red   - newColor.red)   * FadingColor.alpha / 255);
+		newColor.green   = newColor.green + ((FadingColor.green - newColor.green) * FadingColor.alpha / 255);
+		newColor.blue    = newColor.blue  + ((FadingColor.blue  - newColor.blue)  * FadingColor.alpha / 255);
+	}
+
+	return newColor;
 }
+
+void sbTheme::drawFrame( sbSurface surface , const sbRect * rect ) const
+{
+	int x1 = rect->left, y1 = rect->top, x2 = rect->right, y2 = rect->bottom, round = size*0.04f;
+	sbColor color = fadeColor(SelectionFrameColor,x1,y1);
+	
+	sbDrawLine(surface, sbPoint(x1+round,y1), sbPoint(x2-round,y1),color,SelectionFrameWidth);
+	sbDrawLine(surface, sbPoint(x2-round,y1), sbPoint(x2-(round/3),y1+(round/3)),color,SelectionFrameWidth);
+	sbDrawLine(surface, sbPoint(x2-(round/3),y1+(round/3)), sbPoint(x2,y1+round),color,SelectionFrameWidth);
+
+	sbDrawLine(surface, sbPoint(x2,y1+round), sbPoint(x2,y2-round),color,SelectionFrameWidth);
+	sbDrawLine(surface, sbPoint(x2,y2-round), sbPoint(x2-(round/3),y2-(round/3)),color,SelectionFrameWidth);
+	sbDrawLine(surface, sbPoint(x2-(round/3),y2-(round/3)), sbPoint(x2-round,y2),color,SelectionFrameWidth);
+
+	sbDrawLine(surface, sbPoint(x2-round,y2), sbPoint(x1+round,y2),color,SelectionFrameWidth);
+	sbDrawLine(surface, sbPoint(x1+round,y2), sbPoint(x1+(round/3),y2-(round/3)),color,SelectionFrameWidth);
+	sbDrawLine(surface, sbPoint(x1+(round/3),y2-(round/3)), sbPoint(x1,y2-round),color,SelectionFrameWidth);
+
+	sbDrawLine(surface, sbPoint(x1,y2-round), sbPoint(x1,y1+round),color,SelectionFrameWidth);
+	sbDrawLine(surface, sbPoint(x1,y1+round), sbPoint(x1+(round/3),y1+(round/3)),color,SelectionFrameWidth);
+	sbDrawLine(surface, sbPoint(x1+(round/3),y1+(round/3)), sbPoint(x1+round,y1),color,SelectionFrameWidth);
+}
\ No newline at end of file

Modified: trunk/src/SlideBible/sbTheme.h
===================================================================
--- trunk/src/SlideBible/sbTheme.h	2010-04-09 17:38:27 UTC (rev 231)
+++ trunk/src/SlideBible/sbTheme.h	2010-04-09 17:44:00 UTC (rev 232)
@@ -26,18 +26,15 @@
 	sbTheme(){};
 	~sbTheme();
 
-	void                  init();
+	void                  init      ();
+	sbColor               fadeColor ( const sbColor & color, int x, int y ) const;
 
-private:
-
-	void                  checkTransparentColor (sbColor & color, int x, int y) const;
-
-public:
-
 	sbColor               ItemTextColor;
 	sbColor               ControlsColor;
 	sbColor               ItemSubTextColor;
 	sbColor               ItemMenuTextColor;
+	sbColor               SelectionFrameColor;
+	sbColor               FadingColor;
 
 	struct STYLE
 	{
@@ -64,25 +61,27 @@
 		enum TYPE
 		{
 			ITEM = 0,
-			ITEM_SELECTED,
-			ITEM_HOVER,
+			//ITEM_SELECTED,
+			ITEM_PRESSED,
 			ITEM_HIGHLIGHTED,
 			SEPARATOR,
 			BACKGROUND,
 			TAPPED,
-			CONTROL,
-			CONTROL_PRESSED,
+			PANEL,
+			PANEL_PRESSED,
+			//PANEL_SELECTED,
+			MENU,
+			MENU_PRESSED,
+			//MENU_SELECTED,
 			BANNER,
 			COUNT
 		};
 
 		std::vector<std::pair<sbColor,short>>   fill;      // short - gradients vertical/horizontal sparation in range 0-1000
 
-		std::vector<std::vector<std::pair<sbColor,sbPoint>>> region;
-
 		sbBitmap                                bitmap;
 
-		bool                                    have;      // have bitmap
+		bool                                    haveBitmap;      // have bitmap
 		bool                                    vertical;
 		bool                                    gradient;
 		bool                                    stretch;
@@ -90,19 +89,19 @@
 
 	ELEMENT               elements [ELEMENT::COUNT];
 
-	void                  drawElement ( sbSurface surface, const sbRect * rect, sbTheme::ELEMENT::TYPE type, const int animFrame = 0 ) const;
+	void                  drawElement ( sbSurface surface , const sbRect * rect , sbTheme::ELEMENT::TYPE type ) const;
 
+	void                  drawFrame   ( sbSurface surface , const sbRect * rect ) const;
+
 	int                   ListSeparatorHeight;
 	int                   BannerBorderSize;
+	int                   PanelSize;
+	int                   SelectionFrameWidth;
 
-	int                   scale; // screen minimal dimension, determine font and control sizes
-	int                   fingerSize;
+	int                   size; // screen minimal dimension, determine font and control sizes
+	
+	sbRect                itemMargins;
 
-	int                   itemTopMargin;
-	int                   itemBottomMargin;
-	int                   itemLeftMargin;
-	int                   itemRightMargin;
-
 	sbSurface             listBackground;
 };
 

Modified: trunk/src/SlideBible/todo.txt
===================================================================
--- trunk/src/SlideBible/todo.txt	2010-04-09 17:38:27 UTC (rev 231)
+++ trunk/src/SlideBible/todo.txt	2010-04-09 17:44:00 UTC (rev 232)
@@ -1,65 +1,90 @@
-alpha
-+	release configuration
-+	module view description
-+	huge rewrite
-+		platform independent api layer
-+		test base types
-+			memory tracker
-+			threading
-+			sbColor - constructor from string
-+		make it work
-+			wm6.5 not started
-+			release configuration not started
-+	win32 platform
-+	memory leak test
-+	verse history
-+		time function
-+	timer to save configs
+ALPHA
 +	make list scrolling more smooth
-	make verse expantion without jerks
-	history view with dates
-	keypad
-		active control
++	make verse expantion without jerks
++	text fade
++	history view with dates
++		module name in history
++		render item
++	interface description format, xml
++	fopen in application dir for wince
++	render tasks
++		stretch mode - render performed on surface with custom size, then StretchBlt on screen
++		cache background on first render
++		render recieve horizontal displacement
++		remove sbCore::SURFACE
++	keypad
++		cursor
++		active control
++		control / list mode
++			method to smooth-delayed-scroll list
++	lists instead menus
 
 
+	loading all locales takes too long
+		even on win32
+		also look into xiphos dirent.cpp
+		maybe deploy packages for only language
+	warning war - clean build log from warnings
+	combining unicode accents, like accute, should be in platform-dependent part
+	2. Ïàðàëèïîìå\níîí\n4 in chapter title
+	bool sbList::showPlace
+	perfomance optimization
+		sbItem::LINE caching
+	controls, pressed/released
+	volume +/- scroll half of screen, long press linvolve cinetic scroll with increasing speed, zoom-/+ scroll as mouse scroll
 
-	remake sytems
-		general reason why it is needed to remake, that lists should have
-			static decription 
-				home - welcome, readings, history, ... , about
-				added controls
-			and dynamical changing
-				readings count should changing
-				verses should be added dynamicaly
-				text addition in verse
-			sbList - screen controller
-				sbItem - square container
-					sbRenderCache
-		adding items should not be so constrained
-		remove surfaces, make:
-			items-draw-cache: mask surface
-		views interaction
-			make throught Core
-			anywhere i could get current reading place and set necceserity of transition
-t		while view active its background thread should work
-		should be interface to obtain state of module view (current place, current module)
-		if module attached to reading, when reading deleted, module ---removed too--- deatached from reading
-			core should access all lists reading attachments and convert
-		book_select and verse_select
-			cycled attachment
-			in lists map presists both
-			
+
+
+BETA
+	to test
+		other locales, utf encoding
+		locale paths
+	user theme creation
+
+
+
+1.1 RELEASE
+	search
+		clucence
+		input text items
++			sip control
+			cursor
+?			copy/paste
+	different screens and runtime orientation change
+		g-sensor option
+	cross-references, footnotes
+		will be shown in verse context menu, or by multitouch expand
+	daily devotionals
+	genbooks - ?
+	side scrolling - switches lists
+	design improvements: like wp7 metro style
+	new place select dialog
+		three scrollers: book/chapter/verse
 	verse features
 		bookmarks
-			data tree (for bookmarks folders)
+			nested bookmarks folders
 			date created (for sorting)
-			only one item per place in folder
-			ranges allowed
-			place - "KJV:Gen 1:1-12", path - "Holiness\God"
-		history
-			date visited
-			many items per place
-			ranges
+			place in uri sword:
+
+
+
+1.2 RELEASE
+	icons and graphics
+		graphics theme uses large png file
+		remove built-in theme, application will not run if theme not found
+
+
+
+FEATURE RELEASES
+	Link, like Opera Link to synchronize bookmarks and all Per Verse Data among all user devices
+		need Sword change that every verse in Bibile at every v11n has unique id
+	another platform : android , mac os x ,  openembedded , symbian , maemo , ...
+	multitouch
+	linked lists
+		slide list and stroke down/up to link
+		link neighbor lists: items will be fitted by height, empty verses will be displayed hollow
+	random verse on Home view
+	verse features
 		ratings/favourite
 			no ranges, byte-array
 		readings
@@ -74,60 +99,5 @@
 ?			converted beetwheen v11ns on call
 			or maybe implement this throught history
 			
-	search
-		clucence
-		input text items
-+			sip control
-			cursor
-?			copy/paste
-
-	warning war - clean build log from warnings
-?	need i naming for members, like m_Strings or mStrings?
-		ability to search
-		mStrings - member
-		pName - pointer
-		its reduce readableness
-	fopen in application dir for wince
-~	use posix functions
-	background thread some times stops
-	features: move deleted history to special array, and save it with xml
-	render recieve horizontal displacement
-	volume+/- scroll half of screen, long press linvolve cinetic scroll with increasing speed, zoom-/+ scroll as mouse scroll
-	side slide should be not on one list but on some
-	combining unicode accents, like accute, should be in platform-dependent part
-	smart item surface cacher, create square surface of longer screen side
-	text fade
-	2. Ïàðàëèïîìå\níîí\n4 in chapter title
-	start slide to empty list, but drop to not empty produces blank screen
-	daily devotionals
-	cross-references, footnotes
-		will be shown in verse context menu, or by multitouch expand
-	controls, pressed/released
-	link neighbor lists: items will be fitted by height, empty verses will be displayed hollow
-	keypad: on key pressed, keyMode activated, every button on displayed as common text, as touchscreen pressed, every button on screen become drawn as button
-	loading all locale takes too long
-	slide list and stroke down/up - link list
- 	sometimes happens something wrong with height of empty verse and verse text line height
-	different screens and runtime orientation change
-
-?	update theme from psd file
-?	data abort in gwes.exe on emulator
-?	base class for sbItem and sbControl for holding screen text
-?	make lists pins (next/prev/left/right) links constant. so instances of same type should not change their values direct
-?	moving to sdl
-
-beta
-	to test
-		other locales, utf encoding
-		russian paths
-	icons and graphics
-
-release
 ?	sliding, animated backgrounds
-	Link, like Opera Link to synchronize bookmarks and all Per Verse Data among all user devices
-		need Sword change that every verse in Bibile at every v11n has unique id
 ?	read html / txt / rtf / doc formats
-	another platform : android , mac os x ,  openembedded , symbian , maemo , ...
-	g-sensor changes orientation, option
-	multitouch
-	
\ No newline at end of file




More information about the sword-cvs mailing list