Replaced mongoose code with civetweb (https://github.com/bel2125/civetweb)
Refreshed apitrace, GLEW, and FreeGLUT
diff --git a/Makefile.regal b/Makefile.regal
index ffcf4ba..dfec0bf 100644
--- a/Makefile.regal
+++ b/Makefile.regal
@@ -42,10 +42,10 @@
 
 REGAL.SRCS           := $(REGAL.CXX)
 
-# Disable mongoose and Regal HTTP for NaCl build
+# Disable civetweb and Regal HTTP for NaCl build
 
 ifeq ($(filter nacl% emscripten%,$(SYSTEM)),)
-REGAL.SRCS           += src/mongoose/mongoose.c
+REGAL.SRCS           += src/civetweb/civetweb.c
 endif
 
 ifeq ($(filter -DREGAL_NO_MD5%,$(CFLAGS)),)
@@ -195,10 +195,8 @@
 REGAL.SONAME     := lib$(NAME).so.$(SO_MAJOR)
 REGAL.DEVLNK     := lib$(NAME).so
 REGAL.SHARED     := lib$(NAME).so.$(SO_VERSION)
-ifeq ($(filter linux-arm,$(SYSTEM)),)
 REGAL.LDFLAGS.SO := $(LDFLAGS.SO) $(LDFLAGS.DYNAMIC) -Wl,-soname=$(REGAL.SONAME)
 endif
-endif
 
 ifneq ($(filter darwin%,$(SYSTEM)),)
 REGAL.SONAME     := lib$(NAME).$(SO_MAJOR).dylib
@@ -282,11 +280,11 @@
 	@mkdir -p $(dir $@)
 	$(LOG_CXX)$(CCACHE) $(CXX) $(REGAL.CFLAGS) $(CFLAGS) $(PICFLAG) $(CFLAGS.SO) $(REGAL.INCLUDE) -o $@ -c $<
 
-tmp/$(SYSTEM)/regal/static/%.o: src/mongoose/%.c $(REGAL.HEADERS)
+tmp/$(SYSTEM)/regal/static/%.o: src/civetweb/%.c $(REGAL.HEADERS)
 	@mkdir -p $(dir $@)
 	$(LOG_CC)$(CCACHE) $(CC) $(REGAL.CFLAGS) $(CFLAGS) $(CFLAGS.SO) $(REGAL.INCLUDE) -o $@ -c $<
 
-tmp/$(SYSTEM)/regal/shared/%.o: src/mongoose/%.c $(REGAL.HEADERS)
+tmp/$(SYSTEM)/regal/shared/%.o: src/civetweb/%.c $(REGAL.HEADERS)
 	@mkdir -p $(dir $@)
 	$(LOG_CC)$(CCACHE) $(CC) $(REGAL.CFLAGS) $(CFLAGS) $(PICFLAG) $(CFLAGS.SO) $(REGAL.INCLUDE) -o $@ -c $<
 
diff --git a/README.rst b/README.rst
index ff86005..660e6f4 100644
--- a/README.rst
+++ b/README.rst
@@ -334,10 +334,12 @@
 
  * 32-bit:
 
-  ``$ sudo yum install zlib-devel libpng-devel libXmu-devel libXi-devel``
+  ``$ sudo yum install gcc-c++ zlib-devel libpng-devel libXmu-devel libXi-devel``
 
  * 64-bit
 
+  ``$ sudo yum install gcc-c++``
+
   ``$ sudo yum install zlib-devel.i686   libpng-devel.i686``
 
   ``$ sudo yum install zlib-devel.x86_64 libpng-devel.x86_64``
diff --git a/build/android/Regal/jni/Android.mk b/build/android/Regal/jni/Android.mk
index 9d22280..31bb666 100644
--- a/build/android/Regal/jni/Android.mk
+++ b/build/android/Regal/jni/Android.mk
@@ -60,7 +60,7 @@
 apitrace_c_includes := $(regal_path)/include $(regal_path)/src/apitrace/common $(regal_path)/src/apitrace/gen/dispatch $(regal_path)/src/apitrace/dispatch $(regal_path)/src/apitrace/helpers $(regal_path)/src/apitrace/wrappers $(regal_path)/src/apitrace
 apitrace_c_includes += $(regal_path)/src/zlib/include $(regal_path)/src/zlib/src $(regal_path)/src/snappy
 apitrace_c_includes += $(regal_path)/src/apitrace/thirdparty/khronos
-apitrace_c_includes += $(regal_path)/src/regal $(regal_path)/src/mongoose $(regal_path)/src/squish
+apitrace_c_includes += $(regal_path)/src/regal $(regal_path)/src/civetweb $(regal_path)/src/squish
 apitrace_c_includes := $(patsubst $(LOCAL_PATH)/../%,%,$(apitrace_c_includes))
 
 apitrace_export_c_includes := $(regal_path)/include
@@ -79,10 +79,10 @@
 #
 
 regal_src_files := $(patsubst %,$(regal_path)/%,$(REGAL.CXX))
-regal_src_files += $(regal_path)/src/mongoose/mongoose.c $(regal_path)/src/md5/src/md5.c $(regal_path)/src/jsonsl/jsonsl.c
+regal_src_files += $(regal_path)/src/civetweb/civetweb.c $(regal_path)/src/md5/src/md5.c $(regal_path)/src/jsonsl/jsonsl.c
 regal_src_files := $(patsubst $(LOCAL_PATH)/%,%,$(regal_src_files))
 
-regal_c_includes := $(regal_path)/include $(regal_path)/src/regal $(regal_path)/src/boost $(regal_path)/src/mongoose $(regal_path)/src/md5/include $(regal_path)/src/lookup3 $(regal_path)/src/jsonsl
+regal_c_includes := $(regal_path)/include $(regal_path)/src/regal $(regal_path)/src/boost $(regal_path)/src/civetweb $(regal_path)/src/md5/include $(regal_path)/src/lookup3 $(regal_path)/src/jsonsl
 regal_c_includes := $(patsubst $(LOCAL_PATH)/../%,%,$(regal_c_includes))
 
 regal_export_c_includes := $(regal_path)/include
diff --git a/build/ios/Regal/Regal.xcodeproj/project.pbxproj b/build/ios/Regal/Regal.xcodeproj/project.pbxproj
index 9a5d095..48c20c6 100644
--- a/build/ios/Regal/Regal.xcodeproj/project.pbxproj
+++ b/build/ios/Regal/Regal.xcodeproj/project.pbxproj
@@ -60,7 +60,7 @@
 		43FC5FA215C4619B00D0177C /* RegalUtil.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 43FC5F7515C4619B00D0177C /* RegalUtil.cpp */; };
 		43FC5FA315C4619B00D0177C /* RegalUtil.h in Headers */ = {isa = PBXBuildFile; fileRef = 43FC5F7615C4619B00D0177C /* RegalUtil.h */; };
 		43FC5FA415C4619B00D0177C /* RegalVao.h in Headers */ = {isa = PBXBuildFile; fileRef = 43FC5F7715C4619B00D0177C /* RegalVao.h */; };
-		43FC5FA715C461AC00D0177C /* mongoose.c in Sources */ = {isa = PBXBuildFile; fileRef = 43FC5FA615C461AC00D0177C /* mongoose.c */; };
+		43FC5FA715C461AC00D0177C /* civetweb.c in Sources */ = {isa = PBXBuildFile; fileRef = 43FC5FA615C461AC00D0177C /* civetweb.c */; };
 		754D3C9517CFFD7200E4C0E0 /* RegalEmu.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 754D3C9417CFFD7200E4C0E0 /* RegalEmu.cpp */; };
 		75694C8E17EB913B00B8AD9D /* RegalQuads.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 75694C8C17EB913B00B8AD9D /* RegalQuads.cpp */; };
 		75694C8F17EB913B00B8AD9D /* RegalQuads.h in Headers */ = {isa = PBXBuildFile; fileRef = 75694C8D17EB913B00B8AD9D /* RegalQuads.h */; };
@@ -236,7 +236,7 @@
 		43FC5F7515C4619B00D0177C /* RegalUtil.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = RegalUtil.cpp; path = ../../../src/regal/RegalUtil.cpp; sourceTree = "<group>"; };
 		43FC5F7615C4619B00D0177C /* RegalUtil.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = RegalUtil.h; path = ../../../src/regal/RegalUtil.h; sourceTree = "<group>"; };
 		43FC5F7715C4619B00D0177C /* RegalVao.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = RegalVao.h; path = ../../../src/regal/RegalVao.h; sourceTree = "<group>"; };
-		43FC5FA615C461AC00D0177C /* mongoose.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = mongoose.c; path = ../../../src/mongoose/mongoose.c; sourceTree = "<group>"; };
+		43FC5FA615C461AC00D0177C /* civetweb.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = civetweb.c; path = ../../../src/civetweb/civetweb.c; sourceTree = "<group>"; };
 		754D3C9417CFFD7200E4C0E0 /* RegalEmu.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = RegalEmu.cpp; path = ../../../src/regal/RegalEmu.cpp; sourceTree = "<group>"; };
 		75694C8C17EB913B00B8AD9D /* RegalQuads.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = RegalQuads.cpp; path = ../../../src/regal/RegalQuads.cpp; sourceTree = "<group>"; };
 		75694C8D17EB913B00B8AD9D /* RegalQuads.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = RegalQuads.h; path = ../../../src/regal/RegalQuads.h; sourceTree = "<group>"; };
@@ -405,7 +405,7 @@
 				BCDF6697178F16E100EE9569 /* apitrace */,
 				43FC5F4B15C4619B00D0177C /* linear.h */,
 				BC020956160D1C65003FAB99 /* md5 */,
-				43FC5FA515C461A100D0177C /* mongoose */,
+				43FC5FA515C461A100D0177C /* civetweb */,
 				43FC5F4C15C4619B00D0177C /* Regal.cpp */,
 				BC59F9CA174809EE004BC2AC /* RegalBaseVertex.h */,
 				43FC5F4D15C4619B00D0177C /* RegalBin.h */,
@@ -524,12 +524,12 @@
 			name = Regal;
 			sourceTree = "<group>";
 		};
-		43FC5FA515C461A100D0177C /* mongoose */ = {
+		43FC5FA515C461A100D0177C /* civetweb */ = {
 			isa = PBXGroup;
 			children = (
-				43FC5FA615C461AC00D0177C /* mongoose.c */,
+				43FC5FA615C461AC00D0177C /* civetweb.c */,
 			);
-			name = mongoose;
+			name = civetweb;
 			sourceTree = "<group>";
 		};
 		BC020956160D1C65003FAB99 /* md5 */ = {
@@ -790,7 +790,7 @@
 				43FC5F9715C4619B00D0177C /* RegalLookup.cpp in Sources */,
 				43FC5FA015C4619B00D0177C /* RegalToken.cpp in Sources */,
 				43FC5FA215C4619B00D0177C /* RegalUtil.cpp in Sources */,
-				43FC5FA715C461AC00D0177C /* mongoose.c in Sources */,
+				43FC5FA715C461AC00D0177C /* civetweb.c in Sources */,
 				4366EEEF15C9B54E00211205 /* RegalFavicon.cpp in Sources */,
 				4366EEF115C9B54E00211205 /* RegalMac.cpp in Sources */,
 				BC921A5E15D5624600E52C91 /* RegalDispatchMissing.cpp in Sources */,
@@ -925,7 +925,7 @@
 					../../../include,
 					../../../src/boost,
 					../../../src/md5/include,
-					../../../src/mongoose,
+					../../../src/civetweb,
 					../../../src/lookup3,
 					../../../src/apitrace/common,
 					../../../src/apitrace/dispatch,
@@ -957,7 +957,7 @@
 					../../../include,
 					../../../src/boost,
 					../../../src/md5/include,
-					../../../src/mongoose,
+					../../../src/civetweb,
 					../../../src/lookup3,
 					../../../src/apitrace/common,
 					../../../src/apitrace/dispatch,
diff --git a/build/mac/Regal/Regal.xcodeproj/project.pbxproj b/build/mac/Regal/Regal.xcodeproj/project.pbxproj
index 46582a9..42c7928 100644
--- a/build/mac/Regal/Regal.xcodeproj/project.pbxproj
+++ b/build/mac/Regal/Regal.xcodeproj/project.pbxproj
@@ -18,7 +18,6 @@
 		4359147D18293B32002CB92C /* libapitrace.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 4359144B18293A5C002CB92C /* libapitrace.a */; };
 		4359147E18293B32002CB92C /* libjsonsl.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 4359145118293A68002CB92C /* libjsonsl.a */; };
 		4359147F18293B32002CB92C /* libmd5.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 4359145718293A74002CB92C /* libmd5.a */; };
-		4359148018293B32002CB92C /* libmongoose.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 4359145D18293A7D002CB92C /* libmongoose.a */; };
 		4359148118293B32002CB92C /* libpcre.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 4359146318293A8B002CB92C /* libpcre.a */; };
 		4359148218293B32002CB92C /* libpng.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 4359146918293A94002CB92C /* libpng.a */; };
 		4359148318293B32002CB92C /* libsnappy.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 4359146F18293A9C002CB92C /* libsnappy.a */; };
@@ -153,13 +152,6 @@
 			remoteGlobalIDString = 4336678117C56DFD00D45AD9;
 			remoteInfo = md5;
 		};
-		4359145C18293A7D002CB92C /* PBXContainerItemProxy */ = {
-			isa = PBXContainerItemProxy;
-			containerPortal = 4359145818293A7C002CB92C /* mongoose.xcodeproj */;
-			proxyType = 2;
-			remoteGlobalIDString = 4336676E17C56DC700D45AD9;
-			remoteInfo = mongoose;
-		};
 		4359146218293A8B002CB92C /* PBXContainerItemProxy */ = {
 			isa = PBXContainerItemProxy;
 			containerPortal = 4359145E18293A8A002CB92C /* pcre.xcodeproj */;
@@ -209,7 +201,6 @@
 		4359144618293A5B002CB92C /* apitrace.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = apitrace.xcodeproj; path = ../apitrace/apitrace.xcodeproj; sourceTree = "<group>"; };
 		4359144C18293A68002CB92C /* jsonsl.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = jsonsl.xcodeproj; path = ../jsonsl/jsonsl.xcodeproj; sourceTree = "<group>"; };
 		4359145218293A73002CB92C /* md5.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = md5.xcodeproj; path = ../md5/md5.xcodeproj; sourceTree = "<group>"; };
-		4359145818293A7C002CB92C /* mongoose.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = mongoose.xcodeproj; path = ../mongoose/mongoose.xcodeproj; sourceTree = "<group>"; };
 		4359145E18293A8A002CB92C /* pcre.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = pcre.xcodeproj; path = ../pcre/pcre.xcodeproj; sourceTree = "<group>"; };
 		4359146418293A93002CB92C /* png.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = png.xcodeproj; path = ../png/png.xcodeproj; sourceTree = "<group>"; };
 		4359146A18293A9C002CB92C /* snappy.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = snappy.xcodeproj; path = ../snappy/snappy.xcodeproj; sourceTree = "<group>"; };
@@ -333,7 +324,6 @@
 				4359147D18293B32002CB92C /* libapitrace.a in Frameworks */,
 				4359147E18293B32002CB92C /* libjsonsl.a in Frameworks */,
 				4359147F18293B32002CB92C /* libmd5.a in Frameworks */,
-				4359148018293B32002CB92C /* libmongoose.a in Frameworks */,
 				4359148118293B32002CB92C /* libpcre.a in Frameworks */,
 				4359148218293B32002CB92C /* libpng.a in Frameworks */,
 				4359148318293B32002CB92C /* libsnappy.a in Frameworks */,
@@ -369,14 +359,6 @@
 			name = Products;
 			sourceTree = "<group>";
 		};
-		4359145918293A7C002CB92C /* Products */ = {
-			isa = PBXGroup;
-			children = (
-				4359145D18293A7D002CB92C /* libmongoose.a */,
-			);
-			name = Products;
-			sourceTree = "<group>";
-		};
 		4359145F18293A8A002CB92C /* Products */ = {
 			isa = PBXGroup;
 			children = (
@@ -423,7 +405,6 @@
 				4359144618293A5B002CB92C /* apitrace.xcodeproj */,
 				4359144C18293A68002CB92C /* jsonsl.xcodeproj */,
 				4359145218293A73002CB92C /* md5.xcodeproj */,
-				4359145818293A7C002CB92C /* mongoose.xcodeproj */,
 				4359145E18293A8A002CB92C /* pcre.xcodeproj */,
 				4359146418293A93002CB92C /* png.xcodeproj */,
 				4359146A18293A9C002CB92C /* snappy.xcodeproj */,
@@ -697,10 +678,6 @@
 					ProjectRef = 4359145218293A73002CB92C /* md5.xcodeproj */;
 				},
 				{
-					ProductGroup = 4359145918293A7C002CB92C /* Products */;
-					ProjectRef = 4359145818293A7C002CB92C /* mongoose.xcodeproj */;
-				},
-				{
 					ProductGroup = 4359145F18293A8A002CB92C /* Products */;
 					ProjectRef = 4359145E18293A8A002CB92C /* pcre.xcodeproj */;
 				},
@@ -750,13 +727,6 @@
 			remoteRef = 4359145618293A74002CB92C /* PBXContainerItemProxy */;
 			sourceTree = BUILT_PRODUCTS_DIR;
 		};
-		4359145D18293A7D002CB92C /* libmongoose.a */ = {
-			isa = PBXReferenceProxy;
-			fileType = archive.ar;
-			path = libmongoose.a;
-			remoteRef = 4359145C18293A7D002CB92C /* PBXContainerItemProxy */;
-			sourceTree = BUILT_PRODUCTS_DIR;
-		};
 		4359146318293A8B002CB92C /* libpcre.a */ = {
 			isa = PBXReferenceProxy;
 			fileType = archive.ar;
@@ -885,7 +855,7 @@
 				HEADER_SEARCH_PATHS = (
 					../../../include,
 					../../../src/boost,
-					../../../src/mongoose,
+					../../../src/civetweb,
 					../../../src/lookup3,
 					../../../src/jsonsl,
 					../../../src/snappy,
@@ -899,8 +869,8 @@
 				);
 				MACOSX_DEPLOYMENT_TARGET = 10.7;
 				ONLY_ACTIVE_ARCH = YES;
-				SDKROOT = macosx;
-				USER_HEADER_SEARCH_PATHS = "../../../src/mongoose ../../../src/md5/include";
+				SDKROOT = "";
+				USER_HEADER_SEARCH_PATHS = "../../../src/civetweb ../../../src/md5/include";
 			};
 			name = Debug;
 		};
@@ -929,7 +899,7 @@
 				HEADER_SEARCH_PATHS = (
 					../../../include,
 					../../../src/boost,
-					../../../src/mongoose,
+					../../../src/civetweb,
 					../../../src/lookup3,
 					../../../src/jsonsl,
 					../../../src/snappy,
@@ -942,8 +912,8 @@
 					../../../src/zlib/src,
 				);
 				MACOSX_DEPLOYMENT_TARGET = 10.7;
-				SDKROOT = macosx;
-				USER_HEADER_SEARCH_PATHS = "../../../src/mongoose ../../../src/md5/include";
+				SDKROOT = "";
+				USER_HEADER_SEARCH_PATHS = "../../../src/civetweb ../../../src/md5/include";
 			};
 			name = Release;
 		};
diff --git a/build/mac/apitrace/apitrace.xcodeproj/project.pbxproj b/build/mac/apitrace/apitrace.xcodeproj/project.pbxproj
index 5a1fa91..a14d2d8 100644
--- a/build/mac/apitrace/apitrace.xcodeproj/project.pbxproj
+++ b/build/mac/apitrace/apitrace.xcodeproj/project.pbxproj
@@ -367,9 +367,9 @@
 					../../../src/apitrace/thirdparty/khronos,
 					../../../src/regal,
 				);
-				MACOSX_DEPLOYMENT_TARGET = 10.8;
+				MACOSX_DEPLOYMENT_TARGET = 10.7;
 				ONLY_ACTIVE_ARCH = YES;
-				SDKROOT = "";
+				SDKROOT = macosx10.7;
 			};
 			name = Debug;
 		};
@@ -410,8 +410,8 @@
 					../../../src/apitrace/thirdparty/khronos,
 					../../../src/regal,
 				);
-				MACOSX_DEPLOYMENT_TARGET = 10.8;
-				SDKROOT = "";
+				MACOSX_DEPLOYMENT_TARGET = 10.7;
+				SDKROOT = macosx10.7;
 			};
 			name = Release;
 		};
diff --git a/build/mac/mongoose/mongoose.xcodeproj/project.pbxproj b/build/mac/mongoose/mongoose.xcodeproj/project.pbxproj
deleted file mode 100644
index bb10c7b..0000000
--- a/build/mac/mongoose/mongoose.xcodeproj/project.pbxproj
+++ /dev/null
@@ -1,218 +0,0 @@
-// !$*UTF8*$!
-{
-	archiveVersion = 1;
-	classes = {
-	};
-	objectVersion = 46;
-	objects = {
-
-/* Begin PBXBuildFile section */
-		4336677717C56DE400D45AD9 /* mongoose.c in Sources */ = {isa = PBXBuildFile; fileRef = 4336677617C56DE400D45AD9 /* mongoose.c */; };
-/* End PBXBuildFile section */
-
-/* Begin PBXFileReference section */
-		4336676E17C56DC700D45AD9 /* libmongoose.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libmongoose.a; sourceTree = BUILT_PRODUCTS_DIR; };
-		4336677617C56DE400D45AD9 /* mongoose.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = mongoose.c; path = ../../../src/mongoose/mongoose.c; sourceTree = "<group>"; };
-/* End PBXFileReference section */
-
-/* Begin PBXFrameworksBuildPhase section */
-		4336676B17C56DC700D45AD9 /* Frameworks */ = {
-			isa = PBXFrameworksBuildPhase;
-			buildActionMask = 2147483647;
-			files = (
-			);
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-/* End PBXFrameworksBuildPhase section */
-
-/* Begin PBXGroup section */
-		4336676517C56DC600D45AD9 = {
-			isa = PBXGroup;
-			children = (
-				4336677517C56DCD00D45AD9 /* src */,
-				4336676F17C56DC700D45AD9 /* Products */,
-			);
-			sourceTree = "<group>";
-		};
-		4336676F17C56DC700D45AD9 /* Products */ = {
-			isa = PBXGroup;
-			children = (
-				4336676E17C56DC700D45AD9 /* libmongoose.a */,
-			);
-			name = Products;
-			sourceTree = "<group>";
-		};
-		4336677517C56DCD00D45AD9 /* src */ = {
-			isa = PBXGroup;
-			children = (
-				4336677617C56DE400D45AD9 /* mongoose.c */,
-			);
-			name = src;
-			sourceTree = "<group>";
-		};
-/* End PBXGroup section */
-
-/* Begin PBXHeadersBuildPhase section */
-		4336676C17C56DC700D45AD9 /* Headers */ = {
-			isa = PBXHeadersBuildPhase;
-			buildActionMask = 2147483647;
-			files = (
-			);
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-/* End PBXHeadersBuildPhase section */
-
-/* Begin PBXNativeTarget section */
-		4336676D17C56DC700D45AD9 /* mongoose */ = {
-			isa = PBXNativeTarget;
-			buildConfigurationList = 4336677217C56DC700D45AD9 /* Build configuration list for PBXNativeTarget "mongoose" */;
-			buildPhases = (
-				4336676A17C56DC700D45AD9 /* Sources */,
-				4336676B17C56DC700D45AD9 /* Frameworks */,
-				4336676C17C56DC700D45AD9 /* Headers */,
-			);
-			buildRules = (
-			);
-			dependencies = (
-			);
-			name = mongoose;
-			productName = mongoose;
-			productReference = 4336676E17C56DC700D45AD9 /* libmongoose.a */;
-			productType = "com.apple.product-type.library.static";
-		};
-/* End PBXNativeTarget section */
-
-/* Begin PBXProject section */
-		4336676617C56DC600D45AD9 /* Project object */ = {
-			isa = PBXProject;
-			attributes = {
-				LastUpgradeCheck = 0460;
-				ORGANIZATIONNAME = "Cass Everitt";
-			};
-			buildConfigurationList = 4336676917C56DC600D45AD9 /* Build configuration list for PBXProject "mongoose" */;
-			compatibilityVersion = "Xcode 3.2";
-			developmentRegion = English;
-			hasScannedForEncodings = 0;
-			knownRegions = (
-				en,
-			);
-			mainGroup = 4336676517C56DC600D45AD9;
-			productRefGroup = 4336676F17C56DC700D45AD9 /* Products */;
-			projectDirPath = "";
-			projectRoot = "";
-			targets = (
-				4336676D17C56DC700D45AD9 /* mongoose */,
-			);
-		};
-/* End PBXProject section */
-
-/* Begin PBXSourcesBuildPhase section */
-		4336676A17C56DC700D45AD9 /* Sources */ = {
-			isa = PBXSourcesBuildPhase;
-			buildActionMask = 2147483647;
-			files = (
-				4336677717C56DE400D45AD9 /* mongoose.c in Sources */,
-			);
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-/* End PBXSourcesBuildPhase section */
-
-/* Begin XCBuildConfiguration section */
-		4336677017C56DC700D45AD9 /* Debug */ = {
-			isa = XCBuildConfiguration;
-			buildSettings = {
-				ALWAYS_SEARCH_USER_PATHS = NO;
-				ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
-				CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
-				CLANG_CXX_LIBRARY = "libc++";
-				CLANG_WARN_CONSTANT_CONVERSION = YES;
-				CLANG_WARN_EMPTY_BODY = YES;
-				CLANG_WARN_ENUM_CONVERSION = YES;
-				CLANG_WARN_INT_CONVERSION = YES;
-				CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
-				COPY_PHASE_STRIP = NO;
-				GCC_C_LANGUAGE_STANDARD = gnu99;
-				GCC_DYNAMIC_NO_PIC = NO;
-				GCC_ENABLE_OBJC_EXCEPTIONS = YES;
-				GCC_OPTIMIZATION_LEVEL = 0;
-				GCC_PREPROCESSOR_DEFINITIONS = (
-					"DEBUG=1",
-					"$(inherited)",
-				);
-				GCC_SYMBOLS_PRIVATE_EXTERN = NO;
-				GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
-				GCC_WARN_ABOUT_RETURN_TYPE = YES;
-				GCC_WARN_UNINITIALIZED_AUTOS = YES;
-				GCC_WARN_UNUSED_VARIABLE = YES;
-				MACOSX_DEPLOYMENT_TARGET = 10.8;
-				ONLY_ACTIVE_ARCH = YES;
-				SDKROOT = "";
-			};
-			name = Debug;
-		};
-		4336677117C56DC700D45AD9 /* Release */ = {
-			isa = XCBuildConfiguration;
-			buildSettings = {
-				ALWAYS_SEARCH_USER_PATHS = NO;
-				ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
-				CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
-				CLANG_CXX_LIBRARY = "libc++";
-				CLANG_WARN_CONSTANT_CONVERSION = YES;
-				CLANG_WARN_EMPTY_BODY = YES;
-				CLANG_WARN_ENUM_CONVERSION = YES;
-				CLANG_WARN_INT_CONVERSION = YES;
-				CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
-				COPY_PHASE_STRIP = YES;
-				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
-				GCC_C_LANGUAGE_STANDARD = gnu99;
-				GCC_ENABLE_OBJC_EXCEPTIONS = YES;
-				GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
-				GCC_WARN_ABOUT_RETURN_TYPE = YES;
-				GCC_WARN_UNINITIALIZED_AUTOS = YES;
-				GCC_WARN_UNUSED_VARIABLE = YES;
-				MACOSX_DEPLOYMENT_TARGET = 10.8;
-				SDKROOT = "";
-			};
-			name = Release;
-		};
-		4336677317C56DC700D45AD9 /* Debug */ = {
-			isa = XCBuildConfiguration;
-			buildSettings = {
-				EXECUTABLE_PREFIX = lib;
-				PRODUCT_NAME = "$(TARGET_NAME)";
-			};
-			name = Debug;
-		};
-		4336677417C56DC700D45AD9 /* Release */ = {
-			isa = XCBuildConfiguration;
-			buildSettings = {
-				EXECUTABLE_PREFIX = lib;
-				PRODUCT_NAME = "$(TARGET_NAME)";
-			};
-			name = Release;
-		};
-/* End XCBuildConfiguration section */
-
-/* Begin XCConfigurationList section */
-		4336676917C56DC600D45AD9 /* Build configuration list for PBXProject "mongoose" */ = {
-			isa = XCConfigurationList;
-			buildConfigurations = (
-				4336677017C56DC700D45AD9 /* Debug */,
-				4336677117C56DC700D45AD9 /* Release */,
-			);
-			defaultConfigurationIsVisible = 0;
-			defaultConfigurationName = Release;
-		};
-		4336677217C56DC700D45AD9 /* Build configuration list for PBXNativeTarget "mongoose" */ = {
-			isa = XCConfigurationList;
-			buildConfigurations = (
-				4336677317C56DC700D45AD9 /* Debug */,
-				4336677417C56DC700D45AD9 /* Release */,
-			);
-			defaultConfigurationIsVisible = 0;
-			defaultConfigurationName = Release;
-		};
-/* End XCConfigurationList section */
-	};
-	rootObject = 4336676617C56DC600D45AD9 /* Project object */;
-}
diff --git a/build/ppapi/vs2010/Regal/Libraries.sln b/build/ppapi/vs2010/Regal/Libraries.sln
index f6eefed..88451b3 100644
--- a/build/ppapi/vs2010/Regal/Libraries.sln
+++ b/build/ppapi/vs2010/Regal/Libraries.sln
@@ -25,7 +25,7 @@
 	ProjectSection(ProjectDependencies) = postProject
 	EndProjectSection
 EndProject
-Project("{CF05FE22-B763-D96E-C64D-312608111C07}") = "mongooselib", "mongooselib.vcxproj", "{256E64B8-F766-061C-45F8-25B51B7CA24E}"
+Project("{CF05FE22-B763-D96E-C64D-312608111C07}") = "civetweblib", "civetweblib.vcxproj", "{256E64B8-F766-061C-45F8-25B51B7CA24E}"
 	ProjectSection(ProjectDependencies) = postProject
 	EndProjectSection
 EndProject
diff --git a/build/ppapi/vs2010/Regal/Regal.sln b/build/ppapi/vs2010/Regal/Regal.sln
index 3d86f14..44a4cc0 100644
--- a/build/ppapi/vs2010/Regal/Regal.sln
+++ b/build/ppapi/vs2010/Regal/Regal.sln
@@ -49,7 +49,7 @@
 		{12EBE7B9-A6BF-51C2-BC7A-A743E21C7B99} = {12EBE7B9-A6BF-51C2-BC7A-A743E21C7B99}

 	EndProjectSection

 EndProject

-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mongooselib", "mongooselib.vcxproj", "{256E64B8-F766-061C-45F8-25B51B7CA24E}"

+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "civetweblib", "civetweblib.vcxproj", "{256E64B8-F766-061C-45F8-25B51B7CA24E}"

 EndProject

 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "md5lib", "md5lib.vcxproj", "{EF516F6A-1965-7089-C2CA-65778D394F08}"

 EndProject

diff --git a/build/ppapi/vs2010/Regal/Regal.vcxproj b/build/ppapi/vs2010/Regal/Regal.vcxproj
index 20adaef..1c29475 100644
--- a/build/ppapi/vs2010/Regal/Regal.vcxproj
+++ b/build/ppapi/vs2010/Regal/Regal.vcxproj
@@ -72,7 +72,7 @@
     <ClCompile>

       <Optimization>MaxSpeed</Optimization>

       <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>

-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

       <PreprocessorDefinitions>REGAL_WIN_TLS=1;REGAL_DECL_EXPORT;REGAL_SYS_WGL_DECLARE_WGL;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>

       <StringPooling>true</StringPooling>

       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>

@@ -88,7 +88,7 @@
       <DisableSpecificWarnings>4996</DisableSpecificWarnings>

     </ClCompile>

     <Link>

-      <AdditionalDependencies>mongooselib.lib;md5lib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>

+      <AdditionalDependencies>civetweblib.lib;md5lib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>

       <OutputFile>Release\Win32\regal32.dll</OutputFile>

       <SuppressStartupBanner>true</SuppressStartupBanner>

       <AdditionalLibraryDirectories>Release\Win32\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>

@@ -110,7 +110,7 @@
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">

     <ClCompile>

       <Optimization>Disabled</Optimization>

-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

       <PreprocessorDefinitions>REGAL_WIN_TLS=1;REGAL_DECL_EXPORT;REGAL_SYS_WGL_DECLARE_WGL;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>

       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>

       <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>

@@ -126,7 +126,7 @@
       <DisableSpecificWarnings>4996</DisableSpecificWarnings>

     </ClCompile>

     <Link>

-      <AdditionalDependencies>mongooselib.lib;md5lib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>

+      <AdditionalDependencies>civetweblib.lib;md5lib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>

       <OutputFile>Debug\Win32\regal32.dll</OutputFile>

       <SuppressStartupBanner>true</SuppressStartupBanner>

       <AdditionalLibraryDirectories>Debug\Win32\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>

@@ -148,13 +148,13 @@
   </ItemDefinitionGroup>

   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|PPAPI'">

     <Link>

-      <AdditionalDependencies>ppapi_cpp.lib;ppapi.lib;jsonsllib.lib;mongooselib.lib;md5lib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;kernel32.lib;winspool.lib;comdlg32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib</AdditionalDependencies>

+      <AdditionalDependencies>ppapi_cpp.lib;ppapi.lib;jsonsllib.lib;civetweblib.lib;md5lib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;kernel32.lib;winspool.lib;comdlg32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib</AdditionalDependencies>

       <ModuleDefinitionFile>../../../../src/regal/RegalPPAPI.def</ModuleDefinitionFile>

       <SubSystem>Console</SubSystem>

       <AdditionalLibraryDirectories>$(ProjectDir)..\..\..\..\lib\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>

     </Link>

     <ClCompile>

-      <AdditionalIncludeDirectories>../../../../src/jsonsl;../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

+      <AdditionalIncludeDirectories>../../../../src/jsonsl;../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

       <DisableSpecificWarnings>4996</DisableSpecificWarnings>

       <WarningLevel>Level4</WarningLevel>

       <PreprocessorDefinitions>PPAPI;REGAL_NO_TLS;REGAL_WIN_TLS=0;REGAL_DECL_EXPORT;REGAL_SYS_WGL_DECLARE_WGL;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>

@@ -163,13 +163,13 @@
   </ItemDefinitionGroup>

   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|PPAPI'">

     <Link>

-      <AdditionalDependencies>ppapi_cpp.lib;ppapi.lib;jsonsllib.lib;mongooselib.lib;md5lib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;kernel32.lib;winspool.lib;comdlg32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib</AdditionalDependencies>

+      <AdditionalDependencies>ppapi_cpp.lib;ppapi.lib;jsonsllib.lib;civetweblib.lib;md5lib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;kernel32.lib;winspool.lib;comdlg32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib</AdditionalDependencies>

       <ModuleDefinitionFile>../../../../src/regal/RegalPPAPI.def</ModuleDefinitionFile>

       <SubSystem>Console</SubSystem>

       <AdditionalLibraryDirectories>$(ProjectDir)..\..\..\..\lib\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>

     </Link>

     <ClCompile>

-      <AdditionalIncludeDirectories>../../../../src/jsonsl;../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

+      <AdditionalIncludeDirectories>../../../../src/jsonsl;../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

       <DisableSpecificWarnings>4996</DisableSpecificWarnings>

       <WarningLevel>Level4</WarningLevel>

       <PreprocessorDefinitions>PPAPI;REGAL_NO_TLS=1;REGAL_WIN_TLS=0;REGAL_DECL_EXPORT;REGAL_SYS_WGL_DECLARE_WGL;JSONSL_STATE_GENERIC=1;DNDEBUG;REGAL_DECL_EXPORT=1;REGAL_LOG=0;REGAL_LOG_ALL=0;REGAL_LOG_ONCE=0;REGAL_LOG_JSON=0;REGAL_NO_HTTP=1;REGAL_NO_ASSERT=1;REGAL_NO_PNG=1;REGAL_ERROR=0;REGAL_DEBUG=0;REGAL_CACHE=0;REGAL_EMULATION=1;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>

diff --git a/build/ppapi/vs2010/Regal/Regallib.vcxproj b/build/ppapi/vs2010/Regal/Regallib.vcxproj
index aefa86d..f833bd5 100644
--- a/build/ppapi/vs2010/Regal/Regallib.vcxproj
+++ b/build/ppapi/vs2010/Regal/Regallib.vcxproj
@@ -72,7 +72,7 @@
     <ClCompile>

       <Optimization>MaxSpeed</Optimization>

       <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>

-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

       <PreprocessorDefinitions>REGAL_WIN_TLS=1;REGAL_DECL_EXPORT;REGAL_SYS_WGL_DECLARE_WGL;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>

       <StringPooling>true</StringPooling>

       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>

@@ -111,7 +111,7 @@
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">

     <ClCompile>

       <Optimization>Disabled</Optimization>

-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

       <PreprocessorDefinitions>REGAL_WIN_TLS=1;REGAL_DECL_EXPORT;REGAL_SYS_WGL_DECLARE_WGL;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>

       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>

       <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>

@@ -153,7 +153,7 @@
       <AdditionalDependencies>ppapi_cpp.lib;ppapi.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;</AdditionalDependencies>

     </Link>

     <ClCompile>

-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

     </ClCompile>

     <ClCompile>

       <WarningLevel>Level4</WarningLevel>

@@ -166,7 +166,7 @@
       <AdditionalDependencies>ppapi_cpp.lib;ppapi.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;</AdditionalDependencies>

     </Link>

     <ClCompile>

-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

     </ClCompile>

     <ClCompile>

       <WarningLevel>Level4</WarningLevel>

diff --git a/build/ppapi/vs2010/Regal/Regalm.vcxproj b/build/ppapi/vs2010/Regal/Regalm.vcxproj
index 52266ef..05232a5 100644
--- a/build/ppapi/vs2010/Regal/Regalm.vcxproj
+++ b/build/ppapi/vs2010/Regal/Regalm.vcxproj
@@ -66,7 +66,7 @@
     <ClCompile>

       <Optimization>MaxSpeed</Optimization>

       <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>

-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

       <PreprocessorDefinitions>REGAL_WIN_TLS=1;REGAL_NAMESPACE;REGAL_DECL_EXPORT;REGAL_SYS_WGL_DECLARE_WGL;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>

       <StringPooling>true</StringPooling>

       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>

@@ -82,7 +82,7 @@
       <DisableSpecificWarnings>4996</DisableSpecificWarnings>

     </ClCompile>

     <Link>

-      <AdditionalDependencies>mongooselib.lib;md5lib.lib;pnglib.lib;zlib.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>

+      <AdditionalDependencies>civetweblib.lib;md5lib.lib;pnglib.lib;zlib.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>

       <OutputFile>Release\Win32\regalm32.dll</OutputFile>

       <SuppressStartupBanner>true</SuppressStartupBanner>

       <AdditionalLibraryDirectories>Release\Win32\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>

@@ -104,7 +104,7 @@
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">

     <ClCompile>

       <Optimization>Disabled</Optimization>

-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

       <PreprocessorDefinitions>REGAL_WIN_TLS=1;REGAL_NAMESPACE;REGAL_DECL_EXPORT;REGAL_SYS_WGL_DECLARE_WGL;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>

       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>

       <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>

@@ -120,7 +120,7 @@
       <DisableSpecificWarnings>4996</DisableSpecificWarnings>

     </ClCompile>

     <Link>

-      <AdditionalDependencies>mongooselib.lib;md5lib.lib;pnglib.lib;zlib.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>

+      <AdditionalDependencies>civetweblib.lib;md5lib.lib;pnglib.lib;zlib.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>

       <OutputFile>Debug\Win32\regalm32.dll</OutputFile>

       <SuppressStartupBanner>true</SuppressStartupBanner>

       <AdditionalLibraryDirectories>Debug\Win32\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>

@@ -142,12 +142,12 @@
   </ItemDefinitionGroup>

   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|PPAPI'">

     <Link>

-      <AdditionalDependencies>ppapi_cpp.lib;ppapi.lib;mongooselib.lib;md5lib.lib;pnglib.lib;zlib.lib;ws2_32.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;ppapi_cpp.lib;ppapi.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;</AdditionalDependencies>

+      <AdditionalDependencies>ppapi_cpp.lib;ppapi.lib;civetweblib.lib;md5lib.lib;pnglib.lib;zlib.lib;ws2_32.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;ppapi_cpp.lib;ppapi.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;</AdditionalDependencies>

       <ModuleDefinitionFile>../../../../src/regal/RegalPPAPI.def</ModuleDefinitionFile>

       <AdditionalLibraryDirectories>win\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>

     </Link>

     <ClCompile>

-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

       <WarningLevel>Level4</WarningLevel>

       <PreprocessorDefinitions>PPAPI;REGAL_NO_TLS;REGAL_WIN_TLS=0;REGAL_DECL_EXPORT;REGAL_SYS_WGL_DECLARE_WGL;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>

       <DisableSpecificWarnings>4996</DisableSpecificWarnings>

@@ -155,12 +155,12 @@
   </ItemDefinitionGroup>

   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|PPAPI'">

     <Link>

-      <AdditionalDependencies>ppapi_cpp.lib;ppapi.lib;mongooselib.lib;md5lib.lib;pnglib.lib;zlib.lib;ws2_32.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;</AdditionalDependencies>

+      <AdditionalDependencies>ppapi_cpp.lib;ppapi.lib;civetweblib.lib;md5lib.lib;pnglib.lib;zlib.lib;ws2_32.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;</AdditionalDependencies>

       <ModuleDefinitionFile>../../../../src/regal/RegalPPAPI.def</ModuleDefinitionFile>

       <AdditionalLibraryDirectories>win\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>

     </Link>

     <ClCompile>

-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

       <WarningLevel>Level4</WarningLevel>

       <PreprocessorDefinitions>PPAPI;REGAL_NO_TLS;REGAL_WIN_TLS=0;REGAL_DECL_EXPORT;REGAL_SYS_WGL_DECLARE_WGL;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>

     </ClCompile>

diff --git a/build/ppapi/vs2010/Regal/Regalmlib.vcxproj b/build/ppapi/vs2010/Regal/Regalmlib.vcxproj
index 58fe278..c3e091e 100644
--- a/build/ppapi/vs2010/Regal/Regalmlib.vcxproj
+++ b/build/ppapi/vs2010/Regal/Regalmlib.vcxproj
@@ -72,7 +72,7 @@
     <ClCompile>

       <Optimization>MaxSpeed</Optimization>

       <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>

-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

       <PreprocessorDefinitions>REGAL_WIN_TLS=1;REGAL_NAMESPACE;REGAL_DECL_EXPORT;REGAL_SYS_WGL_DECLARE_WGL;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>

       <StringPooling>true</StringPooling>

       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>

@@ -111,7 +111,7 @@
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">

     <ClCompile>

       <Optimization>Disabled</Optimization>

-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

       <PreprocessorDefinitions>REGAL_WIN_TLS=1;REGAL_NAMESPACE;REGAL_DECL_EXPORT;REGAL_SYS_WGL_DECLARE_WGL;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>

       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>

       <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>

@@ -153,7 +153,7 @@
       <AdditionalDependencies>ppapi_cpp.lib;ppapi.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;</AdditionalDependencies>

     </Link>

     <ClCompile>

-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

       <WarningLevel>Level4</WarningLevel>

       <PreprocessorDefinitions>PPAPI;REGAL_NO_TLS;REGAL_WIN_TLS=0;REGAL_DECL_EXPORT;REGAL_SYS_WGL_DECLARE_WGL;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>

       <DisableSpecificWarnings>4996</DisableSpecificWarnings>

@@ -164,7 +164,7 @@
       <AdditionalDependencies>ppapi_cpp.lib;ppapi.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;</AdditionalDependencies>

     </Link>

     <ClCompile>

-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>

       <WarningLevel>Level4</WarningLevel>

       <PreprocessorDefinitions>PPAPI;REGAL_NO_TLS;REGAL_WIN_TLS=0;REGAL_DECL_EXPORT;REGAL_SYS_WGL_DECLARE_WGL;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>

       <DisableSpecificWarnings>4996</DisableSpecificWarnings>

diff --git a/build/ppapi/vs2010/Regal/Regalp.vcxproj b/build/ppapi/vs2010/Regal/Regalp.vcxproj
index 381cf44..14cb32b 100644
--- a/build/ppapi/vs2010/Regal/Regalp.vcxproj
+++ b/build/ppapi/vs2010/Regal/Regalp.vcxproj
@@ -74,7 +74,7 @@
     <ClCompile>
       <Optimization>MaxSpeed</Optimization>
       <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>REGAL_WIN_TLS=1;REGAL_POINTER=1;REGAL_DECL_EXPORT;REGAL_SYS_WGL_DECLARE_WGL;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <StringPooling>true</StringPooling>
       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
@@ -90,7 +90,7 @@
       <DisableSpecificWarnings>4996</DisableSpecificWarnings>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>mongooselib.lib;md5lib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>civetweblib.lib;md5lib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <OutputFile>Release\Win32\regalp.dll</OutputFile>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Release\Win32\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
@@ -113,7 +113,7 @@
     <ClCompile>
       <Optimization>MaxSpeed</Optimization>
       <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>REGAL_WIN_TLS=1;REGAL_POINTER=1;REGAL_DECL_EXPORT;REGAL_SYS_WGL_DECLARE_WGL;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <StringPooling>true</StringPooling>
       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
@@ -130,7 +130,7 @@
       <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>mongooselib.lib;md5lib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>civetweblib.lib;md5lib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <OutputFile>Release\x64\regalp.dll</OutputFile>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Release\x64\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
@@ -151,7 +151,7 @@
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
     <ClCompile>
       <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>REGAL_WIN_TLS=1;REGAL_POINTER=1;REGAL_DECL_EXPORT;REGAL_SYS_WGL_DECLARE_WGL;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
       <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
@@ -167,7 +167,7 @@
       <DisableSpecificWarnings>4996</DisableSpecificWarnings>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>mongooselib.lib;md5lib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>civetweblib.lib;md5lib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <OutputFile>Debug\Win32\regalp.dll</OutputFile>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Debug\Win32\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
@@ -190,7 +190,7 @@
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
     <ClCompile>
       <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>REGAL_WIN_TLS=1;REGAL_POINTER=1;REGAL_DECL_EXPORT;REGAL_SYS_WGL_DECLARE_WGL;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
       <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
@@ -206,7 +206,7 @@
       <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>mongooselib.lib;md5lib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>civetweblib.lib;md5lib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <OutputFile>Debug\x64\regalp.dll</OutputFile>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Debug\x64\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
diff --git a/build/ppapi/vs2010/Regal/mongooselib.vcxproj b/build/ppapi/vs2010/Regal/civetweb.vcxproj
similarity index 88%
rename from build/ppapi/vs2010/Regal/mongooselib.vcxproj
rename to build/ppapi/vs2010/Regal/civetweb.vcxproj
index 94d9790..0d04fe1 100644
--- a/build/ppapi/vs2010/Regal/mongooselib.vcxproj
+++ b/build/ppapi/vs2010/Regal/civetweb.vcxproj
@@ -19,7 +19,7 @@
     </ProjectConfiguration>
   </ItemGroup>
   <PropertyGroup Label="Globals">
-    <ProjectName>mongooselib</ProjectName>
+    <ProjectName>civetweblib</ProjectName>
     <ProjectGuid>{256E64B8-F766-061C-45F8-25B51B7CA24E}</ProjectGuid>
   </PropertyGroup>
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
@@ -52,9 +52,9 @@
   <PropertyGroup>
     <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
     <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Release\Win32\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Release\Win32\mongooselib\</IntDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Release\Win32\civetweblib\</IntDir>
     <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Debug\Win32\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Debug\Win32\mongooselib\</IntDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Debug\Win32\civetweblib\</IntDir>
     <NaClAddInVersion Condition="'$(Configuration)|$(Platform)'=='Debug|PPAPI'">1</NaClAddInVersion>
     <IncludePath Condition="'$(Configuration)|$(Platform)'=='Debug|PPAPI'">$(VSNaClSDKRoot)include;$(VSNaClSDKRoot)include\win;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkDir)include;$(FrameworkSDKDir)\include;</IncludePath>
     <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Debug|PPAPI'">$(VSNaClSDKRoot)lib\win_x86_32_host\$(Configuration);$(VCInstallDir)lib;$(VCInstallDir)atlmfc\lib;$(WindowsSdkDir)lib;$(FrameworkSDKDir)\lib</LibraryPath>
@@ -63,8 +63,8 @@
     <IncludePath Condition="'$(Configuration)|$(Platform)'=='Release|PPAPI'">$(VSNaClSDKRoot)include;$(VSNaClSDKRoot)include\win;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkDir)include;$(FrameworkSDKDir)\include;</IncludePath>
     <LibraryPath Condition="'$(Configuration)|$(Platform)'=='Release|PPAPI'">$(VSNaClSDKRoot)lib\win_x86_32_host\$(Configuration);$(VCInstallDir)lib;$(VCInstallDir)atlmfc\lib;$(WindowsSdkDir)lib;$(FrameworkSDKDir)\lib</LibraryPath>
     <ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Release|PPAPI'">$(VCInstallDir)bin;$(WindowsSdkDir)bin\NETFX 4.0 Tools;$(WindowsSdkDir)bin;$(VSInstallDir)Common7\Tools\bin;$(VSInstallDir)Common7\tools;$(VSInstallDir)Common7\ide;$(ProgramFiles)\HTML Help Workshop;$(FrameworkSDKDir)\bin;$(MSBuildToolsPath32);$(VSInstallDir);$(SystemRoot)\SysWow64;$(FxCopDir);$(PATH);</ExecutablePath>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|PPAPI'">win\$(Configuration)\mongooselib\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|PPAPI'">win\$(Configuration)\mongooselib\</IntDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|PPAPI'">win\$(Configuration)\civetweblib\</IntDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|PPAPI'">win\$(Configuration)\civetweblib\</IntDir>
     <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|PPAPI'">$(ProjectDir)..\..\..\..\lib\</OutDir>
     <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|PPAPI'">$(ProjectDir)..\..\..\..\lib\</OutDir>
   </PropertyGroup>
@@ -72,16 +72,16 @@
     <ClCompile>
       <Optimization>MaxSpeed</Optimization>
       <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
-      <AdditionalIncludeDirectories>../../../../src/mongoose;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/civetweb;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <StringPooling>true</StringPooling>
       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
       <FunctionLevelLinking>true</FunctionLevelLinking>
       <PrecompiledHeader>
       </PrecompiledHeader>
-      <AssemblerListingLocation>Release\Win32\mongooselib\</AssemblerListingLocation>
-      <ObjectFileName>Release\Win32\mongooselib\</ObjectFileName>
-      <ProgramDataBaseFileName>Release\Win32\mongooselib.pdb</ProgramDataBaseFileName>
+      <AssemblerListingLocation>Release\Win32\civetweblib\</AssemblerListingLocation>
+      <ObjectFileName>Release\Win32\civetweblib\</ObjectFileName>
+      <ProgramDataBaseFileName>Release\Win32\civetweblib.pdb</ProgramDataBaseFileName>
       <WarningLevel>Level3</WarningLevel>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <CompileAs>Default</CompileAs>
@@ -89,15 +89,15 @@
     </ClCompile>
     <Link>
       <AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
-      <OutputFile>Release\Win32\mongooselib.lib</OutputFile>
+      <OutputFile>Release\Win32\civetweblib.lib</OutputFile>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Release\Win32\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <ModuleDefinitionFile>
       </ModuleDefinitionFile>
-      <ProgramDatabaseFile>Release\Win32\mongooselib.pdb</ProgramDatabaseFile>
+      <ProgramDatabaseFile>Release\Win32\civetweblib.pdb</ProgramDatabaseFile>
       <SubSystem>Console</SubSystem>
       <TargetMachine>MachineX86</TargetMachine>
-      <ImportLibrary>Release\Win32\mongooselib.lib</ImportLibrary>
+      <ImportLibrary>Release\Win32\civetweblib.lib</ImportLibrary>
     </Link>
     <Midl>
       <HeaderFileName>
@@ -111,15 +111,15 @@
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
     <ClCompile>
       <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>../../../../src/mongoose;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/civetweb;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
       <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
       <PrecompiledHeader>
       </PrecompiledHeader>
-      <AssemblerListingLocation>Debug\Win32\mongooselib\</AssemblerListingLocation>
-      <ObjectFileName>Debug\Win32\mongooselib\</ObjectFileName>
-      <ProgramDataBaseFileName>Debug\Win32\mongooselib.pdb</ProgramDataBaseFileName>
+      <AssemblerListingLocation>Debug\Win32\civetweblib\</AssemblerListingLocation>
+      <ObjectFileName>Debug\Win32\civetweblib\</ObjectFileName>
+      <ProgramDataBaseFileName>Debug\Win32\civetweblib.pdb</ProgramDataBaseFileName>
       <WarningLevel>Level3</WarningLevel>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
@@ -128,16 +128,16 @@
     </ClCompile>
     <Link>
       <AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
-      <OutputFile>Debug\Win32\mongooselib.lib</OutputFile>
+      <OutputFile>Debug\Win32\civetweblib.lib</OutputFile>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Debug\Win32\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <ModuleDefinitionFile>
       </ModuleDefinitionFile>
       <GenerateDebugInformation>true</GenerateDebugInformation>
-      <ProgramDatabaseFile>Debug\Win32\mongooselib.pdb</ProgramDatabaseFile>
+      <ProgramDatabaseFile>Debug\Win32\civetweblib.pdb</ProgramDatabaseFile>
       <SubSystem>Console</SubSystem>
       <TargetMachine>MachineX86</TargetMachine>
-      <ImportLibrary>Debug\Win32\mongooselib.lib</ImportLibrary>
+      <ImportLibrary>Debug\Win32\civetweblib.lib</ImportLibrary>
     </Link>
     <Midl>
       <HeaderFileName>
@@ -153,7 +153,7 @@
       <AdditionalDependencies>ppapi_cpp.lib;ppapi.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;</AdditionalDependencies>
     </Link>
     <ClCompile>
-      <AdditionalIncludeDirectories>../../../../src/mongoose;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/civetweb;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
     </ClCompile>
     <ClCompile>
       <WarningLevel>Level3</WarningLevel>
@@ -166,7 +166,7 @@
       <AdditionalDependencies>ppapi_cpp.lib;ppapi.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;</AdditionalDependencies>
     </Link>
     <ClCompile>
-      <AdditionalIncludeDirectories>../../../../src/mongoose;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/civetweb;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
     </ClCompile>
     <ClCompile>
       <WarningLevel>Level3</WarningLevel>
@@ -178,7 +178,7 @@
     </ClCompile>
   </ItemDefinitionGroup>
   <ItemGroup>
-    <ClCompile Include="..\..\..\..\src\mongoose\mongoose.c" />
+    <ClCompile Include="..\..\..\..\src\civetweb\civetweb.c" />
   </ItemGroup>
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
   <ImportGroup Label="ExtensionTargets">
diff --git a/build/ppapi/vs2010/Regal/dreamtorus_static.vcxproj b/build/ppapi/vs2010/Regal/dreamtorus_static.vcxproj
index 89bf13e..50834b9 100644
--- a/build/ppapi/vs2010/Regal/dreamtorus_static.vcxproj
+++ b/build/ppapi/vs2010/Regal/dreamtorus_static.vcxproj
@@ -90,7 +90,7 @@
       <DisableSpecificWarnings>4996</DisableSpecificWarnings>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>winmm.lib;ws2_32.lib;regalglutlib.lib;regalglulib.lib;regallib.lib;mongooselib.lib;md5lib.lib;pnglib.lib;zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>winmm.lib;ws2_32.lib;regalglutlib.lib;regalglulib.lib;regallib.lib;civetweblib.lib;md5lib.lib;pnglib.lib;zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <OutputFile>Release\Win32\dreamtorus_static.exe</OutputFile>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Release\Win32\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
@@ -130,7 +130,7 @@
       <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>winmm.lib;ws2_32.lib;regalglutlib.lib;regalglulib.lib;regallib.lib;mongooselib.lib;md5lib.lib;pnglib.lib;zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>winmm.lib;ws2_32.lib;regalglutlib.lib;regalglulib.lib;regallib.lib;civetweblib.lib;md5lib.lib;pnglib.lib;zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <OutputFile>Release\x64\dreamtorus_static.exe</OutputFile>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Release\x64\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
@@ -167,7 +167,7 @@
       <DisableSpecificWarnings>4996</DisableSpecificWarnings>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>winmm.lib;ws2_32.lib;regalglutlib.lib;regalglulib.lib;regallib.lib;mongooselib.lib;md5lib.lib;pnglib.lib;zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>winmm.lib;ws2_32.lib;regalglutlib.lib;regalglulib.lib;regallib.lib;civetweblib.lib;md5lib.lib;pnglib.lib;zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <OutputFile>Debug\Win32\dreamtorus_static.exe</OutputFile>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Debug\Win32\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
@@ -206,7 +206,7 @@
       <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>winmm.lib;ws2_32.lib;regalglutlib.lib;regalglulib.lib;regallib.lib;mongooselib.lib;md5lib.lib;pnglib.lib;zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>winmm.lib;ws2_32.lib;regalglutlib.lib;regalglulib.lib;regallib.lib;civetweblib.lib;md5lib.lib;pnglib.lib;zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <OutputFile>Debug\x64\dreamtorus_static.exe</OutputFile>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Debug\x64\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
diff --git a/build/regal.inc b/build/regal.inc
index 022b079..5545ef4 100644
--- a/build/regal.inc
+++ b/build/regal.inc
@@ -132,7 +132,7 @@
 REGAL.INCLUDE   += -Isrc/regal
 REGAL.INCLUDE   += -Isrc/zlib/include
 REGAL.INCLUDE   += -Isrc/libpng/include
-REGAL.INCLUDE   += -Isrc/mongoose
+REGAL.INCLUDE   += -Isrc/civetweb
 REGAL.INCLUDE   += -Isrc/md5/include
 REGAL.INCLUDE   += -Isrc/lookup3
 REGAL.INCLUDE   += -Isrc/jsonsl
diff --git a/build/win32/vs2010/Regal/All.sln b/build/win32/vs2010/Regal/All.sln
index 4618799..24ea43b 100644
--- a/build/win32/vs2010/Regal/All.sln
+++ b/build/win32/vs2010/Regal/All.sln
@@ -2,7 +2,7 @@
 # Visual Studio 2010
 Project("{CF05FE22-B763-D96E-C64D-312608111C07}") = "Regal", "Regal.vcxproj", "{6B2786AC-DF6B-8B13-DE42-875D8D9194D9}"
 	ProjectSection(ProjectDependencies) = postProject
-		{256E64B8-F766-061C-45F8-25B51B7CA24E} = {256E64B8-F766-061C-45F8-25B51B7CA24E}
+		{DF066256-E0AD-E016-6F07-52E868F96C02} = {DF066256-E0AD-E016-6F07-52E868F96C02}
 		{EF516F6A-1965-7089-C2CA-65778D394F08} = {EF516F6A-1965-7089-C2CA-65778D394F08}
 		{12EBE7B9-A6BF-51C2-BC7A-A743E21C7B99} = {12EBE7B9-A6BF-51C2-BC7A-A743E21C7B99}
 		{9C419167-D705-A241-8927-763A6F9A5016} = {9C419167-D705-A241-8927-763A6F9A5016}
@@ -18,7 +18,7 @@
 EndProject
 Project("{CF05FE22-B763-D96E-C64D-312608111C07}") = "Regalm", "Regalm.vcxproj", "{687DE0BC-8B42-53E9-FB1A-C750ED5CD57C}"
 	ProjectSection(ProjectDependencies) = postProject
-		{256E64B8-F766-061C-45F8-25B51B7CA24E} = {256E64B8-F766-061C-45F8-25B51B7CA24E}
+		{DF066256-E0AD-E016-6F07-52E868F96C02} = {DF066256-E0AD-E016-6F07-52E868F96C02}
 		{EF516F6A-1965-7089-C2CA-65778D394F08} = {EF516F6A-1965-7089-C2CA-65778D394F08}
 		{12EBE7B9-A6BF-51C2-BC7A-A743E21C7B99} = {12EBE7B9-A6BF-51C2-BC7A-A743E21C7B99}
 		{9C419167-D705-A241-8927-763A6F9A5016} = {9C419167-D705-A241-8927-763A6F9A5016}
@@ -37,7 +37,7 @@
 		{B2F73D1B-8FA3-518D-0F85-9AAD20EF1E1C} = {B2F73D1B-8FA3-518D-0F85-9AAD20EF1E1C}
 	EndProjectSection
 EndProject
-Project("{CF05FE22-B763-D96E-C64D-312608111C07}") = "mongooselib", "mongooselib.vcxproj", "{256E64B8-F766-061C-45F8-25B51B7CA24E}"
+Project("{CF05FE22-B763-D96E-C64D-312608111C07}") = "civetweblib", "civetweblib.vcxproj", "{DF066256-E0AD-E016-6F07-52E868F96C02}"
 	ProjectSection(ProjectDependencies) = postProject
 	EndProjectSection
 EndProject
@@ -125,7 +125,7 @@
 Project("{CF05FE22-B763-D96E-C64D-312608111C07}") = "dreamtorus_static", "dreamtorus_static.vcxproj", "{4279720C-503C-C9A3-8714-4E88F1D2B1E0}"
 	ProjectSection(ProjectDependencies) = postProject
 		{863337BC-C6F9-E4E8-C27D-2D6BAFF72E18} = {863337BC-C6F9-E4E8-C27D-2D6BAFF72E18}
-		{256E64B8-F766-061C-45F8-25B51B7CA24E} = {256E64B8-F766-061C-45F8-25B51B7CA24E}
+		{DF066256-E0AD-E016-6F07-52E868F96C02} = {DF066256-E0AD-E016-6F07-52E868F96C02}
 		{EF516F6A-1965-7089-C2CA-65778D394F08} = {EF516F6A-1965-7089-C2CA-65778D394F08}
 		{12EBE7B9-A6BF-51C2-BC7A-A743E21C7B99} = {12EBE7B9-A6BF-51C2-BC7A-A743E21C7B99}
 		{9C419167-D705-A241-8927-763A6F9A5016} = {9C419167-D705-A241-8927-763A6F9A5016}
@@ -195,14 +195,14 @@
 		{324CD1C8-680A-9A1D-EFE7-A93D7EFFE858}.Release|Win32.ActiveCfg = Release|Win32
 		{324CD1C8-680A-9A1D-EFE7-A93D7EFFE858}.Release|x64.Build.0 = Release|x64
 		{324CD1C8-680A-9A1D-EFE7-A93D7EFFE858}.Release|x64.ActiveCfg = Release|x64
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Debug|Win32.Build.0 = Debug|Win32
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Debug|Win32.ActiveCfg = Debug|Win32
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Debug|x64.Build.0 = Debug|x64
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Debug|x64.ActiveCfg = Debug|x64
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Release|Win32.Build.0 = Release|Win32
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Release|Win32.ActiveCfg = Release|Win32
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Release|x64.Build.0 = Release|x64
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Release|x64.ActiveCfg = Release|x64
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Debug|Win32.Build.0 = Debug|Win32
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Debug|Win32.ActiveCfg = Debug|Win32
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Debug|x64.Build.0 = Debug|x64
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Debug|x64.ActiveCfg = Debug|x64
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Release|Win32.Build.0 = Release|Win32
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Release|Win32.ActiveCfg = Release|Win32
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Release|x64.Build.0 = Release|x64
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Release|x64.ActiveCfg = Release|x64
 		{EF516F6A-1965-7089-C2CA-65778D394F08}.Debug|Win32.Build.0 = Debug|Win32
 		{EF516F6A-1965-7089-C2CA-65778D394F08}.Debug|Win32.ActiveCfg = Debug|Win32
 		{EF516F6A-1965-7089-C2CA-65778D394F08}.Debug|x64.Build.0 = Debug|x64
@@ -365,7 +365,7 @@
 		{687DE0BC-8B42-53E9-FB1A-C750ED5CD57C} = {E5C5BB03-8E38-94D5-C4F7-7A59153EF8F2}
 		{5C0D9EFE-80E2-1DA1-7A53-D640CAE643C0} = {E5C5BB03-8E38-94D5-C4F7-7A59153EF8F2}
 		{324CD1C8-680A-9A1D-EFE7-A93D7EFFE858} = {E5C5BB03-8E38-94D5-C4F7-7A59153EF8F2}
-		{256E64B8-F766-061C-45F8-25B51B7CA24E} = {AEB42855-4A0A-CC6C-C503-A2E4DA6AE61A}
+		{DF066256-E0AD-E016-6F07-52E868F96C02} = {AEB42855-4A0A-CC6C-C503-A2E4DA6AE61A}
 		{EF516F6A-1965-7089-C2CA-65778D394F08} = {AEB42855-4A0A-CC6C-C503-A2E4DA6AE61A}
 		{12EBE7B9-A6BF-51C2-BC7A-A743E21C7B99} = {AEB42855-4A0A-CC6C-C503-A2E4DA6AE61A}
 		{9C419167-D705-A241-8927-763A6F9A5016} = {AEB42855-4A0A-CC6C-C503-A2E4DA6AE61A}
diff --git a/build/win32/vs2010/Regal/Libraries.sln b/build/win32/vs2010/Regal/Libraries.sln
index b5c76da..07ac679 100644
--- a/build/win32/vs2010/Regal/Libraries.sln
+++ b/build/win32/vs2010/Regal/Libraries.sln
@@ -25,7 +25,7 @@
 	ProjectSection(ProjectDependencies) = postProject
 	EndProjectSection
 EndProject
-Project("{CF05FE22-B763-D96E-C64D-312608111C07}") = "mongooselib", "mongooselib.vcxproj", "{256E64B8-F766-061C-45F8-25B51B7CA24E}"
+Project("{CF05FE22-B763-D96E-C64D-312608111C07}") = "civetweblib", "civetweblib.vcxproj", "{DF066256-E0AD-E016-6F07-52E868F96C02}"
 	ProjectSection(ProjectDependencies) = postProject
 	EndProjectSection
 EndProject
@@ -123,14 +123,14 @@
 		{EB036E23-0C3C-CD7C-5456-A9C5E6209A4C}.Release|Win32.ActiveCfg = Release|Win32
 		{EB036E23-0C3C-CD7C-5456-A9C5E6209A4C}.Release|x64.Build.0 = Release|x64
 		{EB036E23-0C3C-CD7C-5456-A9C5E6209A4C}.Release|x64.ActiveCfg = Release|x64
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Debug|Win32.Build.0 = Debug|Win32
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Debug|Win32.ActiveCfg = Debug|Win32
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Debug|x64.Build.0 = Debug|x64
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Debug|x64.ActiveCfg = Debug|x64
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Release|Win32.Build.0 = Release|Win32
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Release|Win32.ActiveCfg = Release|Win32
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Release|x64.Build.0 = Release|x64
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Release|x64.ActiveCfg = Release|x64
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Debug|Win32.Build.0 = Debug|Win32
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Debug|Win32.ActiveCfg = Debug|Win32
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Debug|x64.Build.0 = Debug|x64
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Debug|x64.ActiveCfg = Debug|x64
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Release|Win32.Build.0 = Release|Win32
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Release|Win32.ActiveCfg = Release|Win32
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Release|x64.Build.0 = Release|x64
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Release|x64.ActiveCfg = Release|x64
 		{EF516F6A-1965-7089-C2CA-65778D394F08}.Debug|Win32.Build.0 = Debug|Win32
 		{EF516F6A-1965-7089-C2CA-65778D394F08}.Debug|Win32.ActiveCfg = Debug|Win32
 		{EF516F6A-1965-7089-C2CA-65778D394F08}.Debug|x64.Build.0 = Debug|x64
diff --git a/build/win32/vs2010/Regal/Regal.sln b/build/win32/vs2010/Regal/Regal.sln
index e4ad01b..e9600c4 100755
--- a/build/win32/vs2010/Regal/Regal.sln
+++ b/build/win32/vs2010/Regal/Regal.sln
@@ -2,7 +2,7 @@
 # Visual Studio 2010
 Project("{CF05FE22-B763-D96E-C64D-312608111C07}") = "Regal", "Regal.vcxproj", "{6B2786AC-DF6B-8B13-DE42-875D8D9194D9}"
 	ProjectSection(ProjectDependencies) = postProject
-		{256E64B8-F766-061C-45F8-25B51B7CA24E} = {256E64B8-F766-061C-45F8-25B51B7CA24E}
+		{DF066256-E0AD-E016-6F07-52E868F96C02} = {DF066256-E0AD-E016-6F07-52E868F96C02}
 		{EF516F6A-1965-7089-C2CA-65778D394F08} = {EF516F6A-1965-7089-C2CA-65778D394F08}
 		{12EBE7B9-A6BF-51C2-BC7A-A743E21C7B99} = {12EBE7B9-A6BF-51C2-BC7A-A743E21C7B99}
 		{9C419167-D705-A241-8927-763A6F9A5016} = {9C419167-D705-A241-8927-763A6F9A5016}
@@ -18,7 +18,7 @@
 EndProject
 Project("{CF05FE22-B763-D96E-C64D-312608111C07}") = "Regalm", "Regalm.vcxproj", "{687DE0BC-8B42-53E9-FB1A-C750ED5CD57C}"
 	ProjectSection(ProjectDependencies) = postProject
-		{256E64B8-F766-061C-45F8-25B51B7CA24E} = {256E64B8-F766-061C-45F8-25B51B7CA24E}
+		{DF066256-E0AD-E016-6F07-52E868F96C02} = {DF066256-E0AD-E016-6F07-52E868F96C02}
 		{EF516F6A-1965-7089-C2CA-65778D394F08} = {EF516F6A-1965-7089-C2CA-65778D394F08}
 		{12EBE7B9-A6BF-51C2-BC7A-A743E21C7B99} = {12EBE7B9-A6BF-51C2-BC7A-A743E21C7B99}
 		{9C419167-D705-A241-8927-763A6F9A5016} = {9C419167-D705-A241-8927-763A6F9A5016}
@@ -37,7 +37,7 @@
 		{B2F73D1B-8FA3-518D-0F85-9AAD20EF1E1C} = {B2F73D1B-8FA3-518D-0F85-9AAD20EF1E1C}
 	EndProjectSection
 EndProject
-Project("{CF05FE22-B763-D96E-C64D-312608111C07}") = "mongooselib", "mongooselib.vcxproj", "{256E64B8-F766-061C-45F8-25B51B7CA24E}"
+Project("{CF05FE22-B763-D96E-C64D-312608111C07}") = "civetweblib", "civetweblib.vcxproj", "{DF066256-E0AD-E016-6F07-52E868F96C02}"
 	ProjectSection(ProjectDependencies) = postProject
 	EndProjectSection
 EndProject
@@ -118,14 +118,14 @@
 		{324CD1C8-680A-9A1D-EFE7-A93D7EFFE858}.Release|Win32.ActiveCfg = Release|Win32
 		{324CD1C8-680A-9A1D-EFE7-A93D7EFFE858}.Release|x64.Build.0 = Release|x64
 		{324CD1C8-680A-9A1D-EFE7-A93D7EFFE858}.Release|x64.ActiveCfg = Release|x64
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Debug|Win32.Build.0 = Debug|Win32
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Debug|Win32.ActiveCfg = Debug|Win32
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Debug|x64.Build.0 = Debug|x64
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Debug|x64.ActiveCfg = Debug|x64
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Release|Win32.Build.0 = Release|Win32
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Release|Win32.ActiveCfg = Release|Win32
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Release|x64.Build.0 = Release|x64
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Release|x64.ActiveCfg = Release|x64
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Debug|Win32.Build.0 = Debug|Win32
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Debug|Win32.ActiveCfg = Debug|Win32
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Debug|x64.Build.0 = Debug|x64
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Debug|x64.ActiveCfg = Debug|x64
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Release|Win32.Build.0 = Release|Win32
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Release|Win32.ActiveCfg = Release|Win32
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Release|x64.Build.0 = Release|x64
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Release|x64.ActiveCfg = Release|x64
 		{EF516F6A-1965-7089-C2CA-65778D394F08}.Debug|Win32.Build.0 = Debug|Win32
 		{EF516F6A-1965-7089-C2CA-65778D394F08}.Debug|Win32.ActiveCfg = Debug|Win32
 		{EF516F6A-1965-7089-C2CA-65778D394F08}.Debug|x64.Build.0 = Debug|x64
diff --git a/build/win32/vs2010/Regal/Regal.vcxproj b/build/win32/vs2010/Regal/Regal.vcxproj
index 6eb01d4..8ac5cd4 100755
--- a/build/win32/vs2010/Regal/Regal.vcxproj
+++ b/build/win32/vs2010/Regal/Regal.vcxproj
@@ -78,7 +78,7 @@
     <ClCompile>
       <Optimization>MaxSpeed</Optimization>
       <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>REGAL_NO_SQUISH=1;REGAL_SYS_WGL_DECLARE_WGL;REGAL_WIN_TLS=1;_ITERATOR_DEBUG_LEVEL=0;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <StringPooling>true</StringPooling>
       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
@@ -96,7 +96,7 @@
       <MultiProcessorCompilation>true</MultiProcessorCompilation>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>mongooselib.lib;md5lib.lib;jsonsllib.lib;squishlib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>civetweblib.lib;md5lib.lib;jsonsllib.lib;squishlib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Release\Win32\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <ModuleDefinitionFile>../../../../src/regal/Regal.def</ModuleDefinitionFile>
@@ -118,7 +118,7 @@
     <ClCompile>
       <Optimization>MaxSpeed</Optimization>
       <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>REGAL_NO_SQUISH=1;REGAL_SYS_WGL_DECLARE_WGL;REGAL_WIN_TLS=1;_ITERATOR_DEBUG_LEVEL=0;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <StringPooling>true</StringPooling>
       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
@@ -137,7 +137,7 @@
       <MultiProcessorCompilation>true</MultiProcessorCompilation>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>mongooselib.lib;md5lib.lib;jsonsllib.lib;squishlib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>civetweblib.lib;md5lib.lib;jsonsllib.lib;squishlib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Release\x64\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <ModuleDefinitionFile>../../../../src/regal/Regal.def</ModuleDefinitionFile>
@@ -157,7 +157,7 @@
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
     <ClCompile>
       <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>REGAL_NO_SQUISH=1;REGAL_SYS_WGL_DECLARE_WGL;REGAL_WIN_TLS=1;_ITERATOR_DEBUG_LEVEL=0;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
       <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
@@ -175,7 +175,7 @@
       <MultiProcessorCompilation>true</MultiProcessorCompilation>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>mongooselib.lib;md5lib.lib;jsonsllib.lib;squishlib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>civetweblib.lib;md5lib.lib;jsonsllib.lib;squishlib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Debug\Win32\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <ModuleDefinitionFile>../../../../src/regal/Regal.def</ModuleDefinitionFile>
@@ -197,7 +197,7 @@
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
     <ClCompile>
       <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>REGAL_NO_SQUISH=1;REGAL_SYS_WGL_DECLARE_WGL;REGAL_WIN_TLS=1;_ITERATOR_DEBUG_LEVEL=0;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
       <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
@@ -215,7 +215,7 @@
       <MultiProcessorCompilation>true</MultiProcessorCompilation>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>mongooselib.lib;md5lib.lib;jsonsllib.lib;squishlib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>civetweblib.lib;md5lib.lib;jsonsllib.lib;squishlib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Debug\x64\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <ModuleDefinitionFile>../../../../src/regal/Regal.def</ModuleDefinitionFile>
diff --git a/build/win32/vs2010/Regal/RegalTest.sln b/build/win32/vs2010/Regal/RegalTest.sln
index 92d4853..349f34e 100644
--- a/build/win32/vs2010/Regal/RegalTest.sln
+++ b/build/win32/vs2010/Regal/RegalTest.sln
@@ -4,7 +4,7 @@
 	ProjectSection(ProjectDependencies) = postProject
 	EndProjectSection
 EndProject
-Project("{CF05FE22-B763-D96E-C64D-312608111C07}") = "mongooselib", "mongooselib.vcxproj", "{256E64B8-F766-061C-45F8-25B51B7CA24E}"
+Project("{CF05FE22-B763-D96E-C64D-312608111C07}") = "civetweblib", "civetweblib.vcxproj", "{DF066256-E0AD-E016-6F07-52E868F96C02}"
 	ProjectSection(ProjectDependencies) = postProject
 	EndProjectSection
 EndProject
@@ -35,7 +35,7 @@
 Project("{CF05FE22-B763-D96E-C64D-312608111C07}") = "Regaltest", "Regaltest.vcxproj", "{F6188D79-AC4B-7445-0772-B4CEF40D72E1}"
 	ProjectSection(ProjectDependencies) = postProject
 		{863337BC-C6F9-E4E8-C27D-2D6BAFF72E18} = {863337BC-C6F9-E4E8-C27D-2D6BAFF72E18}
-		{256E64B8-F766-061C-45F8-25B51B7CA24E} = {256E64B8-F766-061C-45F8-25B51B7CA24E}
+		{DF066256-E0AD-E016-6F07-52E868F96C02} = {DF066256-E0AD-E016-6F07-52E868F96C02}
 		{EF516F6A-1965-7089-C2CA-65778D394F08} = {EF516F6A-1965-7089-C2CA-65778D394F08}
 		{9C419167-D705-A241-8927-763A6F9A5016} = {9C419167-D705-A241-8927-763A6F9A5016}
 		{B2F73D1B-8FA3-518D-0F85-9AAD20EF1E1C} = {B2F73D1B-8FA3-518D-0F85-9AAD20EF1E1C}
@@ -60,14 +60,14 @@
 		{863337BC-C6F9-E4E8-C27D-2D6BAFF72E18}.Release|Win32.ActiveCfg = Release|Win32
 		{863337BC-C6F9-E4E8-C27D-2D6BAFF72E18}.Release|x64.Build.0 = Release|x64
 		{863337BC-C6F9-E4E8-C27D-2D6BAFF72E18}.Release|x64.ActiveCfg = Release|x64
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Debug|Win32.Build.0 = Debug|Win32
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Debug|Win32.ActiveCfg = Debug|Win32
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Debug|x64.Build.0 = Debug|x64
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Debug|x64.ActiveCfg = Debug|x64
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Release|Win32.Build.0 = Release|Win32
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Release|Win32.ActiveCfg = Release|Win32
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Release|x64.Build.0 = Release|x64
-		{256E64B8-F766-061C-45F8-25B51B7CA24E}.Release|x64.ActiveCfg = Release|x64
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Debug|Win32.Build.0 = Debug|Win32
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Debug|Win32.ActiveCfg = Debug|Win32
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Debug|x64.Build.0 = Debug|x64
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Debug|x64.ActiveCfg = Debug|x64
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Release|Win32.Build.0 = Release|Win32
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Release|Win32.ActiveCfg = Release|Win32
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Release|x64.Build.0 = Release|x64
+		{DF066256-E0AD-E016-6F07-52E868F96C02}.Release|x64.ActiveCfg = Release|x64
 		{EF516F6A-1965-7089-C2CA-65778D394F08}.Debug|Win32.Build.0 = Debug|Win32
 		{EF516F6A-1965-7089-C2CA-65778D394F08}.Debug|Win32.ActiveCfg = Debug|Win32
 		{EF516F6A-1965-7089-C2CA-65778D394F08}.Debug|x64.Build.0 = Debug|x64
diff --git a/build/win32/vs2010/Regal/Regallib.vcxproj b/build/win32/vs2010/Regal/Regallib.vcxproj
index e89d2f0..c525be9 100644
--- a/build/win32/vs2010/Regal/Regallib.vcxproj
+++ b/build/win32/vs2010/Regal/Regallib.vcxproj
@@ -78,7 +78,7 @@
     <ClCompile>
       <Optimization>MaxSpeed</Optimization>
       <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>REGAL_DECL_EXPORT;REGAL_NO_SQUISH=1;REGAL_SYS_WGL_DECLARE_WGL;REGAL_WIN_TLS=1;_ITERATOR_DEBUG_LEVEL=0;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <StringPooling>true</StringPooling>
       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
@@ -118,7 +118,7 @@
     <ClCompile>
       <Optimization>MaxSpeed</Optimization>
       <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>REGAL_DECL_EXPORT;REGAL_NO_SQUISH=1;REGAL_SYS_WGL_DECLARE_WGL;REGAL_WIN_TLS=1;_ITERATOR_DEBUG_LEVEL=0;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <StringPooling>true</StringPooling>
       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
@@ -157,7 +157,7 @@
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
     <ClCompile>
       <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>REGAL_DECL_EXPORT;REGAL_NO_SQUISH=1;REGAL_SYS_WGL_DECLARE_WGL;REGAL_WIN_TLS=1;_ITERATOR_DEBUG_LEVEL=0;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
       <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
@@ -197,7 +197,7 @@
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
     <ClCompile>
       <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>REGAL_DECL_EXPORT;REGAL_NO_SQUISH=1;REGAL_SYS_WGL_DECLARE_WGL;REGAL_WIN_TLS=1;_ITERATOR_DEBUG_LEVEL=0;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
       <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
diff --git a/build/win32/vs2010/Regal/Regalm.vcxproj b/build/win32/vs2010/Regal/Regalm.vcxproj
index 4c225b9..32332e2 100644
--- a/build/win32/vs2010/Regal/Regalm.vcxproj
+++ b/build/win32/vs2010/Regal/Regalm.vcxproj
@@ -78,7 +78,7 @@
     <ClCompile>
       <Optimization>MaxSpeed</Optimization>
       <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>REGAL_NAMESPACE;REGAL_NO_SQUISH=1;REGAL_SYS_WGL_DECLARE_WGL;REGAL_WIN_TLS=1;_ITERATOR_DEBUG_LEVEL=0;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <StringPooling>true</StringPooling>
       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
@@ -96,7 +96,7 @@
       <MultiProcessorCompilation>true</MultiProcessorCompilation>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>mongooselib.lib;md5lib.lib;jsonsllib.lib;squishlib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>civetweblib.lib;md5lib.lib;jsonsllib.lib;squishlib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Release\Win32\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <ModuleDefinitionFile>../../../../src/regal/Regalm.def</ModuleDefinitionFile>
@@ -118,7 +118,7 @@
     <ClCompile>
       <Optimization>MaxSpeed</Optimization>
       <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>REGAL_NAMESPACE;REGAL_NO_SQUISH=1;REGAL_SYS_WGL_DECLARE_WGL;REGAL_WIN_TLS=1;_ITERATOR_DEBUG_LEVEL=0;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <StringPooling>true</StringPooling>
       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
@@ -137,7 +137,7 @@
       <MultiProcessorCompilation>true</MultiProcessorCompilation>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>mongooselib.lib;md5lib.lib;jsonsllib.lib;squishlib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>civetweblib.lib;md5lib.lib;jsonsllib.lib;squishlib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Release\x64\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <ModuleDefinitionFile>../../../../src/regal/Regalm.def</ModuleDefinitionFile>
@@ -157,7 +157,7 @@
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
     <ClCompile>
       <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>REGAL_NAMESPACE;REGAL_NO_SQUISH=1;REGAL_SYS_WGL_DECLARE_WGL;REGAL_WIN_TLS=1;_ITERATOR_DEBUG_LEVEL=0;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
       <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
@@ -175,7 +175,7 @@
       <MultiProcessorCompilation>true</MultiProcessorCompilation>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>mongooselib.lib;md5lib.lib;jsonsllib.lib;squishlib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>civetweblib.lib;md5lib.lib;jsonsllib.lib;squishlib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Debug\Win32\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <ModuleDefinitionFile>../../../../src/regal/Regalm.def</ModuleDefinitionFile>
@@ -197,7 +197,7 @@
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
     <ClCompile>
       <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>REGAL_NAMESPACE;REGAL_NO_SQUISH=1;REGAL_SYS_WGL_DECLARE_WGL;REGAL_WIN_TLS=1;_ITERATOR_DEBUG_LEVEL=0;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
       <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
@@ -215,7 +215,7 @@
       <MultiProcessorCompilation>true</MultiProcessorCompilation>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>mongooselib.lib;md5lib.lib;jsonsllib.lib;squishlib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>civetweblib.lib;md5lib.lib;jsonsllib.lib;squishlib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Debug\x64\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <ModuleDefinitionFile>../../../../src/regal/Regalm.def</ModuleDefinitionFile>
diff --git a/build/win32/vs2010/Regal/Regalmlib.vcxproj b/build/win32/vs2010/Regal/Regalmlib.vcxproj
index a20ddcb..e61e62b 100644
--- a/build/win32/vs2010/Regal/Regalmlib.vcxproj
+++ b/build/win32/vs2010/Regal/Regalmlib.vcxproj
@@ -78,7 +78,7 @@
     <ClCompile>
       <Optimization>MaxSpeed</Optimization>
       <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>REGAL_DECL_EXPORT;REGAL_NAMESPACE;REGAL_NO_SQUISH=1;REGAL_SYS_WGL_DECLARE_WGL;REGAL_WIN_TLS=1;_ITERATOR_DEBUG_LEVEL=0;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <StringPooling>true</StringPooling>
       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
@@ -118,7 +118,7 @@
     <ClCompile>
       <Optimization>MaxSpeed</Optimization>
       <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>REGAL_DECL_EXPORT;REGAL_NAMESPACE;REGAL_NO_SQUISH=1;REGAL_SYS_WGL_DECLARE_WGL;REGAL_WIN_TLS=1;_ITERATOR_DEBUG_LEVEL=0;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <StringPooling>true</StringPooling>
       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
@@ -157,7 +157,7 @@
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
     <ClCompile>
       <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>REGAL_DECL_EXPORT;REGAL_NAMESPACE;REGAL_NO_SQUISH=1;REGAL_SYS_WGL_DECLARE_WGL;REGAL_WIN_TLS=1;_ITERATOR_DEBUG_LEVEL=0;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
       <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
@@ -197,7 +197,7 @@
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
     <ClCompile>
       <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>REGAL_DECL_EXPORT;REGAL_NAMESPACE;REGAL_NO_SQUISH=1;REGAL_SYS_WGL_DECLARE_WGL;REGAL_WIN_TLS=1;_ITERATOR_DEBUG_LEVEL=0;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
       <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
diff --git a/build/win32/vs2010/Regal/Regalp.vcxproj b/build/win32/vs2010/Regal/Regalp.vcxproj
index 23aaac1..0a5638e 100644
--- a/build/win32/vs2010/Regal/Regalp.vcxproj
+++ b/build/win32/vs2010/Regal/Regalp.vcxproj
@@ -74,7 +74,7 @@
     <ClCompile>
       <Optimization>MaxSpeed</Optimization>
       <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>REGAL_WIN_TLS=1;REGAL_POINTER=1;REGAL_DECL_EXPORT;REGAL_SYS_WGL_DECLARE_WGL;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <StringPooling>true</StringPooling>
       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
@@ -90,7 +90,7 @@
       <DisableSpecificWarnings>4996</DisableSpecificWarnings>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>mongooselib.lib;md5lib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>civetweblib.lib;md5lib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <OutputFile>Release\Win32\regalp.dll</OutputFile>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Release\Win32\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
@@ -113,7 +113,7 @@
     <ClCompile>
       <Optimization>MaxSpeed</Optimization>
       <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>REGAL_WIN_TLS=1;REGAL_POINTER=1;REGAL_DECL_EXPORT;REGAL_SYS_WGL_DECLARE_WGL;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <StringPooling>true</StringPooling>
       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
@@ -130,7 +130,7 @@
       <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>mongooselib.lib;md5lib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>civetweblib.lib;md5lib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <OutputFile>Release\x64\regalp.dll</OutputFile>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Release\x64\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
@@ -151,7 +151,7 @@
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
     <ClCompile>
       <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>REGAL_WIN_TLS=1;REGAL_POINTER=1;REGAL_DECL_EXPORT;REGAL_SYS_WGL_DECLARE_WGL;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
       <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
@@ -167,7 +167,7 @@
       <DisableSpecificWarnings>4996</DisableSpecificWarnings>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>mongooselib.lib;md5lib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>civetweblib.lib;md5lib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <OutputFile>Debug\Win32\regalp.dll</OutputFile>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Debug\Win32\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
@@ -190,7 +190,7 @@
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
     <ClCompile>
       <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>REGAL_WIN_TLS=1;REGAL_POINTER=1;REGAL_DECL_EXPORT;REGAL_SYS_WGL_DECLARE_WGL;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
       <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
@@ -206,7 +206,7 @@
       <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>mongooselib.lib;md5lib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>civetweblib.lib;md5lib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <OutputFile>Debug\x64\regalp.dll</OutputFile>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Debug\x64\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
@@ -298,4 +298,4 @@
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
   <ImportGroup Label="ExtensionTargets">
   </ImportGroup>
-</Project>
\ No newline at end of file
+</Project>
diff --git a/build/win32/vs2010/Regal/Regaltest.vcxproj b/build/win32/vs2010/Regal/Regaltest.vcxproj
index ba2a973..5157c43 100644
--- a/build/win32/vs2010/Regal/Regaltest.vcxproj
+++ b/build/win32/vs2010/Regal/Regaltest.vcxproj
@@ -96,7 +96,7 @@
       <MultiProcessorCompilation>true</MultiProcessorCompilation>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>gtestlib.lib;regallib.lib;mongooselib.lib;md5lib.lib;jsonsllib.lib;squishlib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>gtestlib.lib;regallib.lib;civetweblib.lib;md5lib.lib;jsonsllib.lib;squishlib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Release\Win32\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <ModuleDefinitionFile></ModuleDefinitionFile>
@@ -137,7 +137,7 @@
       <MultiProcessorCompilation>true</MultiProcessorCompilation>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>gtestlib.lib;regallib.lib;mongooselib.lib;md5lib.lib;jsonsllib.lib;squishlib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>gtestlib.lib;regallib.lib;civetweblib.lib;md5lib.lib;jsonsllib.lib;squishlib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Release\x64\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <ModuleDefinitionFile></ModuleDefinitionFile>
@@ -175,7 +175,7 @@
       <MultiProcessorCompilation>true</MultiProcessorCompilation>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>gtestlib.lib;regallib.lib;mongooselib.lib;md5lib.lib;jsonsllib.lib;squishlib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>gtestlib.lib;regallib.lib;civetweblib.lib;md5lib.lib;jsonsllib.lib;squishlib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Debug\Win32\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <ModuleDefinitionFile></ModuleDefinitionFile>
@@ -215,7 +215,7 @@
       <MultiProcessorCompilation>true</MultiProcessorCompilation>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>gtestlib.lib;regallib.lib;mongooselib.lib;md5lib.lib;jsonsllib.lib;squishlib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>gtestlib.lib;regallib.lib;civetweblib.lib;md5lib.lib;jsonsllib.lib;squishlib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;advapi32.lib;gdi32.lib;user32.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Debug\x64\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <ModuleDefinitionFile></ModuleDefinitionFile>
diff --git a/build/win32/vs2010/Regal/Regalw.vcxproj b/build/win32/vs2010/Regal/Regalw.vcxproj
index eb87839..564ce55 100644
--- a/build/win32/vs2010/Regal/Regalw.vcxproj
+++ b/build/win32/vs2010/Regal/Regalw.vcxproj
@@ -78,7 +78,7 @@
     <ClCompile>
       <Optimization>MaxSpeed</Optimization>
       <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>REGAL_NO_SQUISH=1;REGAL_SYS_WGL_DECLARE_WGL;REGAL_WIN_TLS=1;REGAL_WRANGLER=1;_ITERATOR_DEBUG_LEVEL=0;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <StringPooling>true</StringPooling>
       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
@@ -118,7 +118,7 @@
     <ClCompile>
       <Optimization>MaxSpeed</Optimization>
       <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>REGAL_NO_SQUISH=1;REGAL_SYS_WGL_DECLARE_WGL;REGAL_WIN_TLS=1;REGAL_WRANGLER=1;_ITERATOR_DEBUG_LEVEL=0;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <StringPooling>true</StringPooling>
       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
@@ -157,7 +157,7 @@
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
     <ClCompile>
       <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>REGAL_NO_SQUISH=1;REGAL_SYS_WGL_DECLARE_WGL;REGAL_WIN_TLS=1;REGAL_WRANGLER=1;_ITERATOR_DEBUG_LEVEL=0;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
       <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
@@ -197,7 +197,7 @@
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
     <ClCompile>
       <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/mongoose;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/boost;../../../../include;../../../../src/civetweb;../../../../src/lookup3;../../../../src/md5/include;../../../../src/libpng/include;../../../../src/zlib/include;../../../../src/squish;../../../../src/jsonsl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>REGAL_NO_SQUISH=1;REGAL_SYS_WGL_DECLARE_WGL;REGAL_WIN_TLS=1;REGAL_WRANGLER=1;_ITERATOR_DEBUG_LEVEL=0;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
       <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
diff --git a/build/win32/vs2010/Regal/mongooselib.vcxproj b/build/win32/vs2010/Regal/civetweb.vcxproj
similarity index 74%
copy from build/win32/vs2010/Regal/mongooselib.vcxproj
copy to build/win32/vs2010/Regal/civetweb.vcxproj
index 02f58cb..9eb2b3b 100644
--- a/build/win32/vs2010/Regal/mongooselib.vcxproj
+++ b/build/win32/vs2010/Regal/civetweb.vcxproj
@@ -19,27 +19,27 @@
     </ProjectConfiguration>
   </ItemGroup>
   <PropertyGroup Label="Globals">
-    <ProjectName>mongooselib</ProjectName>
-    <ProjectGuid>{256E64B8-F766-061C-45F8-25B51B7CA24E}</ProjectGuid>
+    <ProjectName>civetweb</ProjectName>
+    <ProjectGuid>{B15707F8-F826-E261-AC07-A13E4E801650}</ProjectGuid>
   </PropertyGroup>
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <ConfigurationType>Application</ConfigurationType>
     <UseOfMfc>false</UseOfMfc>
     <CharacterSet>Unicode</CharacterSet>
   </PropertyGroup>
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <ConfigurationType>Application</ConfigurationType>
     <UseOfMfc>false</UseOfMfc>
     <CharacterSet>Unicode</CharacterSet>
   </PropertyGroup>
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <ConfigurationType>Application</ConfigurationType>
     <UseOfMfc>false</UseOfMfc>
     <CharacterSet>Unicode</CharacterSet>
   </PropertyGroup>
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
-    <ConfigurationType>StaticLibrary</ConfigurationType>
+    <ConfigurationType>Application</ConfigurationType>
     <UseOfMfc>false</UseOfMfc>
     <CharacterSet>Unicode</CharacterSet>
   </PropertyGroup>
@@ -63,31 +63,31 @@
     <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
     <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Release\Win32\</OutDir>
     <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Release\x64\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Release\Win32\mongooselib\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Release\x64\mongooselib\</IntDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Release\Win32\civetweb\</IntDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Release\x64\civetweb\</IntDir>
     <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Debug\Win32\</OutDir>
     <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Debug\x64\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Debug\Win32\mongooselib\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Debug\x64\mongooselib\</IntDir>
-    <TargetName Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">mongooselib</TargetName>
-    <TargetName Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">mongooselib</TargetName>
-    <TargetName Condition="'$(Configuration)|$(Platform)'=='Release|x64'">mongooselib</TargetName>
-    <TargetName Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">mongooselib</TargetName>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Debug\Win32\civetweb\</IntDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Debug\x64\civetweb\</IntDir>
+    <TargetName Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">civetweb</TargetName>
+    <TargetName Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">civetweb</TargetName>
+    <TargetName Condition="'$(Configuration)|$(Platform)'=='Release|x64'">civetweb</TargetName>
+    <TargetName Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">civetweb</TargetName>
   </PropertyGroup>
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
     <ClCompile>
       <Optimization>MaxSpeed</Optimization>
       <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
-      <AdditionalIncludeDirectories>../../../../src/mongoose;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>DEBUG_TRACE=0;NO_SSL;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>../../../../src/civetweb;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <StringPooling>true</StringPooling>
       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
       <FunctionLevelLinking>true</FunctionLevelLinking>
       <PrecompiledHeader>
       </PrecompiledHeader>
-      <AssemblerListingLocation>Release\Win32\mongooselib\</AssemblerListingLocation>
-      <ObjectFileName>Release\Win32\mongooselib\</ObjectFileName>
-      <ProgramDataBaseFileName>Release\Win32\mongooselib.pdb</ProgramDataBaseFileName>
+      <AssemblerListingLocation>Release\Win32\civetweb\</AssemblerListingLocation>
+      <ObjectFileName>Release\Win32\civetweb\</ObjectFileName>
+      <ProgramDataBaseFileName>Release\Win32\civetweb.pdb</ProgramDataBaseFileName>
       <WarningLevel>Level3</WarningLevel>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <CompileAs>Default</CompileAs>
@@ -96,14 +96,14 @@
       <MultiProcessorCompilation>true</MultiProcessorCompilation>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>civetweblib.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Release\Win32\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <ModuleDefinitionFile></ModuleDefinitionFile>
-      <ProgramDatabaseFile>Release\Win32\mongooselib.pdb</ProgramDatabaseFile>
+      <ProgramDatabaseFile>Release\Win32\civetweb.pdb</ProgramDatabaseFile>
       <SubSystem>Console</SubSystem>
       <TargetMachine>MachineX86</TargetMachine>
-      <ImportLibrary>Release\Win32\mongooselib.lib</ImportLibrary>
+      <ImportLibrary>Release\Win32\civetweb.lib</ImportLibrary>
     </Link>
     <Midl>
       <HeaderFileName>
@@ -118,16 +118,16 @@
     <ClCompile>
       <Optimization>MaxSpeed</Optimization>
       <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
-      <AdditionalIncludeDirectories>../../../../src/mongoose;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>DEBUG_TRACE=0;NO_SSL;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>../../../../src/civetweb;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <StringPooling>true</StringPooling>
       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
       <FunctionLevelLinking>true</FunctionLevelLinking>
       <PrecompiledHeader>
       </PrecompiledHeader>
-      <AssemblerListingLocation>Release\x64\mongooselib\</AssemblerListingLocation>
-      <ObjectFileName>Release\x64\mongooselib\</ObjectFileName>
-      <ProgramDataBaseFileName>Release\x64\mongooselib.pdb</ProgramDataBaseFileName>
+      <AssemblerListingLocation>Release\x64\civetweb\</AssemblerListingLocation>
+      <ObjectFileName>Release\x64\civetweb\</ObjectFileName>
+      <ProgramDataBaseFileName>Release\x64\civetweb.pdb</ProgramDataBaseFileName>
       <WarningLevel>Level3</WarningLevel>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <CompileAs>Default</CompileAs>
@@ -137,13 +137,13 @@
       <MultiProcessorCompilation>true</MultiProcessorCompilation>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>civetweblib.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Release\x64\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <ModuleDefinitionFile></ModuleDefinitionFile>
-      <ProgramDatabaseFile>Release\x64\mongooselib.pdb</ProgramDatabaseFile>
+      <ProgramDatabaseFile>Release\x64\civetweb.pdb</ProgramDatabaseFile>
       <SubSystem>Console</SubSystem>
-      <ImportLibrary>Release\x64\mongooselib.lib</ImportLibrary>
+      <ImportLibrary>Release\x64\civetweb.lib</ImportLibrary>
     </Link>
     <Midl>
       <HeaderFileName>
@@ -157,15 +157,15 @@
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
     <ClCompile>
       <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>../../../../src/mongoose;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>DEBUG_TRACE=0;NO_SSL;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>../../../../src/civetweb;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
       <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
       <PrecompiledHeader>
       </PrecompiledHeader>
-      <AssemblerListingLocation>Debug\Win32\mongooselib\</AssemblerListingLocation>
-      <ObjectFileName>Debug\Win32\mongooselib\</ObjectFileName>
-      <ProgramDataBaseFileName>Debug\Win32\mongooselib.pdb</ProgramDataBaseFileName>
+      <AssemblerListingLocation>Debug\Win32\civetweb\</AssemblerListingLocation>
+      <ObjectFileName>Debug\Win32\civetweb\</ObjectFileName>
+      <ProgramDataBaseFileName>Debug\Win32\civetweb.pdb</ProgramDataBaseFileName>
       <WarningLevel>Level3</WarningLevel>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
@@ -175,15 +175,15 @@
       <MultiProcessorCompilation>true</MultiProcessorCompilation>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>civetweblib.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Debug\Win32\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <ModuleDefinitionFile></ModuleDefinitionFile>
       <GenerateDebugInformation>true</GenerateDebugInformation>
-      <ProgramDatabaseFile>Debug\Win32\mongooselib.pdb</ProgramDatabaseFile>
+      <ProgramDatabaseFile>Debug\Win32\civetweb.pdb</ProgramDatabaseFile>
       <SubSystem>Console</SubSystem>
       <TargetMachine>MachineX86</TargetMachine>
-      <ImportLibrary>Debug\Win32\mongooselib.lib</ImportLibrary>
+      <ImportLibrary>Debug\Win32\civetweb.lib</ImportLibrary>
     </Link>
     <Midl>
       <HeaderFileName>
@@ -197,15 +197,15 @@
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
     <ClCompile>
       <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>../../../../src/mongoose;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
-      <PreprocessorDefinitions>DEBUG_TRACE=0;NO_SSL;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>../../../../src/civetweb;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <PreprocessorDefinitions>;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
       <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
       <PrecompiledHeader>
       </PrecompiledHeader>
-      <AssemblerListingLocation>Debug\x64\mongooselib\</AssemblerListingLocation>
-      <ObjectFileName>Debug\x64\mongooselib\</ObjectFileName>
-      <ProgramDataBaseFileName>Debug\x64\mongooselib.pdb</ProgramDataBaseFileName>
+      <AssemblerListingLocation>Debug\x64\civetweb\</AssemblerListingLocation>
+      <ObjectFileName>Debug\x64\civetweb\</ObjectFileName>
+      <ProgramDataBaseFileName>Debug\x64\civetweb.pdb</ProgramDataBaseFileName>
       <WarningLevel>Level3</WarningLevel>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <CompileAs>Default</CompileAs>
@@ -215,14 +215,14 @@
       <MultiProcessorCompilation>true</MultiProcessorCompilation>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>civetweblib.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Debug\x64\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <ModuleDefinitionFile></ModuleDefinitionFile>
       <GenerateDebugInformation>true</GenerateDebugInformation>
-      <ProgramDatabaseFile>Debug\x64\mongooselib.pdb</ProgramDatabaseFile>
+      <ProgramDatabaseFile>Debug\x64\civetweb.pdb</ProgramDatabaseFile>
       <SubSystem>Console</SubSystem>
-      <ImportLibrary>Debug\x64\mongooselib.lib</ImportLibrary>
+      <ImportLibrary>Debug\x64\civetweb.lib</ImportLibrary>
     </Link>
     <Midl>
       <HeaderFileName>
@@ -234,7 +234,7 @@
     </ResourceCompile>
   </ItemDefinitionGroup>
   <ItemGroup>
-    <ClCompile Include="..\..\..\..\src\mongoose\mongoose.c" />
+    <ClCompile Include="..\..\..\..\src\civetweb\main.c" />
   </ItemGroup>
 
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
diff --git a/build/win32/vs2010/Regal/mongooselib.vcxproj b/build/win32/vs2010/Regal/civetweblib.vcxproj
similarity index 84%
rename from build/win32/vs2010/Regal/mongooselib.vcxproj
rename to build/win32/vs2010/Regal/civetweblib.vcxproj
index 02f58cb..2a2d322 100644
--- a/build/win32/vs2010/Regal/mongooselib.vcxproj
+++ b/build/win32/vs2010/Regal/civetweblib.vcxproj
@@ -19,8 +19,8 @@
     </ProjectConfiguration>
   </ItemGroup>
   <PropertyGroup Label="Globals">
-    <ProjectName>mongooselib</ProjectName>
-    <ProjectGuid>{256E64B8-F766-061C-45F8-25B51B7CA24E}</ProjectGuid>
+    <ProjectName>civetweblib</ProjectName>
+    <ProjectGuid>{DF066256-E0AD-E016-6F07-52E868F96C02}</ProjectGuid>
   </PropertyGroup>
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
@@ -63,31 +63,31 @@
     <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
     <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Release\Win32\</OutDir>
     <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Release\x64\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Release\Win32\mongooselib\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Release\x64\mongooselib\</IntDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Release\Win32\civetweblib\</IntDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Release\x64\civetweblib\</IntDir>
     <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Debug\Win32\</OutDir>
     <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Debug\x64\</OutDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Debug\Win32\mongooselib\</IntDir>
-    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Debug\x64\mongooselib\</IntDir>
-    <TargetName Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">mongooselib</TargetName>
-    <TargetName Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">mongooselib</TargetName>
-    <TargetName Condition="'$(Configuration)|$(Platform)'=='Release|x64'">mongooselib</TargetName>
-    <TargetName Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">mongooselib</TargetName>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Debug\Win32\civetweblib\</IntDir>
+    <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Debug\x64\civetweblib\</IntDir>
+    <TargetName Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">civetweblib</TargetName>
+    <TargetName Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">civetweblib</TargetName>
+    <TargetName Condition="'$(Configuration)|$(Platform)'=='Release|x64'">civetweblib</TargetName>
+    <TargetName Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">civetweblib</TargetName>
   </PropertyGroup>
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
     <ClCompile>
       <Optimization>MaxSpeed</Optimization>
       <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
-      <AdditionalIncludeDirectories>../../../../src/mongoose;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/civetweb;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>DEBUG_TRACE=0;NO_SSL;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <StringPooling>true</StringPooling>
       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
       <FunctionLevelLinking>true</FunctionLevelLinking>
       <PrecompiledHeader>
       </PrecompiledHeader>
-      <AssemblerListingLocation>Release\Win32\mongooselib\</AssemblerListingLocation>
-      <ObjectFileName>Release\Win32\mongooselib\</ObjectFileName>
-      <ProgramDataBaseFileName>Release\Win32\mongooselib.pdb</ProgramDataBaseFileName>
+      <AssemblerListingLocation>Release\Win32\civetweblib\</AssemblerListingLocation>
+      <ObjectFileName>Release\Win32\civetweblib\</ObjectFileName>
+      <ProgramDataBaseFileName>Release\Win32\civetweblib.pdb</ProgramDataBaseFileName>
       <WarningLevel>Level3</WarningLevel>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <CompileAs>Default</CompileAs>
@@ -100,10 +100,10 @@
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Release\Win32\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <ModuleDefinitionFile></ModuleDefinitionFile>
-      <ProgramDatabaseFile>Release\Win32\mongooselib.pdb</ProgramDatabaseFile>
+      <ProgramDatabaseFile>Release\Win32\civetweblib.pdb</ProgramDatabaseFile>
       <SubSystem>Console</SubSystem>
       <TargetMachine>MachineX86</TargetMachine>
-      <ImportLibrary>Release\Win32\mongooselib.lib</ImportLibrary>
+      <ImportLibrary>Release\Win32\civetweblib.lib</ImportLibrary>
     </Link>
     <Midl>
       <HeaderFileName>
@@ -118,16 +118,16 @@
     <ClCompile>
       <Optimization>MaxSpeed</Optimization>
       <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
-      <AdditionalIncludeDirectories>../../../../src/mongoose;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/civetweb;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>DEBUG_TRACE=0;NO_SSL;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <StringPooling>true</StringPooling>
       <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
       <FunctionLevelLinking>true</FunctionLevelLinking>
       <PrecompiledHeader>
       </PrecompiledHeader>
-      <AssemblerListingLocation>Release\x64\mongooselib\</AssemblerListingLocation>
-      <ObjectFileName>Release\x64\mongooselib\</ObjectFileName>
-      <ProgramDataBaseFileName>Release\x64\mongooselib.pdb</ProgramDataBaseFileName>
+      <AssemblerListingLocation>Release\x64\civetweblib\</AssemblerListingLocation>
+      <ObjectFileName>Release\x64\civetweblib\</ObjectFileName>
+      <ProgramDataBaseFileName>Release\x64\civetweblib.pdb</ProgramDataBaseFileName>
       <WarningLevel>Level3</WarningLevel>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <CompileAs>Default</CompileAs>
@@ -141,9 +141,9 @@
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Release\x64\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <ModuleDefinitionFile></ModuleDefinitionFile>
-      <ProgramDatabaseFile>Release\x64\mongooselib.pdb</ProgramDatabaseFile>
+      <ProgramDatabaseFile>Release\x64\civetweblib.pdb</ProgramDatabaseFile>
       <SubSystem>Console</SubSystem>
-      <ImportLibrary>Release\x64\mongooselib.lib</ImportLibrary>
+      <ImportLibrary>Release\x64\civetweblib.lib</ImportLibrary>
     </Link>
     <Midl>
       <HeaderFileName>
@@ -157,15 +157,15 @@
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
     <ClCompile>
       <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>../../../../src/mongoose;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/civetweb;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>DEBUG_TRACE=0;NO_SSL;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
       <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
       <PrecompiledHeader>
       </PrecompiledHeader>
-      <AssemblerListingLocation>Debug\Win32\mongooselib\</AssemblerListingLocation>
-      <ObjectFileName>Debug\Win32\mongooselib\</ObjectFileName>
-      <ProgramDataBaseFileName>Debug\Win32\mongooselib.pdb</ProgramDataBaseFileName>
+      <AssemblerListingLocation>Debug\Win32\civetweblib\</AssemblerListingLocation>
+      <ObjectFileName>Debug\Win32\civetweblib\</ObjectFileName>
+      <ProgramDataBaseFileName>Debug\Win32\civetweblib.pdb</ProgramDataBaseFileName>
       <WarningLevel>Level3</WarningLevel>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
@@ -180,10 +180,10 @@
       <AdditionalLibraryDirectories>Debug\Win32\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <ModuleDefinitionFile></ModuleDefinitionFile>
       <GenerateDebugInformation>true</GenerateDebugInformation>
-      <ProgramDatabaseFile>Debug\Win32\mongooselib.pdb</ProgramDatabaseFile>
+      <ProgramDatabaseFile>Debug\Win32\civetweblib.pdb</ProgramDatabaseFile>
       <SubSystem>Console</SubSystem>
       <TargetMachine>MachineX86</TargetMachine>
-      <ImportLibrary>Debug\Win32\mongooselib.lib</ImportLibrary>
+      <ImportLibrary>Debug\Win32\civetweblib.lib</ImportLibrary>
     </Link>
     <Midl>
       <HeaderFileName>
@@ -197,15 +197,15 @@
   <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
     <ClCompile>
       <Optimization>Disabled</Optimization>
-      <AdditionalIncludeDirectories>../../../../src/mongoose;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>../../../../src/civetweb;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>DEBUG_TRACE=0;NO_SSL;_CRT_SECURE_NO_WARNINGS=1;WIN32;_WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
       <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
       <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
       <PrecompiledHeader>
       </PrecompiledHeader>
-      <AssemblerListingLocation>Debug\x64\mongooselib\</AssemblerListingLocation>
-      <ObjectFileName>Debug\x64\mongooselib\</ObjectFileName>
-      <ProgramDataBaseFileName>Debug\x64\mongooselib.pdb</ProgramDataBaseFileName>
+      <AssemblerListingLocation>Debug\x64\civetweblib\</AssemblerListingLocation>
+      <ObjectFileName>Debug\x64\civetweblib\</ObjectFileName>
+      <ProgramDataBaseFileName>Debug\x64\civetweblib.pdb</ProgramDataBaseFileName>
       <WarningLevel>Level3</WarningLevel>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <CompileAs>Default</CompileAs>
@@ -220,9 +220,9 @@
       <AdditionalLibraryDirectories>Debug\x64\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <ModuleDefinitionFile></ModuleDefinitionFile>
       <GenerateDebugInformation>true</GenerateDebugInformation>
-      <ProgramDatabaseFile>Debug\x64\mongooselib.pdb</ProgramDatabaseFile>
+      <ProgramDatabaseFile>Debug\x64\civetweblib.pdb</ProgramDatabaseFile>
       <SubSystem>Console</SubSystem>
-      <ImportLibrary>Debug\x64\mongooselib.lib</ImportLibrary>
+      <ImportLibrary>Debug\x64\civetweblib.lib</ImportLibrary>
     </Link>
     <Midl>
       <HeaderFileName>
@@ -234,7 +234,7 @@
     </ResourceCompile>
   </ItemDefinitionGroup>
   <ItemGroup>
-    <ClCompile Include="..\..\..\..\src\mongoose\mongoose.c" />
+    <ClCompile Include="..\..\..\..\src\civetweb\civetweb.c" />
   </ItemGroup>
 
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
diff --git a/build/win32/vs2010/Regal/dreamtorus_static.vcxproj b/build/win32/vs2010/Regal/dreamtorus_static.vcxproj
index a1436cb..53fa228 100644
--- a/build/win32/vs2010/Regal/dreamtorus_static.vcxproj
+++ b/build/win32/vs2010/Regal/dreamtorus_static.vcxproj
@@ -96,7 +96,7 @@
       <MultiProcessorCompilation>true</MultiProcessorCompilation>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>rglutlib.lib;rglulib.lib;regallib.lib;winmm.lib;ws2_32.lib;mongooselib.lib;md5lib.lib;jsonsllib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>rglutlib.lib;rglulib.lib;regallib.lib;winmm.lib;ws2_32.lib;civetweblib.lib;md5lib.lib;jsonsllib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Release\Win32\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <ModuleDefinitionFile></ModuleDefinitionFile>
@@ -137,7 +137,7 @@
       <MultiProcessorCompilation>true</MultiProcessorCompilation>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>rglutlib.lib;rglulib.lib;regallib.lib;winmm.lib;ws2_32.lib;mongooselib.lib;md5lib.lib;jsonsllib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>rglutlib.lib;rglulib.lib;regallib.lib;winmm.lib;ws2_32.lib;civetweblib.lib;md5lib.lib;jsonsllib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Release\x64\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <ModuleDefinitionFile></ModuleDefinitionFile>
@@ -175,7 +175,7 @@
       <MultiProcessorCompilation>true</MultiProcessorCompilation>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>rglutlib.lib;rglulib.lib;regallib.lib;winmm.lib;ws2_32.lib;mongooselib.lib;md5lib.lib;jsonsllib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>rglutlib.lib;rglulib.lib;regallib.lib;winmm.lib;ws2_32.lib;civetweblib.lib;md5lib.lib;jsonsllib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Debug\Win32\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <ModuleDefinitionFile></ModuleDefinitionFile>
@@ -215,7 +215,7 @@
       <MultiProcessorCompilation>true</MultiProcessorCompilation>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>rglutlib.lib;rglulib.lib;regallib.lib;winmm.lib;ws2_32.lib;mongooselib.lib;md5lib.lib;jsonsllib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>rglutlib.lib;rglulib.lib;regallib.lib;winmm.lib;ws2_32.lib;civetweblib.lib;md5lib.lib;jsonsllib.lib;apitracelib.lib;snappylib.lib;pnglib.lib;zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <AdditionalLibraryDirectories>Debug\x64\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
       <ModuleDefinitionFile></ModuleDefinitionFile>
diff --git a/examples/dreamtorus/osx/minimal_osx.xcodeproj/project.pbxproj b/examples/dreamtorus/osx/minimal_osx.xcodeproj/project.pbxproj
index bad8bfb..7f28643 100644
--- a/examples/dreamtorus/osx/minimal_osx.xcodeproj/project.pbxproj
+++ b/examples/dreamtorus/osx/minimal_osx.xcodeproj/project.pbxproj
@@ -20,7 +20,7 @@
 		BC3A59B31804680000992687 /* libapitrace.a in Frameworks */ = {isa = PBXBuildFile; fileRef = BC9F8ABB1804648500C68C71 /* libapitrace.a */; };
 		BC3A59BA1804680400992687 /* libjsonsl.a in Frameworks */ = {isa = PBXBuildFile; fileRef = BC9F8AC2180464A200C68C71 /* libjsonsl.a */; };
 		BC3A59BB1804680800992687 /* libmd5.a in Frameworks */ = {isa = PBXBuildFile; fileRef = BC9F8AC8180464B200C68C71 /* libmd5.a */; };
-		BC3A59BC1804680B00992687 /* libmongoose.a in Frameworks */ = {isa = PBXBuildFile; fileRef = BC9F8ACE180464C500C68C71 /* libmongoose.a */; };
+		BC3A59BC1804680B00992687 /* libcivetweb.a in Frameworks */ = {isa = PBXBuildFile; fileRef = BC9F8ACE180464C500C68C71 /* libcivetweb.a */; };
 		BC3A59BD1804680E00992687 /* libsnappy.a in Frameworks */ = {isa = PBXBuildFile; fileRef = BC9F8AD4180464D700C68C71 /* libsnappy.a */; };
 		BC3A59BE1804681100992687 /* libsquish.a in Frameworks */ = {isa = PBXBuildFile; fileRef = BC9F8ADA180464F400C68C71 /* libsquish.a */; };
 /* End PBXBuildFile section */
@@ -56,10 +56,10 @@
 		};
 		BC9F8ACD180464C500C68C71 /* PBXContainerItemProxy */ = {
 			isa = PBXContainerItemProxy;
-			containerPortal = BC9F8AC9180464C500C68C71 /* mongoose.xcodeproj */;
+			containerPortal = BC9F8AC9180464C500C68C71 /* civetweb.xcodeproj */;
 			proxyType = 2;
 			remoteGlobalIDString = 4336676E17C56DC700D45AD9;
-			remoteInfo = mongoose;
+			remoteInfo = civetweb;
 		};
 		BC9F8AD3180464D700C68C71 /* PBXContainerItemProxy */ = {
 			isa = PBXContainerItemProxy;
@@ -101,7 +101,7 @@
 		BC9F8AB61804648400C68C71 /* apitrace.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = apitrace.xcodeproj; path = ../../../build/mac/apitrace/apitrace.xcodeproj; sourceTree = "<group>"; };
 		BC9F8ABD180464A200C68C71 /* jsonsl.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = jsonsl.xcodeproj; path = ../../../build/mac/jsonsl/jsonsl.xcodeproj; sourceTree = "<group>"; };
 		BC9F8AC3180464B100C68C71 /* md5.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = md5.xcodeproj; path = ../../../build/mac/md5/md5.xcodeproj; sourceTree = "<group>"; };
-		BC9F8AC9180464C500C68C71 /* mongoose.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = mongoose.xcodeproj; path = ../../../build/mac/mongoose/mongoose.xcodeproj; sourceTree = "<group>"; };
+		BC9F8AC9180464C500C68C71 /* civetweb.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = civetweb.xcodeproj; path = ../../../build/mac/civetweb/civetweb.xcodeproj; sourceTree = "<group>"; };
 		BC9F8ACF180464D700C68C71 /* snappy.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = snappy.xcodeproj; path = ../../../build/mac/snappy/snappy.xcodeproj; sourceTree = "<group>"; };
 		BC9F8AD5180464F400C68C71 /* squish.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = squish.xcodeproj; path = ../../../build/mac/squish/squish.xcodeproj; sourceTree = "<group>"; };
 /* End PBXFileReference section */
@@ -113,7 +113,7 @@
 			files = (
 				BC3A59BE1804681100992687 /* libsquish.a in Frameworks */,
 				BC3A59BD1804680E00992687 /* libsnappy.a in Frameworks */,
-				BC3A59BC1804680B00992687 /* libmongoose.a in Frameworks */,
+				BC3A59BC1804680B00992687 /* libcivetweb.a in Frameworks */,
 				BC3A59BB1804680800992687 /* libmd5.a in Frameworks */,
 				BC3A59BA1804680400992687 /* libjsonsl.a in Frameworks */,
 				BC3A59B31804680000992687 /* libapitrace.a in Frameworks */,
@@ -157,7 +157,7 @@
 				431D3BFF15C9B635009DD04F /* Regal.xcodeproj */,
 				BC9F8AD5180464F400C68C71 /* squish.xcodeproj */,
 				BC9F8ACF180464D700C68C71 /* snappy.xcodeproj */,
-				BC9F8AC9180464C500C68C71 /* mongoose.xcodeproj */,
+				BC9F8AC9180464C500C68C71 /* civetweb.xcodeproj */,
 				BC9F8AC3180464B100C68C71 /* md5.xcodeproj */,
 				BC9F8ABD180464A200C68C71 /* jsonsl.xcodeproj */,
 				BC9F8AB61804648400C68C71 /* apitrace.xcodeproj */,
@@ -241,7 +241,7 @@
 		BC9F8ACA180464C500C68C71 /* Products */ = {
 			isa = PBXGroup;
 			children = (
-				BC9F8ACE180464C500C68C71 /* libmongoose.a */,
+				BC9F8ACE180464C500C68C71 /* libcivetweb.a */,
 			);
 			name = Products;
 			sourceTree = "<group>";
@@ -318,7 +318,7 @@
 				},
 				{
 					ProductGroup = BC9F8ACA180464C500C68C71 /* Products */;
-					ProjectRef = BC9F8AC9180464C500C68C71 /* mongoose.xcodeproj */;
+					ProjectRef = BC9F8AC9180464C500C68C71 /* civetweb.xcodeproj */;
 				},
 				{
 					ProductGroup = 431D3C0015C9B635009DD04F /* Products */;
@@ -369,10 +369,10 @@
 			remoteRef = BC9F8AC7180464B200C68C71 /* PBXContainerItemProxy */;
 			sourceTree = BUILT_PRODUCTS_DIR;
 		};
-		BC9F8ACE180464C500C68C71 /* libmongoose.a */ = {
+		BC9F8ACE180464C500C68C71 /* libcivetweb.a */ = {
 			isa = PBXReferenceProxy;
 			fileType = archive.ar;
-			path = libmongoose.a;
+			path = libcivetweb.a;
 			remoteRef = BC9F8ACD180464C500C68C71 /* PBXContainerItemProxy */;
 			sourceTree = BUILT_PRODUCTS_DIR;
 		};
diff --git a/examples/nehe/lesson04/main.c b/examples/nehe/lesson04/main.c
new file mode 100644
index 0000000..8771ed8
--- /dev/null
+++ b/examples/nehe/lesson04/main.c
@@ -0,0 +1,212 @@
+/* NeHe Lesson 04 */
+
+/* ES 1.0 version adapted from Insanity Design                */
+/* http://insanitydesign.com/wp/projects/nehe-android-ports/  */
+
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <GL/RegalGLEW.h>
+#include <GL/Regal.h>
+
+#ifdef __APPLE__
+#include <GLUT/glut.h>
+#else
+#include <GL/RegalGLUT.h>
+#endif
+
+static void init()
+{
+  glShadeModel(GL_SMOOTH); 			          // Enable Smooth Shading
+  glClearColor(0.0f, 0.0f, 0.0f, 0.5f); 	// Black Background
+  glClearDepth(1.0f); 					          // Depth Buffer Setup
+  glEnable(GL_DEPTH_TEST); 			          // Enables Depth Testing
+  glDepthFunc(GL_LEQUAL); 			          // The Type Of Depth Testing To Do
+  glDisable(GL_CULL_FACE);
+  
+  // Really Nice Perspective Calculations
+  glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); 
+}
+
+static void reshape(int width, int height)
+{
+  if (height<1) { 						// Prevent A Divide By Zero By
+    height = 1; 						  // Making Height Equal One
+  }
+  
+  glViewport(0, 0, width, height); 	// Reset The Current Viewport
+  glMatrixMode(GL_PROJECTION); 	    // Select The Projection Matrix
+  glLoadIdentity(); 					      // Reset The Projection Matrix
+  
+  //Calculate The Aspect Ratio Of The Window
+  gluPerspective(45.0f, (float)width / (float)height, 0.1f, 100.0f);
+  
+  glMatrixMode(GL_MODELVIEW); 	    // Select The Modelview Matrix
+  glLoadIdentity(); 					      // Reset The Modelview Matrix
+}
+
+static void drawSquare()
+{		
+	/** The initial vertex definition */
+	const float vertices[] = { 
+						-1.0f, -1.0f, 0.0f, 	// Bottom Left
+						 1.0f, -1.0f, 0.0f, 	// Bottom Right
+						-1.0f,  1.0f, 0.0f,   // Top Left
+						 1.0f,  1.0f, 0.0f 		// Top Right
+										};
+
+	const float colors[] = {
+    					0.0f, 0.0f, 1.0f, 1.0f, // Blue
+    					0.0f, 0.0f, 1.0f, 1.0f, // Blue
+    					0.0f, 0.0f, 1.0f, 1.0f 	// Blue
+			    							};
+
+		// Set the face rotation
+		glFrontFace(GL_CCW);
+		
+		// Point to our vertex buffer
+		glVertexPointer(3, GL_FLOAT, 0, vertices);
+//  glColorPointer(4, GL_FLOAT, 0, colors);
+
+#if 1
+		// Set The Color To Blue
+		glColor4f(0.5f, 0.5f, 1.0f, 1.0f);	
+#endif
+
+		// Enable vertex buffer
+		glEnableClientState(GL_VERTEX_ARRAY);
+//  glEnableClientState(GL_COLOR_ARRAY);
+		
+		// Draw the vertices as triangle strip
+		glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
+		
+		// Disable the client state before leaving
+		glDisableClientState(GL_VERTEX_ARRAY);	
+//  glDisableClientState(GL_COLOR_ARRAY);		
+}
+
+static void drawTriangle()
+{
+	/** The initial vertex definition */
+	const float vertices[] = { 
+						0.0f, 1.0f, 0.0f, 	//Top
+						-1.0f, -1.0f, 0.0f, //Bottom Left
+						1.0f, -1.0f, 0.0f 	//Bottom Right
+										};
+	/** The initial color definition */
+	const float colors[] = {
+    					1.0f, 0.0f, 0.0f, 1.0f, // Set The Color To Red with full luminance
+    					0.0f, 1.0f, 0.0f, 1.0f, // Set The Color To Green with full luminance
+    					0.0f, 0.0f, 1.0f, 1.0f 	// Set The Color To Blue with full luminance
+			    							};
+			    							
+  //Set the face rotation
+  glFrontFace(GL_CW);
+	
+  glClear(GL_DEPTH_BUFFER_BIT|GL_COLOR_BUFFER_BIT);
+
+  //Point to our buffers
+  glVertexPointer(3, GL_FLOAT, 0, vertices);
+  glColorPointer(4, GL_FLOAT, 0, colors);
+  
+  //Enable the vertex and color state
+  glEnableClientState(GL_VERTEX_ARRAY);
+  glEnableClientState(GL_COLOR_ARRAY);
+  
+  //Draw the vertices as triangles
+  glDrawArrays(GL_TRIANGLES, 0, 3);
+		
+  //Disable the client state before leaving
+  glDisableClientState(GL_VERTEX_ARRAY);
+  glDisableClientState(GL_COLOR_ARRAY);		
+}
+
+float rquad = 0.0f;
+float rtri = 0.0f;
+
+static void display(void)
+{
+  // Clear Screen And Depth Buffer
+  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);	
+  
+  // Reset The Current Modelview Matrix
+  
+  glLoadIdentity();					
+  
+  // Drawing
+
+  glTranslatef(0.0f, -1.2f, -6.0f);	  // Move down 1.0 Unit And Into The Screen 6.0
+  glRotatef(rquad, 1.0f, 0.0f, 0.0f);	// Rotate The Square On The X axis ( NEW )
+  drawSquare();	  					          // Draw the square
+  
+  // Reset The Current Modelview Matrix
+
+  glLoadIdentity(); 					
+  
+  glTranslatef(0.0f, 1.3f, -6.0f);		// Move up 1.3 Units and -6.0 into the Screen
+  glRotatef(rtri, 0.0f, 1.0f, 0.0f);	// Rotate The Triangle On The Y axis ( NEW )
+  drawTriangle();	     					      // Draw the triangle		
+  
+  // Rotation
+  rtri += 0.2f; 							// Increase The Rotation Variable For The Triangle ( NEW )
+  rquad -= 0.15f; 						// Decrease The Rotation Variable For The Quad ( NEW )
+  
+  glutSwapBuffers();
+}
+
+static void idle(void)
+{
+  glutPostRedisplay();
+}
+
+int main(int argc, char *argv[])
+{
+  int status;
+
+  glutInitWindowSize(512,512);
+  glutInit(&argc, argv);
+  
+  glutCreateWindow("NeHe Lesson04 for ES 1.0");
+
+  // Regal workaround for OSX GLUT
+
+  #ifdef __APPLE__
+  extern void *CGLGetCurrentContext(void);
+  RegalMakeCurrent(CGLGetCurrentContext());
+  #endif
+
+  status = glewInit();
+  if (status != GLEW_OK)
+  {
+    printf("OpenGL Extension Wrangler (GLEW) failed to initialize");
+    return EXIT_FAILURE;
+  }
+
+  printf("vendor: %s\n", glGetString(GL_VENDOR));
+  printf("version: %s\n", glGetString(GL_VERSION));
+  printf("renderer: %s\n", glGetString(GL_RENDERER));
+
+  if (!glewIsSupported("GL_REGAL_ES1_0_compatibility"))
+  {
+    printf("GL_REGAL_ES1_0_compatibility is not supported.\n");
+    return EXIT_FAILURE;
+  }
+
+  if (!glewIsSupported("GL_REGAL_ES1_1_compatibility"))
+  {
+    printf("GL_REGAL_ES1_1_compatibility is not supported.\n");
+    return EXIT_FAILURE;
+  }
+
+  glutDisplayFunc(display);
+  glutReshapeFunc(reshape);
+  glutIdleFunc(idle);
+
+  init();
+
+  glutMainLoop();
+
+  return EXIT_SUCCESS;
+}
diff --git a/examples/redbook/checker.cpp b/examples/redbook/checker.cpp
new file mode 100644
index 0000000..bc2288c
--- /dev/null
+++ b/examples/redbook/checker.cpp
@@ -0,0 +1,191 @@
+/*
+ * Copyright (c) 1993-1997, Silicon Graphics, Inc.
+ * ALL RIGHTS RESERVED
+ * Permission to use, copy, modify, and distribute this software for
+ * any purpose and without fee is hereby granted, provided that the above
+ * copyright notice appear in all copies and that both the copyright notice
+ * and this permission notice appear in supporting documentation, and that
+ * the name of Silicon Graphics, Inc. not be used in advertising
+ * or publicity pertaining to distribution of the software without specific,
+ * written prior permission.
+ *
+ * THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS"
+ * AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE,
+ * INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR
+ * FITNESS FOR A PARTICULAR PURPOSE.  IN NO EVENT SHALL SILICON
+ * GRAPHICS, INC.  BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT,
+ * SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY
+ * KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION,
+ * LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF
+ * THIRD PARTIES, WHETHER OR NOT SILICON GRAPHICS, INC.  HAS BEEN
+ * ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE
+ * POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE.
+ *
+ * US Government Users Restricted Rights
+ * Use, duplication, or disclosure by the Government is subject to
+ * restrictions set forth in FAR 52.227.19(c)(2) or subparagraph
+ * (c)(1)(ii) of the Rights in Technical Data and Computer Software
+ * clause at DFARS 252.227-7013 and/or in similar or successor
+ * clauses in the FAR or the DOD or NASA FAR Supplement.
+ * Unpublished-- rights reserved under the copyright laws of the
+ * United States.  Contractor/manufacturer is Silicon Graphics,
+ * Inc., 2011 N.  Shoreline Blvd., Mountain View, CA 94039-7311.
+ *
+ * OpenGL(R) is a registered trademark of Silicon Graphics, Inc.
+ */
+
+/*  checker.c
+ *  This program texture maps a checkerboard image onto
+ *  two rectangles.
+ *
+ *  If running this program on OpenGL 1.0, texture objects are
+ *  not used.
+ */
+
+#include <GL/Regal.h>
+#include <GL/RegalGLU.h>
+
+#include <stdlib.h>
+#include <stdio.h>
+
+/******************************************************************/
+
+/*
+#define USE_VERSION_1_1 0
+*/
+
+#ifndef USE_VERSION_1_1
+#define USE_VERSION_1_1 1
+#endif
+
+/* 0 through 7 work on Mac OSX with and without Regal emulation */
+/* 0 through 3 work on Nvidia Win7 without Regal emulation      */
+/* 0 through 7 work on Nvidia Win7 with Regal emulation         */
+
+#define USE_UNIT (GL_TEXTURE0+7)
+
+/******************************************************************/
+
+#if USE_VERSION_1_1
+static GLuint texName;
+#endif
+
+/*	Create checkerboard texture	*/
+#define	checkImageWidth 64
+#define	checkImageHeight 64
+static GLubyte checkImage[checkImageHeight][checkImageWidth][4];
+
+void makeCheckImage(void)
+{
+   int i, j, c;
+
+   for (i = 0; i < checkImageHeight; i++) {
+      for (j = 0; j < checkImageWidth; j++) {
+         c = ((((i&0x8)==0)^((j&0x8))==0))*255;
+         checkImage[i][j][0] = (GLubyte) c;
+         checkImage[i][j][1] = (GLubyte) c;
+         checkImage[i][j][2] = (GLubyte) c;
+         checkImage[i][j][3] = (GLubyte) 255;
+      }
+   }
+}
+
+void dreamTorusInit(void)
+{
+   /* Report the number of available texture units */
+
+   GLint textureUnits,vertexUnits,fragmentUnits,combinedUnits;
+   GLint vertexAttribs;
+
+   glGetIntegerv(GL_MAX_TEXTURE_UNITS,               &textureUnits);  
+   glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS,         &fragmentUnits);
+   glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS,  &vertexUnits);
+   glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS,&combinedUnits);
+
+   printf("%d texture units, %d fragment, %d vertex and %d combined texture units.\n",textureUnits,fragmentUnits,vertexUnits,combinedUnits);
+
+   glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &vertexAttribs);
+
+   printf("%u vertex attributes.\n",vertexAttribs);
+
+   /* Initialize OpenGL */
+
+   glClearColor (0.0, 1.0, 0.0, 0.0);
+   glShadeModel(GL_FLAT);
+   glEnable(GL_DEPTH_TEST);
+
+#ifdef USE_UNIT
+   glActiveTexture(USE_UNIT);
+#endif
+
+   makeCheckImage();
+   glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
+
+#if USE_VERSION_1_1
+   glGenTextures(1, &texName);
+   glBindTexture(GL_TEXTURE_2D, texName);
+#endif
+
+   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
+   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
+   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+#if USE_VERSION_1_1
+   glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, checkImageWidth, checkImageHeight,
+                0, GL_RGBA, GL_UNSIGNED_BYTE, checkImage);
+#else
+   glTexImage2D(GL_TEXTURE_2D, 0, 4, checkImageWidth, checkImageHeight,
+                0, GL_RGBA, GL_UNSIGNED_BYTE, checkImage);
+#endif
+}
+
+void dreamTorusDisplay(bool clear)
+{
+   if (clear)
+     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+
+   glEnable(GL_TEXTURE_2D);
+   glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
+#if USE_VERSION_1_1
+   glBindTexture(GL_TEXTURE_2D, texName);
+#endif
+
+   glBegin(GL_QUADS);
+
+#ifdef USE_UNIT
+   glMultiTexCoord2f(USE_UNIT, 0.0, 0.0); glVertex3f(-2.0, -1.0, 0.0);
+   glMultiTexCoord2f(USE_UNIT, 0.0, 1.0); glVertex3f(-2.0, 1.0, 0.0);
+   glMultiTexCoord2f(USE_UNIT, 1.0, 1.0); glVertex3f(0.0, 1.0, 0.0);
+   glMultiTexCoord2f(USE_UNIT, 1.0, 0.0); glVertex3f(0.0, -1.0, 0.0);
+
+   glMultiTexCoord2f(USE_UNIT, 0.0, 0.0); glVertex3f(1.0, -1.0, 0.0);
+   glMultiTexCoord2f(USE_UNIT, 0.0, 1.0); glVertex3f(1.0, 1.0, 0.0);
+   glMultiTexCoord2f(USE_UNIT, 1.0, 1.0); glVertex3f(2.41421, 1.0, -1.41421);
+   glMultiTexCoord2f(USE_UNIT, 1.0, 0.0); glVertex3f(2.41421, -1.0, -1.41421);
+#else
+   glTexCoord2f(0.0, 0.0); glVertex3f(-2.0, -1.0, 0.0);
+   glTexCoord2f(0.0, 1.0); glVertex3f(-2.0, 1.0, 0.0);
+   glTexCoord2f(1.0, 1.0); glVertex3f(0.0, 1.0, 0.0);
+   glTexCoord2f(1.0, 0.0); glVertex3f(0.0, -1.0, 0.0);
+
+   glTexCoord2f(0.0, 0.0); glVertex3f(1.0, -1.0, 0.0);
+   glTexCoord2f(0.0, 1.0); glVertex3f(1.0, 1.0, 0.0);
+   glTexCoord2f(1.0, 1.0); glVertex3f(2.41421, 1.0, -1.41421);
+   glTexCoord2f(1.0, 0.0); glVertex3f(2.41421, -1.0, -1.41421);
+#endif
+   glEnd();
+   glFlush();
+   glDisable(GL_TEXTURE_2D);
+}
+
+void dreamTorusReshape(int w, int h)
+{
+   glViewport(0, 0, (GLsizei) w, (GLsizei) h);
+   glMatrixMode(GL_PROJECTION);
+   glLoadIdentity();
+   gluPerspective(60.0, (GLfloat) w/(GLfloat) h, 1.0, 30.0);
+   glMatrixMode(GL_MODELVIEW);
+   glLoadIdentity();
+   glTranslatef(0.0, 0.0, -3.6);
+}
diff --git a/include/GL/Regal.h b/include/GL/Regal.h
index 4208751..caa2b65 100644
--- a/include/GL/Regal.h
+++ b/include/GL/Regal.h
@@ -3731,7 +3731,7 @@
 typedef void (REGAL_CALL *PFNGLCLEARBUFFERDATAPROC)(GLenum target, GLenum internalformat, GLenum format, GLenum type, const GLvoid *data);
 typedef void (REGAL_CALL *PFNGLCLEARBUFFERSUBDATAPROC)(GLenum target, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const GLvoid *data);
 typedef void (REGAL_CALL *PFNGLCLEARNAMEDBUFFERDATAEXTPROC)(GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const GLvoid *data);
-typedef void (REGAL_CALL *PFNGLCLEARNAMEDBUFFERSUBDATAEXTPROC)(GLuint buffer, GLenum internalformat, GLenum format, GLenum type, GLintptr offset, GLsizeiptr size, const GLvoid *data);
+typedef void (REGAL_CALL *PFNGLCLEARNAMEDBUFFERSUBDATAEXTPROC)(GLuint buffer, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const GLvoid *data);
 #endif
 
 #ifndef REGAL_NO_NAMESPACE_GL_ARB_CLEAR_BUFFER_OBJECT
@@ -3745,14 +3745,14 @@
 REGAL_DECL void REGAL_CALL glClearBufferData(GLenum target, GLenum internalformat, GLenum format, GLenum type, const GLvoid *data);
 REGAL_DECL void REGAL_CALL glClearBufferSubData(GLenum target, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const GLvoid *data);
 REGAL_DECL void REGAL_CALL glClearNamedBufferDataEXT(GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const GLvoid *data);
-REGAL_DECL void REGAL_CALL glClearNamedBufferSubDataEXT(GLuint buffer, GLenum internalformat, GLenum format, GLenum type, GLintptr offset, GLsizeiptr size, const GLvoid *data);
+REGAL_DECL void REGAL_CALL glClearNamedBufferSubDataEXT(GLuint buffer, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const GLvoid *data);
 #endif
 
 #ifndef REGAL_NO_PLUGIN_GL_ARB_CLEAR_BUFFER_OBJECT
 REGAL_DECL void REGAL_CALL plugin_glClearBufferData(GLenum target, GLenum internalformat, GLenum format, GLenum type, const GLvoid *data);
 REGAL_DECL void REGAL_CALL plugin_glClearBufferSubData(GLenum target, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const GLvoid *data);
 REGAL_DECL void REGAL_CALL plugin_glClearNamedBufferDataEXT(GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const GLvoid *data);
-REGAL_DECL void REGAL_CALL plugin_glClearNamedBufferSubDataEXT(GLuint buffer, GLenum internalformat, GLenum format, GLenum type, GLintptr offset, GLsizeiptr size, const GLvoid *data);
+REGAL_DECL void REGAL_CALL plugin_glClearNamedBufferSubDataEXT(GLuint buffer, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const GLvoid *data);
 #endif
 
 /**
diff --git a/scripts/api/gl.py b/scripts/api/gl.py
index b1adfb1..88d852c 100644
--- a/scripts/api/gl.py
+++ b/scripts/api/gl.py
@@ -20405,10 +20405,10 @@
 glClearNamedBufferSubDataEXT.ret = Return('void')
 glClearNamedBufferSubDataEXT.add( Input( 'buffer','GLuint' ))
 glClearNamedBufferSubDataEXT.add( Input( 'internalformat','GLenum' ))
-glClearNamedBufferSubDataEXT.add( Input( 'format','GLenum' ))
-glClearNamedBufferSubDataEXT.add( Input( 'type','GLenum' ))
 glClearNamedBufferSubDataEXT.add( Input( 'offset','GLintptr' ))
 glClearNamedBufferSubDataEXT.add( Input( 'size','GLsizeiptr' ))
+glClearNamedBufferSubDataEXT.add( Input( 'format','GLenum' ))
+glClearNamedBufferSubDataEXT.add( Input( 'type','GLenum' ))
 glClearNamedBufferSubDataEXT.add( Input( 'data','const GLvoid *' ))
 glClearNamedBufferSubDataEXT.version = ''
 glClearNamedBufferSubDataEXT.category = 'GL_ARB_clear_buffer_object'
diff --git a/scripts/regal/RegalDispatchTraceExclude.py b/scripts/regal/RegalDispatchTraceExclude.py
index 63516da..585e58f 100644
--- a/scripts/regal/RegalDispatchTraceExclude.py
+++ b/scripts/regal/RegalDispatchTraceExclude.py
@@ -67,7 +67,6 @@
   'GL_NV_blend_equation_advanced',
   'GL_NV_blend_equation_advanced_coherent',
   'GL_NV_copy_buffer',
-  'GL_NV_framebuffer_blit',
   'GL_NV_non_square_matrices',
   'GL_NV_vdpau_interop',
 
diff --git a/src/apitrace/common/trace_callset.cpp b/src/apitrace/common/trace_callset.cpp
index 0239028..dca39d0 100644
--- a/src/apitrace/common/trace_callset.cpp
+++ b/src/apitrace/common/trace_callset.cpp
@@ -223,8 +223,16 @@
 };
 
 
-CallSet::CallSet(const char *string): limits(std::numeric_limits<CallNo>::min(), std::numeric_limits<CallNo>::max())
+void
+CallSet::merge(const char *string)
 {
+    if (firstmerge) {
+        if (!empty()) {
+            *this = CallSet();
+        }
+        firstmerge = false;
+    }
+
     if (*string == '@') {
         FileCallSetParser parser(*this, &string[1]);
         parser.parse();
@@ -235,7 +243,7 @@
 }
 
 
-CallSet::CallSet(CallFlags freq): limits(std::numeric_limits<CallNo>::min(), std::numeric_limits<CallNo>::max()) {
+CallSet::CallSet(CallFlags freq): limits(std::numeric_limits<CallNo>::min(), std::numeric_limits<CallNo>::max()), firstmerge(true) {
     if (freq != FREQUENCY_NONE) {
         CallNo start = std::numeric_limits<CallNo>::min();
         CallNo stop = std::numeric_limits<CallNo>::max();
@@ -244,3 +252,4 @@
         assert(!empty());
     }
 }
+
diff --git a/src/apitrace/common/trace_callset.hpp b/src/apitrace/common/trace_callset.hpp
index 35729c4..53bad98 100644
--- a/src/apitrace/common/trace_callset.hpp
+++ b/src/apitrace/common/trace_callset.hpp
@@ -104,6 +104,7 @@
     {
     private:
         CallRange limits;
+        bool firstmerge;
 
     public:
         FastCallSet fast_call_set;
@@ -114,11 +115,12 @@
         typedef std::list< CallRange > RangeList;
         RangeList ranges;
 
-        CallSet(): limits(std::numeric_limits<CallNo>::min(), std::numeric_limits<CallNo>::max()) {}
+        CallSet(): limits(std::numeric_limits<CallNo>::min(), std::numeric_limits<CallNo>::max()), firstmerge(true) {}
 
         CallSet(CallFlags freq);
 
-        CallSet(const char *str);
+        void
+        merge(const char *str);
 
         // Not empty set
         inline bool
diff --git a/src/apitrace/common/trace_fast_callset.cpp b/src/apitrace/common/trace_fast_callset.cpp
index 5aebfd2..2ac5343 100644
--- a/src/apitrace/common/trace_fast_callset.cpp
+++ b/src/apitrace/common/trace_fast_callset.cpp
@@ -30,6 +30,7 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <limits>
+#include <vector>
 
 #include "os.hpp"
 #include "trace_fast_callset.hpp"
@@ -39,12 +40,13 @@
 #define MAX_LEVEL 16
 
 FastCallRange::FastCallRange(CallNo first, CallNo last, int level)
+: ref_counter(0)
 {
     this->first = first;
     this->last = last;
     this->level = level;
 
-    next = new FastCallRange*[level];
+    next.resize(level, 0);
 }
 
 bool
@@ -64,9 +66,6 @@
     head.first = std::numeric_limits<CallNo>::max();
     head.last = std::numeric_limits<CallNo>::min();
 
-    for (int i = 0; i < MAX_LEVEL; i++)
-        head.next[i] = NULL;
-
     max_level = 0;
 }
 
@@ -97,15 +96,17 @@
 void
 FastCallSet::add(CallNo first, CallNo last)
 {
-    FastCallRange **update[MAX_LEVEL];
-    FastCallRange *node, *next;
+    std::vector<FastCallRangePtr*> update (MAX_LEVEL);
+    FastCallRange *node;
+    FastCallRangePtr new_node;
     int i, level;
 
-    /* Find node immediately before insertion point. */
-    node = &head;
+    /* Find node immediately before insertion point.
+     * NOTE: FastCallRangePtr(), e.g., next[i](), returns FastCallRange* */
+    node = &head;  // Can't reference &head as a FastCallRangePtr
     for (i = max_level - 1; i >= 0; i--) {
-        while (node->next[i] && first > node->next[i]->last) {
-            node = node->next[i];
+        while (node->next[i]() && first > node->next[i]->last) {
+            node = node->next[i]();
         }
         update[i] = &node->next[i];
     }
@@ -113,13 +114,14 @@
     /* Can we contain first by expanding tail of current range by 1? */
     if (node != &head && node->last == first - 1) {
 
-        node->last = last;
+        new_node = FastCallRangePtr(node);
+        new_node->last = last;
         goto MERGE_NODE_WITH_SUBSEQUENT_COVERED_NODES;
 
     }
 
     /* Current range could not contain first, look at next. */
-    node = node->next[0];
+    node = node->next[0]();
 
     if (node) {
         /* Do nothing if new range is already entirely contained. */
@@ -136,7 +138,8 @@
 
         /* This is our candidate node if first is contained */
         if (node->first <= first && node->last >= first) {
-            node->last = last;
+            new_node = FastCallRangePtr(node);
+            new_node->last = last;
             goto MERGE_NODE_WITH_SUBSEQUENT_COVERED_NODES;
         }
     }
@@ -152,21 +155,21 @@
         max_level = level;
     }
 
-    node = new FastCallRange(first, last, level);
+    new_node = FastCallRangePtr(new FastCallRange(first, last, level));
 
     /* Perform insertion into all lists. */
     for (i = 0; i < level; i++) {
-        node->next[i] = *update[i];
-        *update[i] = node;
+        new_node->next[i] = *update[i];
+        *update[i] = new_node;
     }
 
 MERGE_NODE_WITH_SUBSEQUENT_COVERED_NODES:
-    next = node->next[0];
-    while (next && next->first <= node->last + 1) {
+    FastCallRangePtr next = new_node->next[0];
+    node = new_node();
+    while (next() && next->first <= node->last + 1) {
         if (next->last > node->last)
             node->last = next->last;
 
-        /* Delete node 'next' */
         for (i = 0; i < node->level && i < next->level; i++) {
             node->next[i] = next->next[i];
         }
@@ -175,8 +178,6 @@
             *update[i] = next->next[i];
         }
 
-        delete next;
-
         next = node->next[0];
     }
 }
@@ -190,17 +191,17 @@
 bool
 FastCallSet::contains(CallNo call_no) const
 {
-    const FastCallRange *node;
+    FastCallRange *node;
     int i;
 
-    node = &head;
+    node = const_cast<FastCallRange*>(&head);
     for (i = max_level - 1; i >= 0; i--) {
-        while (node->next[i] && call_no > node->next[i]->last) {
-            node = node->next[i];
+        while (node->next[i]() && call_no > node->next[i]->last) {
+            node = node->next[i]();
         }
     }
 
-    node = node->next[0];
+    node = node->next[0]();
 
     if (node == NULL)
         return false;
diff --git a/src/apitrace/common/trace_fast_callset.hpp b/src/apitrace/common/trace_fast_callset.hpp
index af20005..4b27c7a 100644
--- a/src/apitrace/common/trace_fast_callset.hpp
+++ b/src/apitrace/common/trace_fast_callset.hpp
@@ -62,16 +62,63 @@
  * optimizations in some cases).
  */
 
+class FastCallRangePtr;
+
 class FastCallRange {
 public:
     CallNo first;
     CallNo last;
     int level;
-    FastCallRange **next;
+    std::vector<FastCallRangePtr> next;
 
+    // (NOTE: Initalize ref_counter to 0 in all constructors)
     FastCallRange(CallNo first, CallNo last, int level);
 
     bool contains(CallNo call_no) const;
+
+private:
+    friend class FastCallRangePtr;
+    size_t ref_counter;
+    // ref_counter must be initialized to 0 by all constructors
+    // ref_counter is the number of FastCallRangePtr objects that point at this
+};
+
+class FastCallRangePtr {
+public:
+    FastCallRange* operator-> () { return  this->ptr; }
+    FastCallRange& operator * () { return *this->ptr; }
+    FastCallRange* operator ()() { return  this->ptr; } // get pointer
+
+
+    FastCallRangePtr () : ptr(0) {}
+    FastCallRangePtr(FastCallRange* _ptr) : ptr(_ptr)
+                                 { if (this->ptr) ++this->ptr->ref_counter; }
+
+   ~FastCallRangePtr()           { if (this->ptr)
+                                       if (--this->ptr->ref_counter == 0)
+                                           delete this->ptr;
+                                 }
+
+    FastCallRangePtr(FastCallRangePtr const& _ptr) : ptr(_ptr.ptr)
+                                 { if (this->ptr) ++this->ptr->ref_counter; }
+
+    FastCallRangePtr& operator= (FastCallRangePtr const& new_ptr)
+        {   // DO NOT CHANGE THE ORDER OF THESE STATEMENTS!
+            // (This order properly handles self-assignment)
+            // (This order also properly handles recursion, e.g.,
+            //  if a FastCallRange contains FastCallRangePtrs)
+            FastCallRange* const old_ptr = this->ptr;
+            this->ptr = new_ptr.ptr;
+            if (this->ptr)
+                ++this->ptr->ref_counter;
+            if (old_ptr) {
+                if (--old_ptr->ref_counter == 0)
+                    delete old_ptr;
+            }
+            return *this;
+        }
+private:
+    FastCallRange* ptr;
 };
 
 class FastCallSet {
diff --git a/src/apitrace/dispatch/glproc.hpp b/src/apitrace/dispatch/glproc.hpp
index f39d5f8..5dc30a6 100644
--- a/src/apitrace/dispatch/glproc.hpp
+++ b/src/apitrace/dispatch/glproc.hpp
@@ -23492,10 +23492,10 @@
     _glClearNamedBufferDataEXT_ptr(buffer, internalformat, format, type, data);
 }
 
-typedef void (APIENTRY * PFN_GLCLEARNAMEDBUFFERSUBDATAEXT)(GLuint buffer, GLenum internalformat, GLenum format, GLenum type, GLsizeiptr offset, GLsizeiptr size, const void * data);
+typedef void (APIENTRY * PFN_GLCLEARNAMEDBUFFERSUBDATAEXT)(GLuint buffer, GLenum internalformat, GLsizeiptr offset, GLsizeiptr size, GLenum format, GLenum type, const void * data);
 static PFN_GLCLEARNAMEDBUFFERSUBDATAEXT _glClearNamedBufferSubDataEXT_ptr = NULL;
 
-static inline void APIENTRY _glClearNamedBufferSubDataEXT(GLuint buffer, GLenum internalformat, GLenum format, GLenum type, GLsizeiptr offset, GLsizeiptr size, const void * data) {
+static inline void APIENTRY _glClearNamedBufferSubDataEXT(GLuint buffer, GLenum internalformat, GLsizeiptr offset, GLsizeiptr size, GLenum format, GLenum type, const void * data) {
     const char *_name = "glClearNamedBufferSubDataEXT";
     if (!_glClearNamedBufferSubDataEXT_ptr) {
         _glClearNamedBufferSubDataEXT_ptr = (PFN_GLCLEARNAMEDBUFFERSUBDATAEXT)_getPrivateProcAddress(_name);
@@ -23504,7 +23504,7 @@
             return;
         }
     }
-    _glClearNamedBufferSubDataEXT_ptr(buffer, internalformat, format, type, offset, size, data);
+    _glClearNamedBufferSubDataEXT_ptr(buffer, internalformat, offset, size, format, type, data);
 }
 
 typedef void (APIENTRY * PFN_GLDISPATCHCOMPUTE)(GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z);
@@ -42710,6 +42710,21 @@
     _glDrawTextureNV_ptr(texture, sampler, x0, y0, x1, y1, z, s0, t0, s1, t1);
 }
 
+typedef void (APIENTRY * PFN_GLBLITFRAMEBUFFERNV)(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
+static PFN_GLBLITFRAMEBUFFERNV _glBlitFramebufferNV_ptr = NULL;
+
+static inline void APIENTRY _glBlitFramebufferNV(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) {
+    const char *_name = "glBlitFramebufferNV";
+    if (!_glBlitFramebufferNV_ptr) {
+        _glBlitFramebufferNV_ptr = (PFN_GLBLITFRAMEBUFFERNV)_getPrivateProcAddress(_name);
+        if (!_glBlitFramebufferNV_ptr) {
+            os::log("warning: ignoring call to unavailable function %s\n", _name);
+            return;
+        }
+    }
+    _glBlitFramebufferNV_ptr(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter);
+}
+
 typedef GLuint (APIENTRY * PFN_GLNEWBUFFERREGION)(GLenum type);
 static PFN_GLNEWBUFFERREGION _glNewBufferRegion_ptr = NULL;
 
@@ -45247,6 +45262,7 @@
 #define glTexStorageSparseAMD _glTexStorageSparseAMD
 #define glTextureStorageSparseAMD _glTextureStorageSparseAMD
 #define glDrawTextureNV _glDrawTextureNV
+#define glBlitFramebufferNV _glBlitFramebufferNV
 #define glNewBufferRegion _glNewBufferRegion
 #define glDeleteBufferRegion _glDeleteBufferRegion
 #define glReadBufferRegion _glReadBufferRegion
diff --git a/src/apitrace/helpers/glsize.hpp b/src/apitrace/helpers/glsize.hpp
index 7c1d017..0293a13 100644
--- a/src/apitrace/helpers/glsize.hpp
+++ b/src/apitrace/helpers/glsize.hpp
@@ -896,12 +896,26 @@
         image_height = height;
     }
 
-    /* XXX: GL_UNPACK_IMAGE_HEIGHT and GL_UNPACK_SKIP_IMAGES should probably
-     * not be considered for pixel rectangles. */
-
     size_t image_stride = image_height*row_stride;
 
-    size_t size = depth*image_stride;
+    /*
+     * We can't just do
+     *
+     *   size = depth*image_stride
+     *
+     * here as that could result in reading beyond the end of the buffer when
+     * selecting sub-rectangles via GL_UNPACK_SKIP_*.
+     */
+    size_t size = (width*bits_per_pixel + 7)/8;
+    if (height > 1) {
+        size += (height - 1)*row_stride;
+    }
+    if (depth > 1) {
+        size += (depth - 1)*image_stride;
+    }
+
+    /* XXX: GL_UNPACK_IMAGE_HEIGHT and GL_UNPACK_SKIP_IMAGES should probably
+     * not be considered for pixel rectangles. */
 
     size += (skip_pixels*bits_per_pixel + 7)/8;
     size += skip_rows*row_stride;
diff --git a/src/apitrace/specs/d3d9.py b/src/apitrace/specs/d3d9.py
index 59b0eda..5530ccb 100644
--- a/src/apitrace/specs/d3d9.py
+++ b/src/apitrace/specs/d3d9.py
@@ -182,8 +182,8 @@
     StdMethod(HRESULT, "CreateDepthStencilSurface", [(UINT, "Width"), (UINT, "Height"), (D3DFORMAT, "Format"), (D3DMULTISAMPLE_TYPE, "MultiSample"), (DWORD, "MultisampleQuality"), (BOOL, "Discard"), Out(Pointer(PDIRECT3DSURFACE9), "ppSurface"), (Pointer(HANDLE), "pSharedHandle")]),
     StdMethod(HRESULT, "UpdateSurface", [(PDIRECT3DSURFACE9, "pSourceSurface"), (ConstPointer(RECT), "pSourceRect"), (PDIRECT3DSURFACE9, "pDestinationSurface"), (ConstPointer(POINT), "pDestPoint")]),
     StdMethod(HRESULT, "UpdateTexture", [(PDIRECT3DBASETEXTURE9, "pSourceTexture"), (PDIRECT3DBASETEXTURE9, "pDestinationTexture")]),
-    StdMethod(HRESULT, "GetRenderTargetData", [(PDIRECT3DSURFACE9, "pRenderTarget"), (PDIRECT3DSURFACE9, "pDestSurface")], sideeffects=False),
-    StdMethod(HRESULT, "GetFrontBufferData", [(UINT, "iSwapChain"), (PDIRECT3DSURFACE9, "pDestSurface")], sideeffects=False),
+    StdMethod(HRESULT, "GetRenderTargetData", [(PDIRECT3DSURFACE9, "pRenderTarget"), (PDIRECT3DSURFACE9, "pDestSurface")]),
+    StdMethod(HRESULT, "GetFrontBufferData", [(UINT, "iSwapChain"), (PDIRECT3DSURFACE9, "pDestSurface")]),
     StdMethod(HRESULT, "StretchRect", [(PDIRECT3DSURFACE9, "pSourceSurface"), (ConstPointer(RECT), "pSourceRect"), (PDIRECT3DSURFACE9, "pDestSurface"), (ConstPointer(RECT), "pDestRect"), (D3DTEXTUREFILTERTYPE, "Filter")]),
     StdMethod(HRESULT, "ColorFill", [(PDIRECT3DSURFACE9, "pSurface"), (ConstPointer(RECT), "pRect"), (D3DCOLOR, "color")]),
     StdMethod(HRESULT, "CreateOffscreenPlainSurface", [(UINT, "Width"), (UINT, "Height"), (D3DFORMAT, "Format"), (D3DPOOL, "Pool"), Out(Pointer(PDIRECT3DSURFACE9), "ppSurface"), (Pointer(HANDLE), "pSharedHandle")]),
@@ -279,7 +279,7 @@
 
 IDirect3DSwapChain9.methods += [
     StdMethod(HRESULT, "Present", [(ConstPointer(RECT), "pSourceRect"), (ConstPointer(RECT), "pDestRect"), (HWND, "hDestWindowOverride"), (ConstPointer(RGNDATA), "pDirtyRegion"), (D3DPRESENT, "dwFlags")]),
-    StdMethod(HRESULT, "GetFrontBufferData", [(PDIRECT3DSURFACE9, "pDestSurface")], sideeffects=False),
+    StdMethod(HRESULT, "GetFrontBufferData", [(PDIRECT3DSURFACE9, "pDestSurface")]),
     StdMethod(HRESULT, "GetBackBuffer", [(UINT, "iBackBuffer"), (D3DBACKBUFFER_TYPE, "Type"), Out(Pointer(PDIRECT3DSURFACE9), "ppBackBuffer")]),
     StdMethod(HRESULT, "GetRasterStatus", [Out(Pointer(D3DRASTER_STATUS), "pRasterStatus")], sideeffects=False),
     StdMethod(HRESULT, "GetDisplayMode", [Out(Pointer(D3DDISPLAYMODE), "pMode")], sideeffects=False),
@@ -383,7 +383,7 @@
     StdMethod(D3DQUERYTYPE, "GetType", [], sideeffects=False),
     StdMethod(DWORD, "GetDataSize", [], sideeffects=False),
     StdMethod(HRESULT, "Issue", [(D3DISSUE, "dwIssueFlags")]),
-    StdMethod(HRESULT, "GetData", [Out(Blob(Void, "dwSize"), "pData"), (DWORD, "dwSize"), (D3DGETDATA, "dwGetDataFlags")], sideeffects=False),
+    StdMethod(HRESULT, "GetData", [Out(D3DQUERYDATA, "pData"), (DWORD, "dwSize"), (D3DGETDATA, "dwGetDataFlags")], sideeffects=False),
 ]
 
 IDirect3D9Ex.methods += [
diff --git a/src/apitrace/specs/d3d9types.py b/src/apitrace/specs/d3d9types.py
index dc9e852..a9aefff 100644
--- a/src/apitrace/specs/d3d9types.py
+++ b/src/apitrace/specs/d3d9types.py
@@ -979,23 +979,6 @@
     (UINT, "ScanLine"),
 ])
 
-D3DQUERYTYPE = Enum("D3DQUERYTYPE", [
-    "D3DQUERYTYPE_VCACHE",
-    "D3DQUERYTYPE_RESOURCEMANAGER",
-    "D3DQUERYTYPE_VERTEXSTATS",
-    "D3DQUERYTYPE_EVENT",
-    "D3DQUERYTYPE_OCCLUSION",
-    "D3DQUERYTYPE_TIMESTAMP",
-    "D3DQUERYTYPE_TIMESTAMPDISJOINT",
-    "D3DQUERYTYPE_TIMESTAMPFREQ",
-    "D3DQUERYTYPE_PIPELINETIMINGS",
-    "D3DQUERYTYPE_INTERFACETIMINGS",
-    "D3DQUERYTYPE_VERTEXTIMINGS",
-    "D3DQUERYTYPE_PIXELTIMINGS",
-    "D3DQUERYTYPE_BANDWIDTHTIMINGS",
-    "D3DQUERYTYPE_CACHEUTILIZATION",
-])
-
 D3DISSUE = Flags(DWORD, [
     "D3DISSUE_END",
     "D3DISSUE_BEGIN",
@@ -1068,6 +1051,23 @@
     (FLOAT, "PostTransformVertexCacheHitRate"),
 ])
 
+D3DQUERYTYPE, D3DQUERYDATA = EnumPolymorphic("D3DQUERYTYPE", "_this->GetType()", [
+    ("D3DQUERYTYPE_VCACHE", Pointer(D3DDEVINFO_VCACHE)),
+    ("D3DQUERYTYPE_RESOURCEMANAGER", Pointer(D3DDEVINFO_RESOURCEMANAGER)),
+    ("D3DQUERYTYPE_VERTEXSTATS", Pointer(D3DDEVINFO_D3DVERTEXSTATS)),
+    ("D3DQUERYTYPE_EVENT", Pointer(BOOL)),
+    ("D3DQUERYTYPE_OCCLUSION", Pointer(DWORD)),
+    ("D3DQUERYTYPE_TIMESTAMP", Pointer(UINT64)),
+    ("D3DQUERYTYPE_TIMESTAMPDISJOINT", Pointer(BOOL)),
+    ("D3DQUERYTYPE_TIMESTAMPFREQ", Pointer(UINT64)),
+    ("D3DQUERYTYPE_PIPELINETIMINGS", Pointer(D3DDEVINFO_D3D9PIPELINETIMINGS)),
+    ("D3DQUERYTYPE_INTERFACETIMINGS", Pointer(D3DDEVINFO_D3D9INTERFACETIMINGS)),
+    ("D3DQUERYTYPE_VERTEXTIMINGS", Pointer(D3DDEVINFO_D3D9STAGETIMINGS)),
+    ("D3DQUERYTYPE_PIXELTIMINGS", Pointer(D3DDEVINFO_D3D9STAGETIMINGS)),
+    ("D3DQUERYTYPE_BANDWIDTHTIMINGS", Pointer(D3DDEVINFO_D3D9BANDWIDTHTIMINGS)),
+    ("D3DQUERYTYPE_CACHEUTILIZATION", Pointer(D3DDEVINFO_D3D9CACHEUTILIZATION)),
+], Blob(Void, "dwSize"), False)
+
 D3DCOMPOSERECTSOP = Enum("D3DCOMPOSERECTSOP", [
     "D3DCOMPOSERECTS_COPY",
     "D3DCOMPOSERECTS_OR",
diff --git a/src/apitrace/specs/glapi.py b/src/apitrace/specs/glapi.py
index e0489bc..1e620fb 100644
--- a/src/apitrace/specs/glapi.py
+++ b/src/apitrace/specs/glapi.py
@@ -1376,7 +1376,7 @@
     GlFunction(Void, "glClearBufferData", [(GLenum, "target"), (GLenum, "internalformat"), (GLenum, "format"), (GLenum, "type"), (Blob(Const(Void), "_glClearBufferData_size(format, type)"), "data")]),
     GlFunction(Void, "glClearBufferSubData", [(GLenum, "target"), (GLenum, "internalformat"), (GLintptr, "offset"), (GLsizeiptr, "size"), (GLenum, "format"), (GLenum, "type"), (Blob(Const(Void), "_glClearBufferData_size(format, type)"), "data")]),
     GlFunction(Void, "glClearNamedBufferDataEXT", [(GLbuffer, "buffer"), (GLenum, "internalformat"), (GLenum, "format"), (GLenum, "type"), (Blob(Const(Void), "_glClearBufferData_size(format, type)"), "data")]),
-    GlFunction(Void, "glClearNamedBufferSubDataEXT", [(GLbuffer, "buffer"), (GLenum, "internalformat"), (GLenum, "format"), (GLenum, "type"), (GLsizeiptr, "offset"), (GLsizeiptr, "size"), (Blob(Const(Void), "_glClearBufferData_size(format, type)"), "data")]),
+    GlFunction(Void, "glClearNamedBufferSubDataEXT", [(GLbuffer, "buffer"), (GLenum, "internalformat"), (GLsizeiptr, "offset"), (GLsizeiptr, "size"), (GLenum, "format"), (GLenum, "type"), (Blob(Const(Void), "_glClearBufferData_size(format, type)"), "data")]),
 
     # GL_ARB_compute_shader
     GlFunction(Void, "glDispatchCompute", [(GLuint, "num_groups_x"), (GLuint, "num_groups_y"), (GLuint, "num_groups_z")]),
@@ -3015,6 +3015,9 @@
     # GL_NV_draw_texture
     GlFunction(Void, "glDrawTextureNV", [(GLtexture, "texture"), (GLsampler, "sampler"), (GLfloat, "x0"), (GLfloat, "y0"), (GLfloat, "x1"), (GLfloat, "y1"), (GLfloat, "z"), (GLfloat, "s0"), (GLfloat, "t0"), (GLfloat, "s1"), (GLfloat, "t1")]),
 
+    # GL_NV_framebuffer_blit
+    GlFunction(Void, "glBlitFramebufferNV", [(GLint, "srcX0"), (GLint, "srcY0"), (GLint, "srcX1"), (GLint, "srcY1"), (GLint, "dstX0"), (GLint, "dstY0"), (GLint, "dstX1"), (GLint, "dstY1"), (GLbitfield_attrib, "mask"), (GLenum, "filter")]),
+
     # GL_KTX_buffer_region
     # XXX: http://www.west.net/~brittain/3dsmax2.htm does not mention EXT suffix
     GlFunction(GLregion, "glNewBufferRegion", [(GLenum, "type")]),
diff --git a/src/apitrace/thirdparty/khronos/GL/glext.h b/src/apitrace/thirdparty/khronos/GL/glext.h
index 54e76ce..876acd3 100644
--- a/src/apitrace/thirdparty/khronos/GL/glext.h
+++ b/src/apitrace/thirdparty/khronos/GL/glext.h
@@ -33,7 +33,7 @@
 ** used to make the header, and the header can be found at
 **   http://www.opengl.org/registry/
 **
-** Khronos $Revision: 24205 $ on $Date: 2013-11-26 04:42:27 -0800 (Tue, 26 Nov 2013) $
+** Khronos $Revision: 24756 $ on $Date: 2014-01-14 03:42:29 -0800 (Tue, 14 Jan 2014) $
 */
 
 #if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__)
@@ -53,7 +53,7 @@
 #define GLAPI extern
 #endif
 
-#define GL_GLEXT_VERSION 20131126
+#define GL_GLEXT_VERSION 20140114
 
 /* Generated C header for:
  * API: gl
@@ -1485,7 +1485,7 @@
 typedef void (APIENTRYP PFNGLTEXIMAGE2DMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations);
 typedef void (APIENTRYP PFNGLTEXIMAGE3DMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations);
 typedef void (APIENTRYP PFNGLGETMULTISAMPLEFVPROC) (GLenum pname, GLuint index, GLfloat *val);
-typedef void (APIENTRYP PFNGLSAMPLEMASKIPROC) (GLuint index, GLbitfield mask);
+typedef void (APIENTRYP PFNGLSAMPLEMASKIPROC) (GLuint maskNumber, GLbitfield mask);
 #ifdef GL_GLEXT_PROTOTYPES
 GLAPI void APIENTRY glDrawElementsBaseVertex (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex);
 GLAPI void APIENTRY glDrawRangeElementsBaseVertex (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLint basevertex);
@@ -1505,7 +1505,7 @@
 GLAPI void APIENTRY glTexImage2DMultisample (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations);
 GLAPI void APIENTRY glTexImage3DMultisample (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations);
 GLAPI void APIENTRY glGetMultisamplefv (GLenum pname, GLuint index, GLfloat *val);
-GLAPI void APIENTRY glSampleMaski (GLuint index, GLbitfield mask);
+GLAPI void APIENTRY glSampleMaski (GLuint maskNumber, GLbitfield mask);
 #endif
 #endif /* GL_VERSION_3_2 */
 
@@ -2144,6 +2144,10 @@
 #define GL_MAX_GEOMETRY_IMAGE_UNIFORMS    0x90CD
 #define GL_MAX_FRAGMENT_IMAGE_UNIFORMS    0x90CE
 #define GL_MAX_COMBINED_IMAGE_UNIFORMS    0x90CF
+#define GL_COMPRESSED_RGBA_BPTC_UNORM     0x8E8C
+#define GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM 0x8E8D
+#define GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT 0x8E8E
+#define GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT 0x8E8F
 #define GL_TEXTURE_IMMUTABLE_FORMAT       0x912F
 typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEPROC) (GLenum mode, GLint first, GLsizei count, GLsizei instancecount, GLuint baseinstance);
 typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLuint baseinstance);
@@ -6177,7 +6181,7 @@
 typedef void (APIENTRYP PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr length);
 typedef void (APIENTRYP PFNGLNAMEDBUFFERSTORAGEEXTPROC) (GLuint buffer, GLsizeiptr size, const void *data, GLbitfield flags);
 typedef void (APIENTRYP PFNGLCLEARNAMEDBUFFERDATAEXTPROC) (GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const void *data);
-typedef void (APIENTRYP PFNGLCLEARNAMEDBUFFERSUBDATAEXTPROC) (GLuint buffer, GLenum internalformat, GLenum format, GLenum type, GLsizeiptr offset, GLsizeiptr size, const void *data);
+typedef void (APIENTRYP PFNGLCLEARNAMEDBUFFERSUBDATAEXTPROC) (GLuint buffer, GLenum internalformat, GLsizeiptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data);
 typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERPARAMETERIEXTPROC) (GLuint framebuffer, GLenum pname, GLint param);
 typedef void (APIENTRYP PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVEXTPROC) (GLuint framebuffer, GLenum pname, GLint *params);
 typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1DEXTPROC) (GLuint program, GLint location, GLdouble x);
@@ -6433,7 +6437,7 @@
 GLAPI void APIENTRY glFlushMappedNamedBufferRangeEXT (GLuint buffer, GLintptr offset, GLsizeiptr length);
 GLAPI void APIENTRY glNamedBufferStorageEXT (GLuint buffer, GLsizeiptr size, const void *data, GLbitfield flags);
 GLAPI void APIENTRY glClearNamedBufferDataEXT (GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const void *data);
-GLAPI void APIENTRY glClearNamedBufferSubDataEXT (GLuint buffer, GLenum internalformat, GLenum format, GLenum type, GLsizeiptr offset, GLsizeiptr size, const void *data);
+GLAPI void APIENTRY glClearNamedBufferSubDataEXT (GLuint buffer, GLenum internalformat, GLsizeiptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data);
 GLAPI void APIENTRY glNamedFramebufferParameteriEXT (GLuint framebuffer, GLenum pname, GLint param);
 GLAPI void APIENTRY glGetNamedFramebufferParameterivEXT (GLuint framebuffer, GLenum pname, GLint *params);
 GLAPI void APIENTRY glProgramUniform1dEXT (GLuint program, GLint location, GLdouble x);
@@ -8122,6 +8126,52 @@
 #endif
 #endif /* GL_INTEL_parallel_arrays */
 
+#ifndef GL_INTEL_performance_query
+#define GL_INTEL_performance_query 1
+#define GL_PERFQUERY_SINGLE_CONTEXT_INTEL 0x00000000
+#define GL_PERFQUERY_GLOBAL_CONTEXT_INTEL 0x00000001
+#define GL_PERFQUERY_WAIT_INTEL           0x83FB
+#define GL_PERFQUERY_FLUSH_INTEL          0x83FA
+#define GL_PERFQUERY_DONOT_FLUSH_INTEL    0x83F9
+#define GL_PERFQUERY_COUNTER_EVENT_INTEL  0x94F0
+#define GL_PERFQUERY_COUNTER_DURATION_NORM_INTEL 0x94F1
+#define GL_PERFQUERY_COUNTER_DURATION_RAW_INTEL 0x94F2
+#define GL_PERFQUERY_COUNTER_THROUGHPUT_INTEL 0x94F3
+#define GL_PERFQUERY_COUNTER_RAW_INTEL    0x94F4
+#define GL_PERFQUERY_COUNTER_TIMESTAMP_INTEL 0x94F5
+#define GL_PERFQUERY_COUNTER_DATA_UINT32_INTEL 0x94F8
+#define GL_PERFQUERY_COUNTER_DATA_UINT64_INTEL 0x94F9
+#define GL_PERFQUERY_COUNTER_DATA_FLOAT_INTEL 0x94FA
+#define GL_PERFQUERY_COUNTER_DATA_DOUBLE_INTEL 0x94FB
+#define GL_PERFQUERY_COUNTER_DATA_BOOL32_INTEL 0x94FC
+#define GL_PERFQUERY_QUERY_NAME_LENGTH_MAX_INTEL 0x94FD
+#define GL_PERFQUERY_COUNTER_NAME_LENGTH_MAX_INTEL 0x94FE
+#define GL_PERFQUERY_COUNTER_DESC_LENGTH_MAX_INTEL 0x94FF
+#define GL_PERFQUERY_GPA_EXTENDED_COUNTERS_INTEL 0x9500
+typedef void (APIENTRYP PFNGLBEGINPERFQUERYINTELPROC) (GLuint queryHandle);
+typedef void (APIENTRYP PFNGLCREATEPERFQUERYINTELPROC) (GLuint queryId, GLuint *queryHandle);
+typedef void (APIENTRYP PFNGLDELETEPERFQUERYINTELPROC) (GLuint queryHandle);
+typedef void (APIENTRYP PFNGLENDPERFQUERYINTELPROC) (GLuint queryHandle);
+typedef void (APIENTRYP PFNGLGETFIRSTPERFQUERYIDINTELPROC) (GLuint *queryId);
+typedef void (APIENTRYP PFNGLGETNEXTPERFQUERYIDINTELPROC) (GLuint queryId, GLuint *nextQueryId);
+typedef void (APIENTRYP PFNGLGETPERFCOUNTERINFOINTELPROC) (GLuint queryId, GLuint counterId, GLuint counterNameLength, GLchar *counterName, GLuint counterDescLength, GLchar *counterDesc, GLuint *counterOffset, GLuint *counterDataSize, GLuint *counterTypeEnum, GLuint *counterDataTypeEnum, GLuint64 *rawCounterMaxValue);
+typedef void (APIENTRYP PFNGLGETPERFQUERYDATAINTELPROC) (GLuint queryHandle, GLuint flags, GLsizei dataSize, GLvoid *data, GLuint *bytesWritten);
+typedef void (APIENTRYP PFNGLGETPERFQUERYIDBYNAMEINTELPROC) (GLchar *queryName, GLuint *queryId);
+typedef void (APIENTRYP PFNGLGETPERFQUERYINFOINTELPROC) (GLuint queryId, GLuint queryNameLength, GLchar *queryName, GLuint *dataSize, GLuint *noCounters, GLuint *noInstances, GLuint *capsMask);
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBeginPerfQueryINTEL (GLuint queryHandle);
+GLAPI void APIENTRY glCreatePerfQueryINTEL (GLuint queryId, GLuint *queryHandle);
+GLAPI void APIENTRY glDeletePerfQueryINTEL (GLuint queryHandle);
+GLAPI void APIENTRY glEndPerfQueryINTEL (GLuint queryHandle);
+GLAPI void APIENTRY glGetFirstPerfQueryIdINTEL (GLuint *queryId);
+GLAPI void APIENTRY glGetNextPerfQueryIdINTEL (GLuint queryId, GLuint *nextQueryId);
+GLAPI void APIENTRY glGetPerfCounterInfoINTEL (GLuint queryId, GLuint counterId, GLuint counterNameLength, GLchar *counterName, GLuint counterDescLength, GLchar *counterDesc, GLuint *counterOffset, GLuint *counterDataSize, GLuint *counterTypeEnum, GLuint *counterDataTypeEnum, GLuint64 *rawCounterMaxValue);
+GLAPI void APIENTRY glGetPerfQueryDataINTEL (GLuint queryHandle, GLuint flags, GLsizei dataSize, GLvoid *data, GLuint *bytesWritten);
+GLAPI void APIENTRY glGetPerfQueryIdByNameINTEL (GLchar *queryName, GLuint *queryId);
+GLAPI void APIENTRY glGetPerfQueryInfoINTEL (GLuint queryId, GLuint queryNameLength, GLchar *queryName, GLuint *dataSize, GLuint *noCounters, GLuint *noInstances, GLuint *capsMask);
+#endif
+#endif /* GL_INTEL_performance_query */
+
 #ifndef GL_MESAX_texture_stack
 #define GL_MESAX_texture_stack 1
 #define GL_TEXTURE_1D_STACK_MESAX         0x8759
@@ -9643,7 +9693,7 @@
 typedef void (APIENTRYP PFNGLVDPAUFININVPROC) (void);
 typedef GLvdpauSurfaceNV (APIENTRYP PFNGLVDPAUREGISTERVIDEOSURFACENVPROC) (const void *vdpSurface, GLenum target, GLsizei numTextureNames, const GLuint *textureNames);
 typedef GLvdpauSurfaceNV (APIENTRYP PFNGLVDPAUREGISTEROUTPUTSURFACENVPROC) (const void *vdpSurface, GLenum target, GLsizei numTextureNames, const GLuint *textureNames);
-typedef void (APIENTRYP PFNGLVDPAUISSURFACENVPROC) (GLvdpauSurfaceNV surface);
+typedef GLboolean (APIENTRYP PFNGLVDPAUISSURFACENVPROC) (GLvdpauSurfaceNV surface);
 typedef void (APIENTRYP PFNGLVDPAUUNREGISTERSURFACENVPROC) (GLvdpauSurfaceNV surface);
 typedef void (APIENTRYP PFNGLVDPAUGETSURFACEIVNVPROC) (GLvdpauSurfaceNV surface, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values);
 typedef void (APIENTRYP PFNGLVDPAUSURFACEACCESSNVPROC) (GLvdpauSurfaceNV surface, GLenum access);
@@ -9654,7 +9704,7 @@
 GLAPI void APIENTRY glVDPAUFiniNV (void);
 GLAPI GLvdpauSurfaceNV APIENTRY glVDPAURegisterVideoSurfaceNV (const void *vdpSurface, GLenum target, GLsizei numTextureNames, const GLuint *textureNames);
 GLAPI GLvdpauSurfaceNV APIENTRY glVDPAURegisterOutputSurfaceNV (const void *vdpSurface, GLenum target, GLsizei numTextureNames, const GLuint *textureNames);
-GLAPI void APIENTRY glVDPAUIsSurfaceNV (GLvdpauSurfaceNV surface);
+GLAPI GLboolean APIENTRY glVDPAUIsSurfaceNV (GLvdpauSurfaceNV surface);
 GLAPI void APIENTRY glVDPAUUnregisterSurfaceNV (GLvdpauSurfaceNV surface);
 GLAPI void APIENTRY glVDPAUGetSurfaceivNV (GLvdpauSurfaceNV surface, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values);
 GLAPI void APIENTRY glVDPAUSurfaceAccessNV (GLvdpauSurfaceNV surface, GLenum access);
diff --git a/src/apitrace/wrappers/regaltrace.cpp b/src/apitrace/wrappers/regaltrace.cpp
index d6287d5..fba08a6 100644
--- a/src/apitrace/wrappers/regaltrace.cpp
+++ b/src/apitrace/wrappers/regaltrace.cpp
@@ -10109,7 +10109,7 @@
 static const char * _glClearNamedBufferDataEXT_args[5] = {"buffer", "internalformat", "format", "type", "data"};
 static const trace::FunctionSig _glClearNamedBufferDataEXT_sig = {1168, "glClearNamedBufferDataEXT", 5, _glClearNamedBufferDataEXT_args};
 
-static const char * _glClearNamedBufferSubDataEXT_args[7] = {"buffer", "internalformat", "format", "type", "offset", "size", "data"};
+static const char * _glClearNamedBufferSubDataEXT_args[7] = {"buffer", "internalformat", "offset", "size", "format", "type", "data"};
 static const trace::FunctionSig _glClearNamedBufferSubDataEXT_sig = {1169, "glClearNamedBufferSubDataEXT", 7, _glClearNamedBufferSubDataEXT_args};
 
 static const char * _glDispatchCompute_args[3] = {"num_groups_x", "num_groups_y", "num_groups_z"};
@@ -13952,1522 +13952,1525 @@
 static const char * _glDrawTextureNV_args[11] = {"texture", "sampler", "x0", "y0", "x1", "y1", "z", "s0", "t0", "s1", "t1"};
 static const trace::FunctionSig _glDrawTextureNV_sig = {2449, "glDrawTextureNV", 11, _glDrawTextureNV_args};
 
+static const char * _glBlitFramebufferNV_args[10] = {"srcX0", "srcY0", "srcX1", "srcY1", "dstX0", "dstY0", "dstX1", "dstY1", "mask", "filter"};
+static const trace::FunctionSig _glBlitFramebufferNV_sig = {2450, "glBlitFramebufferNV", 10, _glBlitFramebufferNV_args};
+
 static const char * _glNewBufferRegion_args[1] = {"type"};
-static const trace::FunctionSig _glNewBufferRegion_sig = {2450, "glNewBufferRegion", 1, _glNewBufferRegion_args};
+static const trace::FunctionSig _glNewBufferRegion_sig = {2451, "glNewBufferRegion", 1, _glNewBufferRegion_args};
 
 static const char * _glDeleteBufferRegion_args[1] = {"region"};
-static const trace::FunctionSig _glDeleteBufferRegion_sig = {2451, "glDeleteBufferRegion", 1, _glDeleteBufferRegion_args};
+static const trace::FunctionSig _glDeleteBufferRegion_sig = {2452, "glDeleteBufferRegion", 1, _glDeleteBufferRegion_args};
 
 static const char * _glReadBufferRegion_args[5] = {"region", "x", "y", "width", "height"};
-static const trace::FunctionSig _glReadBufferRegion_sig = {2452, "glReadBufferRegion", 5, _glReadBufferRegion_args};
+static const trace::FunctionSig _glReadBufferRegion_sig = {2453, "glReadBufferRegion", 5, _glReadBufferRegion_args};
 
 static const char * _glDrawBufferRegion_args[7] = {"region", "x", "y", "width", "height", "xDest", "yDest"};
-static const trace::FunctionSig _glDrawBufferRegion_sig = {2453, "glDrawBufferRegion", 7, _glDrawBufferRegion_args};
+static const trace::FunctionSig _glDrawBufferRegion_sig = {2454, "glDrawBufferRegion", 7, _glDrawBufferRegion_args};
 
 static const char ** _glBufferRegionEnabled_args = NULL;
-static const trace::FunctionSig _glBufferRegionEnabled_sig = {2454, "glBufferRegionEnabled", 0, _glBufferRegionEnabled_args};
+static const trace::FunctionSig _glBufferRegionEnabled_sig = {2455, "glBufferRegionEnabled", 0, _glBufferRegionEnabled_args};
 
 static const char * _glAddSwapHintRectWIN_args[4] = {"x", "y", "width", "height"};
-static const trace::FunctionSig _glAddSwapHintRectWIN_sig = {2455, "glAddSwapHintRectWIN", 4, _glAddSwapHintRectWIN_args};
+static const trace::FunctionSig _glAddSwapHintRectWIN_sig = {2456, "glAddSwapHintRectWIN", 4, _glAddSwapHintRectWIN_args};
 
 static const char * _glFrustumf_args[6] = {"left", "right", "bottom", "top", "zNear", "zFar"};
-static const trace::FunctionSig _glFrustumf_sig = {2456, "glFrustumf", 6, _glFrustumf_args};
+static const trace::FunctionSig _glFrustumf_sig = {2457, "glFrustumf", 6, _glFrustumf_args};
 
 static const char * _glOrthof_args[6] = {"left", "right", "bottom", "top", "zNear", "zFar"};
-static const trace::FunctionSig _glOrthof_sig = {2457, "glOrthof", 6, _glOrthof_args};
+static const trace::FunctionSig _glOrthof_sig = {2458, "glOrthof", 6, _glOrthof_args};
 
 static const char * _glClipPlanef_args[2] = {"plane", "equation"};
-static const trace::FunctionSig _glClipPlanef_sig = {2458, "glClipPlanef", 2, _glClipPlanef_args};
+static const trace::FunctionSig _glClipPlanef_sig = {2459, "glClipPlanef", 2, _glClipPlanef_args};
 
 static const char * _glGetClipPlanef_args[2] = {"plane", "equation"};
-static const trace::FunctionSig _glGetClipPlanef_sig = {2459, "glGetClipPlanef", 2, _glGetClipPlanef_args};
+static const trace::FunctionSig _glGetClipPlanef_sig = {2460, "glGetClipPlanef", 2, _glGetClipPlanef_args};
 
 static const char * _glAlphaFuncx_args[2] = {"func", "ref"};
-static const trace::FunctionSig _glAlphaFuncx_sig = {2460, "glAlphaFuncx", 2, _glAlphaFuncx_args};
+static const trace::FunctionSig _glAlphaFuncx_sig = {2461, "glAlphaFuncx", 2, _glAlphaFuncx_args};
 
 static const char * _glClearColorx_args[4] = {"red", "green", "blue", "alpha"};
-static const trace::FunctionSig _glClearColorx_sig = {2461, "glClearColorx", 4, _glClearColorx_args};
+static const trace::FunctionSig _glClearColorx_sig = {2462, "glClearColorx", 4, _glClearColorx_args};
 
 static const char * _glClearDepthx_args[1] = {"depth"};
-static const trace::FunctionSig _glClearDepthx_sig = {2462, "glClearDepthx", 1, _glClearDepthx_args};
+static const trace::FunctionSig _glClearDepthx_sig = {2463, "glClearDepthx", 1, _glClearDepthx_args};
 
 static const char * _glColor4x_args[4] = {"red", "green", "blue", "alpha"};
-static const trace::FunctionSig _glColor4x_sig = {2463, "glColor4x", 4, _glColor4x_args};
+static const trace::FunctionSig _glColor4x_sig = {2464, "glColor4x", 4, _glColor4x_args};
 
 static const char * _glDepthRangex_args[2] = {"zNear", "zFar"};
-static const trace::FunctionSig _glDepthRangex_sig = {2464, "glDepthRangex", 2, _glDepthRangex_args};
+static const trace::FunctionSig _glDepthRangex_sig = {2465, "glDepthRangex", 2, _glDepthRangex_args};
 
 static const char * _glFogx_args[2] = {"pname", "param"};
-static const trace::FunctionSig _glFogx_sig = {2465, "glFogx", 2, _glFogx_args};
+static const trace::FunctionSig _glFogx_sig = {2466, "glFogx", 2, _glFogx_args};
 
 static const char * _glFogxv_args[2] = {"pname", "params"};
-static const trace::FunctionSig _glFogxv_sig = {2466, "glFogxv", 2, _glFogxv_args};
+static const trace::FunctionSig _glFogxv_sig = {2467, "glFogxv", 2, _glFogxv_args};
 
 static const char * _glFrustumx_args[6] = {"left", "right", "bottom", "top", "zNear", "zFar"};
-static const trace::FunctionSig _glFrustumx_sig = {2467, "glFrustumx", 6, _glFrustumx_args};
+static const trace::FunctionSig _glFrustumx_sig = {2468, "glFrustumx", 6, _glFrustumx_args};
 
 static const char * _glLightModelx_args[2] = {"pname", "param"};
-static const trace::FunctionSig _glLightModelx_sig = {2468, "glLightModelx", 2, _glLightModelx_args};
+static const trace::FunctionSig _glLightModelx_sig = {2469, "glLightModelx", 2, _glLightModelx_args};
 
 static const char * _glLightModelxv_args[2] = {"pname", "params"};
-static const trace::FunctionSig _glLightModelxv_sig = {2469, "glLightModelxv", 2, _glLightModelxv_args};
+static const trace::FunctionSig _glLightModelxv_sig = {2470, "glLightModelxv", 2, _glLightModelxv_args};
 
 static const char * _glLightx_args[3] = {"light", "pname", "param"};
-static const trace::FunctionSig _glLightx_sig = {2470, "glLightx", 3, _glLightx_args};
+static const trace::FunctionSig _glLightx_sig = {2471, "glLightx", 3, _glLightx_args};
 
 static const char * _glLightxv_args[3] = {"light", "pname", "params"};
-static const trace::FunctionSig _glLightxv_sig = {2471, "glLightxv", 3, _glLightxv_args};
+static const trace::FunctionSig _glLightxv_sig = {2472, "glLightxv", 3, _glLightxv_args};
 
 static const char * _glLineWidthx_args[1] = {"width"};
-static const trace::FunctionSig _glLineWidthx_sig = {2472, "glLineWidthx", 1, _glLineWidthx_args};
+static const trace::FunctionSig _glLineWidthx_sig = {2473, "glLineWidthx", 1, _glLineWidthx_args};
 
 static const char * _glLoadMatrixx_args[1] = {"m"};
-static const trace::FunctionSig _glLoadMatrixx_sig = {2473, "glLoadMatrixx", 1, _glLoadMatrixx_args};
+static const trace::FunctionSig _glLoadMatrixx_sig = {2474, "glLoadMatrixx", 1, _glLoadMatrixx_args};
 
 static const char * _glMaterialx_args[3] = {"face", "pname", "param"};
-static const trace::FunctionSig _glMaterialx_sig = {2474, "glMaterialx", 3, _glMaterialx_args};
+static const trace::FunctionSig _glMaterialx_sig = {2475, "glMaterialx", 3, _glMaterialx_args};
 
 static const char * _glMaterialxv_args[3] = {"face", "pname", "params"};
-static const trace::FunctionSig _glMaterialxv_sig = {2475, "glMaterialxv", 3, _glMaterialxv_args};
+static const trace::FunctionSig _glMaterialxv_sig = {2476, "glMaterialxv", 3, _glMaterialxv_args};
 
 static const char * _glMultMatrixx_args[1] = {"m"};
-static const trace::FunctionSig _glMultMatrixx_sig = {2476, "glMultMatrixx", 1, _glMultMatrixx_args};
+static const trace::FunctionSig _glMultMatrixx_sig = {2477, "glMultMatrixx", 1, _glMultMatrixx_args};
 
 static const char * _glMultiTexCoord4x_args[5] = {"target", "s", "t", "r", "q"};
-static const trace::FunctionSig _glMultiTexCoord4x_sig = {2477, "glMultiTexCoord4x", 5, _glMultiTexCoord4x_args};
+static const trace::FunctionSig _glMultiTexCoord4x_sig = {2478, "glMultiTexCoord4x", 5, _glMultiTexCoord4x_args};
 
 static const char * _glNormal3x_args[3] = {"nx", "ny", "nz"};
-static const trace::FunctionSig _glNormal3x_sig = {2478, "glNormal3x", 3, _glNormal3x_args};
+static const trace::FunctionSig _glNormal3x_sig = {2479, "glNormal3x", 3, _glNormal3x_args};
 
 static const char * _glOrthox_args[6] = {"left", "right", "bottom", "top", "zNear", "zFar"};
-static const trace::FunctionSig _glOrthox_sig = {2479, "glOrthox", 6, _glOrthox_args};
+static const trace::FunctionSig _glOrthox_sig = {2480, "glOrthox", 6, _glOrthox_args};
 
 static const char * _glPointSizex_args[1] = {"size"};
-static const trace::FunctionSig _glPointSizex_sig = {2480, "glPointSizex", 1, _glPointSizex_args};
+static const trace::FunctionSig _glPointSizex_sig = {2481, "glPointSizex", 1, _glPointSizex_args};
 
 static const char * _glPolygonOffsetx_args[2] = {"factor", "units"};
-static const trace::FunctionSig _glPolygonOffsetx_sig = {2481, "glPolygonOffsetx", 2, _glPolygonOffsetx_args};
+static const trace::FunctionSig _glPolygonOffsetx_sig = {2482, "glPolygonOffsetx", 2, _glPolygonOffsetx_args};
 
 static const char * _glRotatex_args[4] = {"angle", "x", "y", "z"};
-static const trace::FunctionSig _glRotatex_sig = {2482, "glRotatex", 4, _glRotatex_args};
+static const trace::FunctionSig _glRotatex_sig = {2483, "glRotatex", 4, _glRotatex_args};
 
 static const char * _glSampleCoveragex_args[2] = {"value", "invert"};
-static const trace::FunctionSig _glSampleCoveragex_sig = {2483, "glSampleCoveragex", 2, _glSampleCoveragex_args};
+static const trace::FunctionSig _glSampleCoveragex_sig = {2484, "glSampleCoveragex", 2, _glSampleCoveragex_args};
 
 static const char * _glScalex_args[3] = {"x", "y", "z"};
-static const trace::FunctionSig _glScalex_sig = {2484, "glScalex", 3, _glScalex_args};
+static const trace::FunctionSig _glScalex_sig = {2485, "glScalex", 3, _glScalex_args};
 
 static const char * _glTexEnvx_args[3] = {"target", "pname", "param"};
-static const trace::FunctionSig _glTexEnvx_sig = {2485, "glTexEnvx", 3, _glTexEnvx_args};
+static const trace::FunctionSig _glTexEnvx_sig = {2486, "glTexEnvx", 3, _glTexEnvx_args};
 
 static const char * _glTexEnvxv_args[3] = {"target", "pname", "params"};
-static const trace::FunctionSig _glTexEnvxv_sig = {2486, "glTexEnvxv", 3, _glTexEnvxv_args};
+static const trace::FunctionSig _glTexEnvxv_sig = {2487, "glTexEnvxv", 3, _glTexEnvxv_args};
 
 static const char * _glTexParameterx_args[3] = {"target", "pname", "param"};
-static const trace::FunctionSig _glTexParameterx_sig = {2487, "glTexParameterx", 3, _glTexParameterx_args};
+static const trace::FunctionSig _glTexParameterx_sig = {2488, "glTexParameterx", 3, _glTexParameterx_args};
 
 static const char * _glTranslatex_args[3] = {"x", "y", "z"};
-static const trace::FunctionSig _glTranslatex_sig = {2488, "glTranslatex", 3, _glTranslatex_args};
+static const trace::FunctionSig _glTranslatex_sig = {2489, "glTranslatex", 3, _glTranslatex_args};
 
 static const char * _glClipPlanex_args[2] = {"plane", "equation"};
-static const trace::FunctionSig _glClipPlanex_sig = {2489, "glClipPlanex", 2, _glClipPlanex_args};
+static const trace::FunctionSig _glClipPlanex_sig = {2490, "glClipPlanex", 2, _glClipPlanex_args};
 
 static const char * _glGetClipPlanex_args[2] = {"plane", "equation"};
-static const trace::FunctionSig _glGetClipPlanex_sig = {2490, "glGetClipPlanex", 2, _glGetClipPlanex_args};
+static const trace::FunctionSig _glGetClipPlanex_sig = {2491, "glGetClipPlanex", 2, _glGetClipPlanex_args};
 
 static const char * _glGetFixedv_args[2] = {"pname", "params"};
-static const trace::FunctionSig _glGetFixedv_sig = {2491, "glGetFixedv", 2, _glGetFixedv_args};
+static const trace::FunctionSig _glGetFixedv_sig = {2492, "glGetFixedv", 2, _glGetFixedv_args};
 
 static const char * _glGetLightxv_args[3] = {"light", "pname", "params"};
-static const trace::FunctionSig _glGetLightxv_sig = {2492, "glGetLightxv", 3, _glGetLightxv_args};
+static const trace::FunctionSig _glGetLightxv_sig = {2493, "glGetLightxv", 3, _glGetLightxv_args};
 
 static const char * _glGetMaterialxv_args[3] = {"face", "pname", "params"};
-static const trace::FunctionSig _glGetMaterialxv_sig = {2493, "glGetMaterialxv", 3, _glGetMaterialxv_args};
+static const trace::FunctionSig _glGetMaterialxv_sig = {2494, "glGetMaterialxv", 3, _glGetMaterialxv_args};
 
 static const char * _glGetTexEnvxv_args[3] = {"target", "pname", "params"};
-static const trace::FunctionSig _glGetTexEnvxv_sig = {2494, "glGetTexEnvxv", 3, _glGetTexEnvxv_args};
+static const trace::FunctionSig _glGetTexEnvxv_sig = {2495, "glGetTexEnvxv", 3, _glGetTexEnvxv_args};
 
 static const char * _glGetTexParameterxv_args[3] = {"target", "pname", "params"};
-static const trace::FunctionSig _glGetTexParameterxv_sig = {2495, "glGetTexParameterxv", 3, _glGetTexParameterxv_args};
+static const trace::FunctionSig _glGetTexParameterxv_sig = {2496, "glGetTexParameterxv", 3, _glGetTexParameterxv_args};
 
 static const char * _glPointParameterx_args[2] = {"pname", "param"};
-static const trace::FunctionSig _glPointParameterx_sig = {2496, "glPointParameterx", 2, _glPointParameterx_args};
+static const trace::FunctionSig _glPointParameterx_sig = {2497, "glPointParameterx", 2, _glPointParameterx_args};
 
 static const char * _glPointParameterxv_args[2] = {"pname", "params"};
-static const trace::FunctionSig _glPointParameterxv_sig = {2497, "glPointParameterxv", 2, _glPointParameterxv_args};
+static const trace::FunctionSig _glPointParameterxv_sig = {2498, "glPointParameterxv", 2, _glPointParameterxv_args};
 
 static const char * _glTexParameterxv_args[3] = {"target", "pname", "params"};
-static const trace::FunctionSig _glTexParameterxv_sig = {2498, "glTexParameterxv", 3, _glTexParameterxv_args};
+static const trace::FunctionSig _glTexParameterxv_sig = {2499, "glTexParameterxv", 3, _glTexParameterxv_args};
 
 static const char * _glBlendEquationSeparateOES_args[2] = {"modeRGB", "modeAlpha"};
-static const trace::FunctionSig _glBlendEquationSeparateOES_sig = {2499, "glBlendEquationSeparateOES", 2, _glBlendEquationSeparateOES_args};
+static const trace::FunctionSig _glBlendEquationSeparateOES_sig = {2500, "glBlendEquationSeparateOES", 2, _glBlendEquationSeparateOES_args};
 
 static const char * _glBlendFuncSeparateOES_args[4] = {"sfactorRGB", "dfactorRGB", "sfactorAlpha", "dfactorAlpha"};
-static const trace::FunctionSig _glBlendFuncSeparateOES_sig = {2500, "glBlendFuncSeparateOES", 4, _glBlendFuncSeparateOES_args};
+static const trace::FunctionSig _glBlendFuncSeparateOES_sig = {2501, "glBlendFuncSeparateOES", 4, _glBlendFuncSeparateOES_args};
 
 static const char * _glBlendEquationOES_args[1] = {"mode"};
-static const trace::FunctionSig _glBlendEquationOES_sig = {2501, "glBlendEquationOES", 1, _glBlendEquationOES_args};
+static const trace::FunctionSig _glBlendEquationOES_sig = {2502, "glBlendEquationOES", 1, _glBlendEquationOES_args};
 
 static const char * _glIsRenderbufferOES_args[1] = {"renderbuffer"};
-static const trace::FunctionSig _glIsRenderbufferOES_sig = {2502, "glIsRenderbufferOES", 1, _glIsRenderbufferOES_args};
+static const trace::FunctionSig _glIsRenderbufferOES_sig = {2503, "glIsRenderbufferOES", 1, _glIsRenderbufferOES_args};
 
 static const char * _glBindRenderbufferOES_args[2] = {"target", "renderbuffer"};
-static const trace::FunctionSig _glBindRenderbufferOES_sig = {2503, "glBindRenderbufferOES", 2, _glBindRenderbufferOES_args};
+static const trace::FunctionSig _glBindRenderbufferOES_sig = {2504, "glBindRenderbufferOES", 2, _glBindRenderbufferOES_args};
 
 static const char * _glDeleteRenderbuffersOES_args[2] = {"n", "renderbuffers"};
-static const trace::FunctionSig _glDeleteRenderbuffersOES_sig = {2504, "glDeleteRenderbuffersOES", 2, _glDeleteRenderbuffersOES_args};
+static const trace::FunctionSig _glDeleteRenderbuffersOES_sig = {2505, "glDeleteRenderbuffersOES", 2, _glDeleteRenderbuffersOES_args};
 
 static const char * _glGenRenderbuffersOES_args[2] = {"n", "renderbuffers"};
-static const trace::FunctionSig _glGenRenderbuffersOES_sig = {2505, "glGenRenderbuffersOES", 2, _glGenRenderbuffersOES_args};
+static const trace::FunctionSig _glGenRenderbuffersOES_sig = {2506, "glGenRenderbuffersOES", 2, _glGenRenderbuffersOES_args};
 
 static const char * _glRenderbufferStorageOES_args[4] = {"target", "internalformat", "width", "height"};
-static const trace::FunctionSig _glRenderbufferStorageOES_sig = {2506, "glRenderbufferStorageOES", 4, _glRenderbufferStorageOES_args};
+static const trace::FunctionSig _glRenderbufferStorageOES_sig = {2507, "glRenderbufferStorageOES", 4, _glRenderbufferStorageOES_args};
 
 static const char * _glGetRenderbufferParameterivOES_args[3] = {"target", "pname", "params"};
-static const trace::FunctionSig _glGetRenderbufferParameterivOES_sig = {2507, "glGetRenderbufferParameterivOES", 3, _glGetRenderbufferParameterivOES_args};
+static const trace::FunctionSig _glGetRenderbufferParameterivOES_sig = {2508, "glGetRenderbufferParameterivOES", 3, _glGetRenderbufferParameterivOES_args};
 
 static const char * _glIsFramebufferOES_args[1] = {"framebuffer"};
-static const trace::FunctionSig _glIsFramebufferOES_sig = {2508, "glIsFramebufferOES", 1, _glIsFramebufferOES_args};
+static const trace::FunctionSig _glIsFramebufferOES_sig = {2509, "glIsFramebufferOES", 1, _glIsFramebufferOES_args};
 
 static const char * _glBindFramebufferOES_args[2] = {"target", "framebuffer"};
-static const trace::FunctionSig _glBindFramebufferOES_sig = {2509, "glBindFramebufferOES", 2, _glBindFramebufferOES_args};
+static const trace::FunctionSig _glBindFramebufferOES_sig = {2510, "glBindFramebufferOES", 2, _glBindFramebufferOES_args};
 
 static const char * _glDeleteFramebuffersOES_args[2] = {"n", "framebuffers"};
-static const trace::FunctionSig _glDeleteFramebuffersOES_sig = {2510, "glDeleteFramebuffersOES", 2, _glDeleteFramebuffersOES_args};
+static const trace::FunctionSig _glDeleteFramebuffersOES_sig = {2511, "glDeleteFramebuffersOES", 2, _glDeleteFramebuffersOES_args};
 
 static const char * _glGenFramebuffersOES_args[2] = {"n", "framebuffers"};
-static const trace::FunctionSig _glGenFramebuffersOES_sig = {2511, "glGenFramebuffersOES", 2, _glGenFramebuffersOES_args};
+static const trace::FunctionSig _glGenFramebuffersOES_sig = {2512, "glGenFramebuffersOES", 2, _glGenFramebuffersOES_args};
 
 static const char * _glCheckFramebufferStatusOES_args[1] = {"target"};
-static const trace::FunctionSig _glCheckFramebufferStatusOES_sig = {2512, "glCheckFramebufferStatusOES", 1, _glCheckFramebufferStatusOES_args};
+static const trace::FunctionSig _glCheckFramebufferStatusOES_sig = {2513, "glCheckFramebufferStatusOES", 1, _glCheckFramebufferStatusOES_args};
 
 static const char * _glFramebufferTexture2DOES_args[5] = {"target", "attachment", "textarget", "texture", "level"};
-static const trace::FunctionSig _glFramebufferTexture2DOES_sig = {2513, "glFramebufferTexture2DOES", 5, _glFramebufferTexture2DOES_args};
+static const trace::FunctionSig _glFramebufferTexture2DOES_sig = {2514, "glFramebufferTexture2DOES", 5, _glFramebufferTexture2DOES_args};
 
 static const char * _glFramebufferRenderbufferOES_args[4] = {"target", "attachment", "renderbuffertarget", "renderbuffer"};
-static const trace::FunctionSig _glFramebufferRenderbufferOES_sig = {2514, "glFramebufferRenderbufferOES", 4, _glFramebufferRenderbufferOES_args};
+static const trace::FunctionSig _glFramebufferRenderbufferOES_sig = {2515, "glFramebufferRenderbufferOES", 4, _glFramebufferRenderbufferOES_args};
 
 static const char * _glGetFramebufferAttachmentParameterivOES_args[4] = {"target", "attachment", "pname", "params"};
-static const trace::FunctionSig _glGetFramebufferAttachmentParameterivOES_sig = {2515, "glGetFramebufferAttachmentParameterivOES", 4, _glGetFramebufferAttachmentParameterivOES_args};
+static const trace::FunctionSig _glGetFramebufferAttachmentParameterivOES_sig = {2516, "glGetFramebufferAttachmentParameterivOES", 4, _glGetFramebufferAttachmentParameterivOES_args};
 
 static const char * _glGenerateMipmapOES_args[1] = {"target"};
-static const trace::FunctionSig _glGenerateMipmapOES_sig = {2516, "glGenerateMipmapOES", 1, _glGenerateMipmapOES_args};
+static const trace::FunctionSig _glGenerateMipmapOES_sig = {2517, "glGenerateMipmapOES", 1, _glGenerateMipmapOES_args};
 
 static const char * _glCurrentPaletteMatrixOES_args[1] = {"index"};
-static const trace::FunctionSig _glCurrentPaletteMatrixOES_sig = {2517, "glCurrentPaletteMatrixOES", 1, _glCurrentPaletteMatrixOES_args};
+static const trace::FunctionSig _glCurrentPaletteMatrixOES_sig = {2518, "glCurrentPaletteMatrixOES", 1, _glCurrentPaletteMatrixOES_args};
 
 static const char ** _glLoadPaletteFromModelViewMatrixOES_args = NULL;
-static const trace::FunctionSig _glLoadPaletteFromModelViewMatrixOES_sig = {2518, "glLoadPaletteFromModelViewMatrixOES", 0, _glLoadPaletteFromModelViewMatrixOES_args};
+static const trace::FunctionSig _glLoadPaletteFromModelViewMatrixOES_sig = {2519, "glLoadPaletteFromModelViewMatrixOES", 0, _glLoadPaletteFromModelViewMatrixOES_args};
 
 static const char * _glMatrixIndexPointerOES_args[4] = {"size", "type", "stride", "pointer"};
-static const trace::FunctionSig _glMatrixIndexPointerOES_sig = {2519, "glMatrixIndexPointerOES", 4, _glMatrixIndexPointerOES_args};
+static const trace::FunctionSig _glMatrixIndexPointerOES_sig = {2520, "glMatrixIndexPointerOES", 4, _glMatrixIndexPointerOES_args};
 
 static const char * _glWeightPointerOES_args[4] = {"size", "type", "stride", "pointer"};
-static const trace::FunctionSig _glWeightPointerOES_sig = {2520, "glWeightPointerOES", 4, _glWeightPointerOES_args};
+static const trace::FunctionSig _glWeightPointerOES_sig = {2521, "glWeightPointerOES", 4, _glWeightPointerOES_args};
 
 static const char * _glPointSizePointerOES_args[3] = {"type", "stride", "ptr"};
-static const trace::FunctionSig _glPointSizePointerOES_sig = {2521, "glPointSizePointerOES", 3, _glPointSizePointerOES_args};
+static const trace::FunctionSig _glPointSizePointerOES_sig = {2522, "glPointSizePointerOES", 3, _glPointSizePointerOES_args};
 
 static const char * _glQueryMatrixxOES_args[2] = {"mantissa", "exponent"};
-static const trace::FunctionSig _glQueryMatrixxOES_sig = {2522, "glQueryMatrixxOES", 2, _glQueryMatrixxOES_args};
+static const trace::FunctionSig _glQueryMatrixxOES_sig = {2523, "glQueryMatrixxOES", 2, _glQueryMatrixxOES_args};
 
 static const char * _glTexGenfOES_args[3] = {"coord", "pname", "param"};
-static const trace::FunctionSig _glTexGenfOES_sig = {2523, "glTexGenfOES", 3, _glTexGenfOES_args};
+static const trace::FunctionSig _glTexGenfOES_sig = {2524, "glTexGenfOES", 3, _glTexGenfOES_args};
 
 static const char * _glTexGenfvOES_args[3] = {"coord", "pname", "params"};
-static const trace::FunctionSig _glTexGenfvOES_sig = {2524, "glTexGenfvOES", 3, _glTexGenfvOES_args};
+static const trace::FunctionSig _glTexGenfvOES_sig = {2525, "glTexGenfvOES", 3, _glTexGenfvOES_args};
 
 static const char * _glTexGeniOES_args[3] = {"coord", "pname", "param"};
-static const trace::FunctionSig _glTexGeniOES_sig = {2525, "glTexGeniOES", 3, _glTexGeniOES_args};
+static const trace::FunctionSig _glTexGeniOES_sig = {2526, "glTexGeniOES", 3, _glTexGeniOES_args};
 
 static const char * _glTexGenivOES_args[3] = {"coord", "pname", "params"};
-static const trace::FunctionSig _glTexGenivOES_sig = {2526, "glTexGenivOES", 3, _glTexGenivOES_args};
+static const trace::FunctionSig _glTexGenivOES_sig = {2527, "glTexGenivOES", 3, _glTexGenivOES_args};
 
 static const char * _glTexGenxOES_args[3] = {"coord", "pname", "param"};
-static const trace::FunctionSig _glTexGenxOES_sig = {2527, "glTexGenxOES", 3, _glTexGenxOES_args};
+static const trace::FunctionSig _glTexGenxOES_sig = {2528, "glTexGenxOES", 3, _glTexGenxOES_args};
 
 static const char * _glTexGenxvOES_args[3] = {"coord", "pname", "params"};
-static const trace::FunctionSig _glTexGenxvOES_sig = {2528, "glTexGenxvOES", 3, _glTexGenxvOES_args};
+static const trace::FunctionSig _glTexGenxvOES_sig = {2529, "glTexGenxvOES", 3, _glTexGenxvOES_args};
 
 static const char * _glGetTexGenfvOES_args[3] = {"coord", "pname", "params"};
-static const trace::FunctionSig _glGetTexGenfvOES_sig = {2529, "glGetTexGenfvOES", 3, _glGetTexGenfvOES_args};
+static const trace::FunctionSig _glGetTexGenfvOES_sig = {2530, "glGetTexGenfvOES", 3, _glGetTexGenfvOES_args};
 
 static const char * _glGetTexGenivOES_args[3] = {"coord", "pname", "params"};
-static const trace::FunctionSig _glGetTexGenivOES_sig = {2530, "glGetTexGenivOES", 3, _glGetTexGenivOES_args};
+static const trace::FunctionSig _glGetTexGenivOES_sig = {2531, "glGetTexGenivOES", 3, _glGetTexGenivOES_args};
 
 static const char * _glGetTexGenxvOES_args[3] = {"coord", "pname", "params"};
-static const trace::FunctionSig _glGetTexGenxvOES_sig = {2531, "glGetTexGenxvOES", 3, _glGetTexGenxvOES_args};
+static const trace::FunctionSig _glGetTexGenxvOES_sig = {2532, "glGetTexGenxvOES", 3, _glGetTexGenxvOES_args};
 
 static const char * _glGetBufferPointervOES_args[3] = {"target", "pname", "params"};
-static const trace::FunctionSig _glGetBufferPointervOES_sig = {2532, "glGetBufferPointervOES", 3, _glGetBufferPointervOES_args};
+static const trace::FunctionSig _glGetBufferPointervOES_sig = {2533, "glGetBufferPointervOES", 3, _glGetBufferPointervOES_args};
 
 static const char * _glMapBufferOES_args[2] = {"target", "access"};
-static const trace::FunctionSig _glMapBufferOES_sig = {2533, "glMapBufferOES", 2, _glMapBufferOES_args};
+static const trace::FunctionSig _glMapBufferOES_sig = {2534, "glMapBufferOES", 2, _glMapBufferOES_args};
 
 static const char * _glUnmapBufferOES_args[1] = {"target"};
-static const trace::FunctionSig _glUnmapBufferOES_sig = {2534, "glUnmapBufferOES", 1, _glUnmapBufferOES_args};
+static const trace::FunctionSig _glUnmapBufferOES_sig = {2535, "glUnmapBufferOES", 1, _glUnmapBufferOES_args};
 
 static const char * _glTexImage3DOES_args[10] = {"target", "level", "internalformat", "width", "height", "depth", "border", "format", "type", "pixels"};
-static const trace::FunctionSig _glTexImage3DOES_sig = {2535, "glTexImage3DOES", 10, _glTexImage3DOES_args};
+static const trace::FunctionSig _glTexImage3DOES_sig = {2536, "glTexImage3DOES", 10, _glTexImage3DOES_args};
 
 static const char * _glTexSubImage3DOES_args[11] = {"target", "level", "xoffset", "yoffset", "zoffset", "width", "height", "depth", "format", "type", "pixels"};
-static const trace::FunctionSig _glTexSubImage3DOES_sig = {2536, "glTexSubImage3DOES", 11, _glTexSubImage3DOES_args};
+static const trace::FunctionSig _glTexSubImage3DOES_sig = {2537, "glTexSubImage3DOES", 11, _glTexSubImage3DOES_args};
 
 static const char * _glCopyTexSubImage3DOES_args[9] = {"target", "level", "xoffset", "yoffset", "zoffset", "x", "y", "width", "height"};
-static const trace::FunctionSig _glCopyTexSubImage3DOES_sig = {2537, "glCopyTexSubImage3DOES", 9, _glCopyTexSubImage3DOES_args};
+static const trace::FunctionSig _glCopyTexSubImage3DOES_sig = {2538, "glCopyTexSubImage3DOES", 9, _glCopyTexSubImage3DOES_args};
 
 static const char * _glCompressedTexImage3DOES_args[9] = {"target", "level", "internalformat", "width", "height", "depth", "border", "imageSize", "data"};
-static const trace::FunctionSig _glCompressedTexImage3DOES_sig = {2538, "glCompressedTexImage3DOES", 9, _glCompressedTexImage3DOES_args};
+static const trace::FunctionSig _glCompressedTexImage3DOES_sig = {2539, "glCompressedTexImage3DOES", 9, _glCompressedTexImage3DOES_args};
 
 static const char * _glCompressedTexSubImage3DOES_args[11] = {"target", "level", "xoffset", "yoffset", "zoffset", "width", "height", "depth", "format", "imageSize", "data"};
-static const trace::FunctionSig _glCompressedTexSubImage3DOES_sig = {2539, "glCompressedTexSubImage3DOES", 11, _glCompressedTexSubImage3DOES_args};
+static const trace::FunctionSig _glCompressedTexSubImage3DOES_sig = {2540, "glCompressedTexSubImage3DOES", 11, _glCompressedTexSubImage3DOES_args};
 
 static const char * _glFramebufferTexture3DOES_args[6] = {"target", "attachment", "textarget", "texture", "level", "zoffset"};
-static const trace::FunctionSig _glFramebufferTexture3DOES_sig = {2540, "glFramebufferTexture3DOES", 6, _glFramebufferTexture3DOES_args};
+static const trace::FunctionSig _glFramebufferTexture3DOES_sig = {2541, "glFramebufferTexture3DOES", 6, _glFramebufferTexture3DOES_args};
 
 static const char * _glGetProgramBinaryOES_args[5] = {"program", "bufSize", "length", "binaryFormat", "binary"};
-static const trace::FunctionSig _glGetProgramBinaryOES_sig = {2541, "glGetProgramBinaryOES", 5, _glGetProgramBinaryOES_args};
+static const trace::FunctionSig _glGetProgramBinaryOES_sig = {2542, "glGetProgramBinaryOES", 5, _glGetProgramBinaryOES_args};
 
 static const char * _glProgramBinaryOES_args[4] = {"program", "binaryFormat", "binary", "length"};
-static const trace::FunctionSig _glProgramBinaryOES_sig = {2542, "glProgramBinaryOES", 4, _glProgramBinaryOES_args};
+static const trace::FunctionSig _glProgramBinaryOES_sig = {2543, "glProgramBinaryOES", 4, _glProgramBinaryOES_args};
 
 static const char * _glDrawTexfOES_args[5] = {"x", "y", "z", "width", "height"};
-static const trace::FunctionSig _glDrawTexfOES_sig = {2543, "glDrawTexfOES", 5, _glDrawTexfOES_args};
+static const trace::FunctionSig _glDrawTexfOES_sig = {2544, "glDrawTexfOES", 5, _glDrawTexfOES_args};
 
 static const char * _glDrawTexfvOES_args[1] = {"coords"};
-static const trace::FunctionSig _glDrawTexfvOES_sig = {2544, "glDrawTexfvOES", 1, _glDrawTexfvOES_args};
+static const trace::FunctionSig _glDrawTexfvOES_sig = {2545, "glDrawTexfvOES", 1, _glDrawTexfvOES_args};
 
 static const char * _glDrawTexiOES_args[5] = {"x", "y", "z", "width", "height"};
-static const trace::FunctionSig _glDrawTexiOES_sig = {2545, "glDrawTexiOES", 5, _glDrawTexiOES_args};
+static const trace::FunctionSig _glDrawTexiOES_sig = {2546, "glDrawTexiOES", 5, _glDrawTexiOES_args};
 
 static const char * _glDrawTexivOES_args[1] = {"coords"};
-static const trace::FunctionSig _glDrawTexivOES_sig = {2546, "glDrawTexivOES", 1, _glDrawTexivOES_args};
+static const trace::FunctionSig _glDrawTexivOES_sig = {2547, "glDrawTexivOES", 1, _glDrawTexivOES_args};
 
 static const char * _glDrawTexsOES_args[5] = {"x", "y", "z", "width", "height"};
-static const trace::FunctionSig _glDrawTexsOES_sig = {2547, "glDrawTexsOES", 5, _glDrawTexsOES_args};
+static const trace::FunctionSig _glDrawTexsOES_sig = {2548, "glDrawTexsOES", 5, _glDrawTexsOES_args};
 
 static const char * _glDrawTexsvOES_args[1] = {"coords"};
-static const trace::FunctionSig _glDrawTexsvOES_sig = {2548, "glDrawTexsvOES", 1, _glDrawTexsvOES_args};
+static const trace::FunctionSig _glDrawTexsvOES_sig = {2549, "glDrawTexsvOES", 1, _glDrawTexsvOES_args};
 
 static const char * _glDiscardFramebufferEXT_args[3] = {"target", "numAttachments", "attachments"};
-static const trace::FunctionSig _glDiscardFramebufferEXT_sig = {2549, "glDiscardFramebufferEXT", 3, _glDiscardFramebufferEXT_args};
+static const trace::FunctionSig _glDiscardFramebufferEXT_sig = {2550, "glDiscardFramebufferEXT", 3, _glDiscardFramebufferEXT_args};
 
 static const char * _glBindVertexArrayOES_args[1] = {"array"};
-static const trace::FunctionSig _glBindVertexArrayOES_sig = {2550, "glBindVertexArrayOES", 1, _glBindVertexArrayOES_args};
+static const trace::FunctionSig _glBindVertexArrayOES_sig = {2551, "glBindVertexArrayOES", 1, _glBindVertexArrayOES_args};
 
 static const char * _glDeleteVertexArraysOES_args[2] = {"n", "arrays"};
-static const trace::FunctionSig _glDeleteVertexArraysOES_sig = {2551, "glDeleteVertexArraysOES", 2, _glDeleteVertexArraysOES_args};
+static const trace::FunctionSig _glDeleteVertexArraysOES_sig = {2552, "glDeleteVertexArraysOES", 2, _glDeleteVertexArraysOES_args};
 
 static const char * _glGenVertexArraysOES_args[2] = {"n", "arrays"};
-static const trace::FunctionSig _glGenVertexArraysOES_sig = {2552, "glGenVertexArraysOES", 2, _glGenVertexArraysOES_args};
+static const trace::FunctionSig _glGenVertexArraysOES_sig = {2553, "glGenVertexArraysOES", 2, _glGenVertexArraysOES_args};
 
 static const char * _glIsVertexArrayOES_args[1] = {"array"};
-static const trace::FunctionSig _glIsVertexArrayOES_sig = {2553, "glIsVertexArrayOES", 1, _glIsVertexArrayOES_args};
+static const trace::FunctionSig _glIsVertexArrayOES_sig = {2554, "glIsVertexArrayOES", 1, _glIsVertexArrayOES_args};
 
 static const char * _glCoverageMaskNV_args[1] = {"mask"};
-static const trace::FunctionSig _glCoverageMaskNV_sig = {2554, "glCoverageMaskNV", 1, _glCoverageMaskNV_args};
+static const trace::FunctionSig _glCoverageMaskNV_sig = {2555, "glCoverageMaskNV", 1, _glCoverageMaskNV_args};
 
 static const char * _glCoverageOperationNV_args[1] = {"operation"};
-static const trace::FunctionSig _glCoverageOperationNV_sig = {2555, "glCoverageOperationNV", 1, _glCoverageOperationNV_args};
+static const trace::FunctionSig _glCoverageOperationNV_sig = {2556, "glCoverageOperationNV", 1, _glCoverageOperationNV_args};
 
 static const char * _glRenderbufferStorageMultisampleIMG_args[5] = {"target", "samples", "internalformat", "width", "height"};
-static const trace::FunctionSig _glRenderbufferStorageMultisampleIMG_sig = {2556, "glRenderbufferStorageMultisampleIMG", 5, _glRenderbufferStorageMultisampleIMG_args};
+static const trace::FunctionSig _glRenderbufferStorageMultisampleIMG_sig = {2557, "glRenderbufferStorageMultisampleIMG", 5, _glRenderbufferStorageMultisampleIMG_args};
 
 static const char * _glFramebufferTexture2DMultisampleIMG_args[6] = {"target", "attachment", "textarget", "texture", "level", "samples"};
-static const trace::FunctionSig _glFramebufferTexture2DMultisampleIMG_sig = {2557, "glFramebufferTexture2DMultisampleIMG", 6, _glFramebufferTexture2DMultisampleIMG_args};
+static const trace::FunctionSig _glFramebufferTexture2DMultisampleIMG_sig = {2558, "glFramebufferTexture2DMultisampleIMG", 6, _glFramebufferTexture2DMultisampleIMG_args};
 
 static const char * _glRenderbufferStorageMultisampleAPPLE_args[5] = {"target", "samples", "internalformat", "width", "height"};
-static const trace::FunctionSig _glRenderbufferStorageMultisampleAPPLE_sig = {2558, "glRenderbufferStorageMultisampleAPPLE", 5, _glRenderbufferStorageMultisampleAPPLE_args};
+static const trace::FunctionSig _glRenderbufferStorageMultisampleAPPLE_sig = {2559, "glRenderbufferStorageMultisampleAPPLE", 5, _glRenderbufferStorageMultisampleAPPLE_args};
 
 static const char ** _glResolveMultisampleFramebufferAPPLE_args = NULL;
-static const trace::FunctionSig _glResolveMultisampleFramebufferAPPLE_sig = {2559, "glResolveMultisampleFramebufferAPPLE", 0, _glResolveMultisampleFramebufferAPPLE_args};
+static const trace::FunctionSig _glResolveMultisampleFramebufferAPPLE_sig = {2560, "glResolveMultisampleFramebufferAPPLE", 0, _glResolveMultisampleFramebufferAPPLE_args};
 
 static const char * _glBlitFramebufferANGLE_args[10] = {"srcX0", "srcY0", "srcX1", "srcY1", "dstX0", "dstY0", "dstX1", "dstY1", "mask", "filter"};
-static const trace::FunctionSig _glBlitFramebufferANGLE_sig = {2560, "glBlitFramebufferANGLE", 10, _glBlitFramebufferANGLE_args};
+static const trace::FunctionSig _glBlitFramebufferANGLE_sig = {2561, "glBlitFramebufferANGLE", 10, _glBlitFramebufferANGLE_args};
 
 static const char * _glRenderbufferStorageMultisampleANGLE_args[5] = {"target", "samples", "internalformat", "width", "height"};
-static const trace::FunctionSig _glRenderbufferStorageMultisampleANGLE_sig = {2561, "glRenderbufferStorageMultisampleANGLE", 5, _glRenderbufferStorageMultisampleANGLE_args};
+static const trace::FunctionSig _glRenderbufferStorageMultisampleANGLE_sig = {2562, "glRenderbufferStorageMultisampleANGLE", 5, _glRenderbufferStorageMultisampleANGLE_args};
 
 static const char * _glDrawBuffersNV_args[2] = {"n", "bufs"};
-static const trace::FunctionSig _glDrawBuffersNV_sig = {2562, "glDrawBuffersNV", 2, _glDrawBuffersNV_args};
+static const trace::FunctionSig _glDrawBuffersNV_sig = {2563, "glDrawBuffersNV", 2, _glDrawBuffersNV_args};
 
 static const char * _glReadBufferNV_args[1] = {"mode"};
-static const trace::FunctionSig _glReadBufferNV_sig = {2563, "glReadBufferNV", 1, _glReadBufferNV_args};
+static const trace::FunctionSig _glReadBufferNV_sig = {2564, "glReadBufferNV", 1, _glReadBufferNV_args};
 
 static const char * _glLabelObjectEXT_args[4] = {"type", "object", "length", "label"};
-static const trace::FunctionSig _glLabelObjectEXT_sig = {2564, "glLabelObjectEXT", 4, _glLabelObjectEXT_args};
+static const trace::FunctionSig _glLabelObjectEXT_sig = {2565, "glLabelObjectEXT", 4, _glLabelObjectEXT_args};
 
 static const char * _glGetObjectLabelEXT_args[5] = {"type", "object", "bufSize", "length", "label"};
-static const trace::FunctionSig _glGetObjectLabelEXT_sig = {2565, "glGetObjectLabelEXT", 5, _glGetObjectLabelEXT_args};
+static const trace::FunctionSig _glGetObjectLabelEXT_sig = {2566, "glGetObjectLabelEXT", 5, _glGetObjectLabelEXT_args};
 
 static const char * _glInsertEventMarkerEXT_args[2] = {"length", "marker"};
-static const trace::FunctionSig _glInsertEventMarkerEXT_sig = {2566, "glInsertEventMarkerEXT", 2, _glInsertEventMarkerEXT_args};
+static const trace::FunctionSig _glInsertEventMarkerEXT_sig = {2567, "glInsertEventMarkerEXT", 2, _glInsertEventMarkerEXT_args};
 
 static const char * _glPushGroupMarkerEXT_args[2] = {"length", "marker"};
-static const trace::FunctionSig _glPushGroupMarkerEXT_sig = {2567, "glPushGroupMarkerEXT", 2, _glPushGroupMarkerEXT_args};
+static const trace::FunctionSig _glPushGroupMarkerEXT_sig = {2568, "glPushGroupMarkerEXT", 2, _glPushGroupMarkerEXT_args};
 
 static const char ** _glPopGroupMarkerEXT_args = NULL;
-static const trace::FunctionSig _glPopGroupMarkerEXT_sig = {2568, "glPopGroupMarkerEXT", 0, _glPopGroupMarkerEXT_args};
+static const trace::FunctionSig _glPopGroupMarkerEXT_sig = {2569, "glPopGroupMarkerEXT", 0, _glPopGroupMarkerEXT_args};
 
 static const char * _glGenQueriesEXT_args[2] = {"n", "ids"};
-static const trace::FunctionSig _glGenQueriesEXT_sig = {2569, "glGenQueriesEXT", 2, _glGenQueriesEXT_args};
+static const trace::FunctionSig _glGenQueriesEXT_sig = {2570, "glGenQueriesEXT", 2, _glGenQueriesEXT_args};
 
 static const char * _glDeleteQueriesEXT_args[2] = {"n", "ids"};
-static const trace::FunctionSig _glDeleteQueriesEXT_sig = {2570, "glDeleteQueriesEXT", 2, _glDeleteQueriesEXT_args};
+static const trace::FunctionSig _glDeleteQueriesEXT_sig = {2571, "glDeleteQueriesEXT", 2, _glDeleteQueriesEXT_args};
 
 static const char * _glIsQueryEXT_args[1] = {"id"};
-static const trace::FunctionSig _glIsQueryEXT_sig = {2571, "glIsQueryEXT", 1, _glIsQueryEXT_args};
+static const trace::FunctionSig _glIsQueryEXT_sig = {2572, "glIsQueryEXT", 1, _glIsQueryEXT_args};
 
 static const char * _glBeginQueryEXT_args[2] = {"target", "id"};
-static const trace::FunctionSig _glBeginQueryEXT_sig = {2572, "glBeginQueryEXT", 2, _glBeginQueryEXT_args};
+static const trace::FunctionSig _glBeginQueryEXT_sig = {2573, "glBeginQueryEXT", 2, _glBeginQueryEXT_args};
 
 static const char * _glEndQueryEXT_args[1] = {"target"};
-static const trace::FunctionSig _glEndQueryEXT_sig = {2573, "glEndQueryEXT", 1, _glEndQueryEXT_args};
+static const trace::FunctionSig _glEndQueryEXT_sig = {2574, "glEndQueryEXT", 1, _glEndQueryEXT_args};
 
 static const char * _glGetQueryivEXT_args[3] = {"target", "pname", "params"};
-static const trace::FunctionSig _glGetQueryivEXT_sig = {2574, "glGetQueryivEXT", 3, _glGetQueryivEXT_args};
+static const trace::FunctionSig _glGetQueryivEXT_sig = {2575, "glGetQueryivEXT", 3, _glGetQueryivEXT_args};
 
 static const char * _glGetQueryObjectuivEXT_args[3] = {"id", "pname", "params"};
-static const trace::FunctionSig _glGetQueryObjectuivEXT_sig = {2575, "glGetQueryObjectuivEXT", 3, _glGetQueryObjectuivEXT_args};
+static const trace::FunctionSig _glGetQueryObjectuivEXT_sig = {2576, "glGetQueryObjectuivEXT", 3, _glGetQueryObjectuivEXT_args};
 
 static const char * _glUseProgramStagesEXT_args[3] = {"pipeline", "stages", "program"};
-static const trace::FunctionSig _glUseProgramStagesEXT_sig = {2576, "glUseProgramStagesEXT", 3, _glUseProgramStagesEXT_args};
+static const trace::FunctionSig _glUseProgramStagesEXT_sig = {2577, "glUseProgramStagesEXT", 3, _glUseProgramStagesEXT_args};
 
 static const char * _glActiveShaderProgramEXT_args[2] = {"pipeline", "program"};
-static const trace::FunctionSig _glActiveShaderProgramEXT_sig = {2577, "glActiveShaderProgramEXT", 2, _glActiveShaderProgramEXT_args};
+static const trace::FunctionSig _glActiveShaderProgramEXT_sig = {2578, "glActiveShaderProgramEXT", 2, _glActiveShaderProgramEXT_args};
 
 static const char * _glCreateShaderProgramvEXT_args[3] = {"type", "count", "strings"};
-static const trace::FunctionSig _glCreateShaderProgramvEXT_sig = {2578, "glCreateShaderProgramvEXT", 3, _glCreateShaderProgramvEXT_args};
+static const trace::FunctionSig _glCreateShaderProgramvEXT_sig = {2579, "glCreateShaderProgramvEXT", 3, _glCreateShaderProgramvEXT_args};
 
 static const char * _glBindProgramPipelineEXT_args[1] = {"pipeline"};
-static const trace::FunctionSig _glBindProgramPipelineEXT_sig = {2579, "glBindProgramPipelineEXT", 1, _glBindProgramPipelineEXT_args};
+static const trace::FunctionSig _glBindProgramPipelineEXT_sig = {2580, "glBindProgramPipelineEXT", 1, _glBindProgramPipelineEXT_args};
 
 static const char * _glDeleteProgramPipelinesEXT_args[2] = {"n", "pipelines"};
-static const trace::FunctionSig _glDeleteProgramPipelinesEXT_sig = {2580, "glDeleteProgramPipelinesEXT", 2, _glDeleteProgramPipelinesEXT_args};
+static const trace::FunctionSig _glDeleteProgramPipelinesEXT_sig = {2581, "glDeleteProgramPipelinesEXT", 2, _glDeleteProgramPipelinesEXT_args};
 
 static const char * _glGenProgramPipelinesEXT_args[2] = {"n", "pipelines"};
-static const trace::FunctionSig _glGenProgramPipelinesEXT_sig = {2581, "glGenProgramPipelinesEXT", 2, _glGenProgramPipelinesEXT_args};
+static const trace::FunctionSig _glGenProgramPipelinesEXT_sig = {2582, "glGenProgramPipelinesEXT", 2, _glGenProgramPipelinesEXT_args};
 
 static const char * _glIsProgramPipelineEXT_args[1] = {"pipeline"};
-static const trace::FunctionSig _glIsProgramPipelineEXT_sig = {2582, "glIsProgramPipelineEXT", 1, _glIsProgramPipelineEXT_args};
+static const trace::FunctionSig _glIsProgramPipelineEXT_sig = {2583, "glIsProgramPipelineEXT", 1, _glIsProgramPipelineEXT_args};
 
 static const char * _glGetProgramPipelineivEXT_args[3] = {"pipeline", "pname", "params"};
-static const trace::FunctionSig _glGetProgramPipelineivEXT_sig = {2583, "glGetProgramPipelineivEXT", 3, _glGetProgramPipelineivEXT_args};
+static const trace::FunctionSig _glGetProgramPipelineivEXT_sig = {2584, "glGetProgramPipelineivEXT", 3, _glGetProgramPipelineivEXT_args};
 
 static const char * _glValidateProgramPipelineEXT_args[1] = {"pipeline"};
-static const trace::FunctionSig _glValidateProgramPipelineEXT_sig = {2584, "glValidateProgramPipelineEXT", 1, _glValidateProgramPipelineEXT_args};
+static const trace::FunctionSig _glValidateProgramPipelineEXT_sig = {2585, "glValidateProgramPipelineEXT", 1, _glValidateProgramPipelineEXT_args};
 
 static const char * _glGetProgramPipelineInfoLogEXT_args[4] = {"pipeline", "bufSize", "length", "infoLog"};
-static const trace::FunctionSig _glGetProgramPipelineInfoLogEXT_sig = {2585, "glGetProgramPipelineInfoLogEXT", 4, _glGetProgramPipelineInfoLogEXT_args};
+static const trace::FunctionSig _glGetProgramPipelineInfoLogEXT_sig = {2586, "glGetProgramPipelineInfoLogEXT", 4, _glGetProgramPipelineInfoLogEXT_args};
 
 static const char * _glFramebufferTexture2DMultisampleEXT_args[6] = {"target", "attachment", "textarget", "texture", "level", "samples"};
-static const trace::FunctionSig _glFramebufferTexture2DMultisampleEXT_sig = {2586, "glFramebufferTexture2DMultisampleEXT", 6, _glFramebufferTexture2DMultisampleEXT_args};
+static const trace::FunctionSig _glFramebufferTexture2DMultisampleEXT_sig = {2587, "glFramebufferTexture2DMultisampleEXT", 6, _glFramebufferTexture2DMultisampleEXT_args};
 
 static const char * _glTexStorage1DEXT_args[4] = {"target", "levels", "internalformat", "width"};
-static const trace::FunctionSig _glTexStorage1DEXT_sig = {2587, "glTexStorage1DEXT", 4, _glTexStorage1DEXT_args};
+static const trace::FunctionSig _glTexStorage1DEXT_sig = {2588, "glTexStorage1DEXT", 4, _glTexStorage1DEXT_args};
 
 static const char * _glTexStorage2DEXT_args[5] = {"target", "levels", "internalformat", "width", "height"};
-static const trace::FunctionSig _glTexStorage2DEXT_sig = {2588, "glTexStorage2DEXT", 5, _glTexStorage2DEXT_args};
+static const trace::FunctionSig _glTexStorage2DEXT_sig = {2589, "glTexStorage2DEXT", 5, _glTexStorage2DEXT_args};
 
 static const char * _glTexStorage3DEXT_args[6] = {"target", "levels", "internalformat", "width", "height", "depth"};
-static const trace::FunctionSig _glTexStorage3DEXT_sig = {2589, "glTexStorage3DEXT", 6, _glTexStorage3DEXT_args};
+static const trace::FunctionSig _glTexStorage3DEXT_sig = {2590, "glTexStorage3DEXT", 6, _glTexStorage3DEXT_args};
 
 
 #if REGAL_SYS_OSX
 static const char * _CGLSetCurrentContext_args[1] = {"ctx"};
-static const trace::FunctionSig _CGLSetCurrentContext_sig = {2590, "CGLSetCurrentContext", 1, _CGLSetCurrentContext_args};
+static const trace::FunctionSig _CGLSetCurrentContext_sig = {2591, "CGLSetCurrentContext", 1, _CGLSetCurrentContext_args};
 
 static const char ** _CGLGetCurrentContext_args = NULL;
-static const trace::FunctionSig _CGLGetCurrentContext_sig = {2591, "CGLGetCurrentContext", 0, _CGLGetCurrentContext_args};
+static const trace::FunctionSig _CGLGetCurrentContext_sig = {2592, "CGLGetCurrentContext", 0, _CGLGetCurrentContext_args};
 
 static const char * _CGLChoosePixelFormat_args[3] = {"attribs", "pix", "npix"};
-static const trace::FunctionSig _CGLChoosePixelFormat_sig = {2592, "CGLChoosePixelFormat", 3, _CGLChoosePixelFormat_args};
+static const trace::FunctionSig _CGLChoosePixelFormat_sig = {2593, "CGLChoosePixelFormat", 3, _CGLChoosePixelFormat_args};
 
 static const char * _CGLDestroyPixelFormat_args[1] = {"pix"};
-static const trace::FunctionSig _CGLDestroyPixelFormat_sig = {2593, "CGLDestroyPixelFormat", 1, _CGLDestroyPixelFormat_args};
+static const trace::FunctionSig _CGLDestroyPixelFormat_sig = {2594, "CGLDestroyPixelFormat", 1, _CGLDestroyPixelFormat_args};
 
 static const char * _CGLDescribePixelFormat_args[4] = {"pix", "pix_num", "attrib", "value"};
-static const trace::FunctionSig _CGLDescribePixelFormat_sig = {2594, "CGLDescribePixelFormat", 4, _CGLDescribePixelFormat_args};
+static const trace::FunctionSig _CGLDescribePixelFormat_sig = {2595, "CGLDescribePixelFormat", 4, _CGLDescribePixelFormat_args};
 
 static const char * _CGLReleasePixelFormat_args[1] = {"pix"};
-static const trace::FunctionSig _CGLReleasePixelFormat_sig = {2595, "CGLReleasePixelFormat", 1, _CGLReleasePixelFormat_args};
+static const trace::FunctionSig _CGLReleasePixelFormat_sig = {2596, "CGLReleasePixelFormat", 1, _CGLReleasePixelFormat_args};
 
 static const char * _CGLRetainPixelFormat_args[1] = {"pix"};
-static const trace::FunctionSig _CGLRetainPixelFormat_sig = {2596, "CGLRetainPixelFormat", 1, _CGLRetainPixelFormat_args};
+static const trace::FunctionSig _CGLRetainPixelFormat_sig = {2597, "CGLRetainPixelFormat", 1, _CGLRetainPixelFormat_args};
 
 static const char * _CGLGetPixelFormatRetainCount_args[1] = {"pix"};
-static const trace::FunctionSig _CGLGetPixelFormatRetainCount_sig = {2597, "CGLGetPixelFormatRetainCount", 1, _CGLGetPixelFormatRetainCount_args};
+static const trace::FunctionSig _CGLGetPixelFormatRetainCount_sig = {2598, "CGLGetPixelFormatRetainCount", 1, _CGLGetPixelFormatRetainCount_args};
 
 static const char * _CGLQueryRendererInfo_args[3] = {"display_mask", "rend", "nrend"};
-static const trace::FunctionSig _CGLQueryRendererInfo_sig = {2598, "CGLQueryRendererInfo", 3, _CGLQueryRendererInfo_args};
+static const trace::FunctionSig _CGLQueryRendererInfo_sig = {2599, "CGLQueryRendererInfo", 3, _CGLQueryRendererInfo_args};
 
 static const char * _CGLDestroyRendererInfo_args[1] = {"rend"};
-static const trace::FunctionSig _CGLDestroyRendererInfo_sig = {2599, "CGLDestroyRendererInfo", 1, _CGLDestroyRendererInfo_args};
+static const trace::FunctionSig _CGLDestroyRendererInfo_sig = {2600, "CGLDestroyRendererInfo", 1, _CGLDestroyRendererInfo_args};
 
 static const char * _CGLDescribeRenderer_args[4] = {"rend", "rend_num", "prop", "value"};
-static const trace::FunctionSig _CGLDescribeRenderer_sig = {2600, "CGLDescribeRenderer", 4, _CGLDescribeRenderer_args};
+static const trace::FunctionSig _CGLDescribeRenderer_sig = {2601, "CGLDescribeRenderer", 4, _CGLDescribeRenderer_args};
 
 static const char * _CGLCreateContext_args[3] = {"pix", "share", "ctx"};
-static const trace::FunctionSig _CGLCreateContext_sig = {2601, "CGLCreateContext", 3, _CGLCreateContext_args};
+static const trace::FunctionSig _CGLCreateContext_sig = {2602, "CGLCreateContext", 3, _CGLCreateContext_args};
 
 static const char * _CGLDestroyContext_args[1] = {"ctx"};
-static const trace::FunctionSig _CGLDestroyContext_sig = {2602, "CGLDestroyContext", 1, _CGLDestroyContext_args};
+static const trace::FunctionSig _CGLDestroyContext_sig = {2603, "CGLDestroyContext", 1, _CGLDestroyContext_args};
 
 static const char * _CGLCopyContext_args[3] = {"src", "dst", "mask"};
-static const trace::FunctionSig _CGLCopyContext_sig = {2603, "CGLCopyContext", 3, _CGLCopyContext_args};
+static const trace::FunctionSig _CGLCopyContext_sig = {2604, "CGLCopyContext", 3, _CGLCopyContext_args};
 
 static const char * _CGLRetainContext_args[1] = {"ctx"};
-static const trace::FunctionSig _CGLRetainContext_sig = {2604, "CGLRetainContext", 1, _CGLRetainContext_args};
+static const trace::FunctionSig _CGLRetainContext_sig = {2605, "CGLRetainContext", 1, _CGLRetainContext_args};
 
 static const char * _CGLReleaseContext_args[1] = {"ctx"};
-static const trace::FunctionSig _CGLReleaseContext_sig = {2605, "CGLReleaseContext", 1, _CGLReleaseContext_args};
+static const trace::FunctionSig _CGLReleaseContext_sig = {2606, "CGLReleaseContext", 1, _CGLReleaseContext_args};
 
 static const char * _CGLGetContextRetainCount_args[1] = {"ctx"};
-static const trace::FunctionSig _CGLGetContextRetainCount_sig = {2606, "CGLGetContextRetainCount", 1, _CGLGetContextRetainCount_args};
+static const trace::FunctionSig _CGLGetContextRetainCount_sig = {2607, "CGLGetContextRetainCount", 1, _CGLGetContextRetainCount_args};
 
 static const char * _CGLGetPixelFormat_args[1] = {"ctx"};
-static const trace::FunctionSig _CGLGetPixelFormat_sig = {2607, "CGLGetPixelFormat", 1, _CGLGetPixelFormat_args};
+static const trace::FunctionSig _CGLGetPixelFormat_sig = {2608, "CGLGetPixelFormat", 1, _CGLGetPixelFormat_args};
 
 static const char * _CGLCreatePBuffer_args[6] = {"width", "height", "target", "internalFormat", "max_level", "pbuffer"};
-static const trace::FunctionSig _CGLCreatePBuffer_sig = {2608, "CGLCreatePBuffer", 6, _CGLCreatePBuffer_args};
+static const trace::FunctionSig _CGLCreatePBuffer_sig = {2609, "CGLCreatePBuffer", 6, _CGLCreatePBuffer_args};
 
 static const char * _CGLDestroyPBuffer_args[1] = {"pbuffer"};
-static const trace::FunctionSig _CGLDestroyPBuffer_sig = {2609, "CGLDestroyPBuffer", 1, _CGLDestroyPBuffer_args};
+static const trace::FunctionSig _CGLDestroyPBuffer_sig = {2610, "CGLDestroyPBuffer", 1, _CGLDestroyPBuffer_args};
 
 static const char * _CGLDescribePBuffer_args[6] = {"obj", "width", "height", "target", "internalFormat", "mipmap"};
-static const trace::FunctionSig _CGLDescribePBuffer_sig = {2610, "CGLDescribePBuffer", 6, _CGLDescribePBuffer_args};
+static const trace::FunctionSig _CGLDescribePBuffer_sig = {2611, "CGLDescribePBuffer", 6, _CGLDescribePBuffer_args};
 
 static const char * _CGLTexImagePBuffer_args[3] = {"ctx", "pbuffer", "source"};
-static const trace::FunctionSig _CGLTexImagePBuffer_sig = {2611, "CGLTexImagePBuffer", 3, _CGLTexImagePBuffer_args};
+static const trace::FunctionSig _CGLTexImagePBuffer_sig = {2612, "CGLTexImagePBuffer", 3, _CGLTexImagePBuffer_args};
 
 static const char * _CGLRetainPBuffer_args[1] = {"pbuffer"};
-static const trace::FunctionSig _CGLRetainPBuffer_sig = {2612, "CGLRetainPBuffer", 1, _CGLRetainPBuffer_args};
+static const trace::FunctionSig _CGLRetainPBuffer_sig = {2613, "CGLRetainPBuffer", 1, _CGLRetainPBuffer_args};
 
 static const char * _CGLReleasePBuffer_args[1] = {"pbuffer"};
-static const trace::FunctionSig _CGLReleasePBuffer_sig = {2613, "CGLReleasePBuffer", 1, _CGLReleasePBuffer_args};
+static const trace::FunctionSig _CGLReleasePBuffer_sig = {2614, "CGLReleasePBuffer", 1, _CGLReleasePBuffer_args};
 
 static const char * _CGLGetPBufferRetainCount_args[1] = {"pbuffer"};
-static const trace::FunctionSig _CGLGetPBufferRetainCount_sig = {2614, "CGLGetPBufferRetainCount", 1, _CGLGetPBufferRetainCount_args};
+static const trace::FunctionSig _CGLGetPBufferRetainCount_sig = {2615, "CGLGetPBufferRetainCount", 1, _CGLGetPBufferRetainCount_args};
 
 static const char * _CGLSetOffScreen_args[5] = {"ctx", "width", "height", "rowbytes", "baseaddr"};
-static const trace::FunctionSig _CGLSetOffScreen_sig = {2615, "CGLSetOffScreen", 5, _CGLSetOffScreen_args};
+static const trace::FunctionSig _CGLSetOffScreen_sig = {2616, "CGLSetOffScreen", 5, _CGLSetOffScreen_args};
 
 static const char * _CGLGetOffScreen_args[5] = {"ctx", "width", "height", "rowbytes", "baseaddr"};
-static const trace::FunctionSig _CGLGetOffScreen_sig = {2616, "CGLGetOffScreen", 5, _CGLGetOffScreen_args};
+static const trace::FunctionSig _CGLGetOffScreen_sig = {2617, "CGLGetOffScreen", 5, _CGLGetOffScreen_args};
 
 static const char * _CGLSetFullScreen_args[1] = {"ctx"};
-static const trace::FunctionSig _CGLSetFullScreen_sig = {2617, "CGLSetFullScreen", 1, _CGLSetFullScreen_args};
+static const trace::FunctionSig _CGLSetFullScreen_sig = {2618, "CGLSetFullScreen", 1, _CGLSetFullScreen_args};
 
 static const char * _CGLSetFullScreenOnDisplay_args[2] = {"ctx", "display_mask"};
-static const trace::FunctionSig _CGLSetFullScreenOnDisplay_sig = {2618, "CGLSetFullScreenOnDisplay", 2, _CGLSetFullScreenOnDisplay_args};
+static const trace::FunctionSig _CGLSetFullScreenOnDisplay_sig = {2619, "CGLSetFullScreenOnDisplay", 2, _CGLSetFullScreenOnDisplay_args};
 
 static const char * _CGLSetPBuffer_args[5] = {"ctx", "pbuffer", "face", "level", "screen"};
-static const trace::FunctionSig _CGLSetPBuffer_sig = {2619, "CGLSetPBuffer", 5, _CGLSetPBuffer_args};
+static const trace::FunctionSig _CGLSetPBuffer_sig = {2620, "CGLSetPBuffer", 5, _CGLSetPBuffer_args};
 
 static const char * _CGLGetPBuffer_args[5] = {"ctx", "pbuffer", "face", "level", "screen"};
-static const trace::FunctionSig _CGLGetPBuffer_sig = {2620, "CGLGetPBuffer", 5, _CGLGetPBuffer_args};
+static const trace::FunctionSig _CGLGetPBuffer_sig = {2621, "CGLGetPBuffer", 5, _CGLGetPBuffer_args};
 
 static const char * _CGLClearDrawable_args[1] = {"ctx"};
-static const trace::FunctionSig _CGLClearDrawable_sig = {2621, "CGLClearDrawable", 1, _CGLClearDrawable_args};
+static const trace::FunctionSig _CGLClearDrawable_sig = {2622, "CGLClearDrawable", 1, _CGLClearDrawable_args};
 
 static const char * _CGLFlushDrawable_args[1] = {"ctx"};
-static const trace::FunctionSig _CGLFlushDrawable_sig = {2622, "CGLFlushDrawable", 1, _CGLFlushDrawable_args};
+static const trace::FunctionSig _CGLFlushDrawable_sig = {2623, "CGLFlushDrawable", 1, _CGLFlushDrawable_args};
 
 static const char * _CGLEnable_args[2] = {"ctx", "pname"};
-static const trace::FunctionSig _CGLEnable_sig = {2623, "CGLEnable", 2, _CGLEnable_args};
+static const trace::FunctionSig _CGLEnable_sig = {2624, "CGLEnable", 2, _CGLEnable_args};
 
 static const char * _CGLDisable_args[2] = {"ctx", "pname"};
-static const trace::FunctionSig _CGLDisable_sig = {2624, "CGLDisable", 2, _CGLDisable_args};
+static const trace::FunctionSig _CGLDisable_sig = {2625, "CGLDisable", 2, _CGLDisable_args};
 
 static const char * _CGLIsEnabled_args[3] = {"ctx", "pname", "enable"};
-static const trace::FunctionSig _CGLIsEnabled_sig = {2625, "CGLIsEnabled", 3, _CGLIsEnabled_args};
+static const trace::FunctionSig _CGLIsEnabled_sig = {2626, "CGLIsEnabled", 3, _CGLIsEnabled_args};
 
 static const char * _CGLSetParameter_args[3] = {"ctx", "pname", "params"};
-static const trace::FunctionSig _CGLSetParameter_sig = {2626, "CGLSetParameter", 3, _CGLSetParameter_args};
+static const trace::FunctionSig _CGLSetParameter_sig = {2627, "CGLSetParameter", 3, _CGLSetParameter_args};
 
 static const char * _CGLGetParameter_args[3] = {"ctx", "pname", "params"};
-static const trace::FunctionSig _CGLGetParameter_sig = {2627, "CGLGetParameter", 3, _CGLGetParameter_args};
+static const trace::FunctionSig _CGLGetParameter_sig = {2628, "CGLGetParameter", 3, _CGLGetParameter_args};
 
 static const char * _CGLSetVirtualScreen_args[2] = {"ctx", "screen"};
-static const trace::FunctionSig _CGLSetVirtualScreen_sig = {2628, "CGLSetVirtualScreen", 2, _CGLSetVirtualScreen_args};
+static const trace::FunctionSig _CGLSetVirtualScreen_sig = {2629, "CGLSetVirtualScreen", 2, _CGLSetVirtualScreen_args};
 
 static const char * _CGLGetVirtualScreen_args[2] = {"ctx", "screen"};
-static const trace::FunctionSig _CGLGetVirtualScreen_sig = {2629, "CGLGetVirtualScreen", 2, _CGLGetVirtualScreen_args};
+static const trace::FunctionSig _CGLGetVirtualScreen_sig = {2630, "CGLGetVirtualScreen", 2, _CGLGetVirtualScreen_args};
 
 static const char * _CGLSetGlobalOption_args[2] = {"pname", "params"};
-static const trace::FunctionSig _CGLSetGlobalOption_sig = {2630, "CGLSetGlobalOption", 2, _CGLSetGlobalOption_args};
+static const trace::FunctionSig _CGLSetGlobalOption_sig = {2631, "CGLSetGlobalOption", 2, _CGLSetGlobalOption_args};
 
 static const char * _CGLGetGlobalOption_args[2] = {"pname", "params"};
-static const trace::FunctionSig _CGLGetGlobalOption_sig = {2631, "CGLGetGlobalOption", 2, _CGLGetGlobalOption_args};
+static const trace::FunctionSig _CGLGetGlobalOption_sig = {2632, "CGLGetGlobalOption", 2, _CGLGetGlobalOption_args};
 
 static const char * _CGLSetOption_args[2] = {"pname", "param"};
-static const trace::FunctionSig _CGLSetOption_sig = {2632, "CGLSetOption", 2, _CGLSetOption_args};
+static const trace::FunctionSig _CGLSetOption_sig = {2633, "CGLSetOption", 2, _CGLSetOption_args};
 
 static const char * _CGLGetOption_args[2] = {"pname", "param"};
-static const trace::FunctionSig _CGLGetOption_sig = {2633, "CGLGetOption", 2, _CGLGetOption_args};
+static const trace::FunctionSig _CGLGetOption_sig = {2634, "CGLGetOption", 2, _CGLGetOption_args};
 
 static const char * _CGLLockContext_args[1] = {"ctx"};
-static const trace::FunctionSig _CGLLockContext_sig = {2634, "CGLLockContext", 1, _CGLLockContext_args};
+static const trace::FunctionSig _CGLLockContext_sig = {2635, "CGLLockContext", 1, _CGLLockContext_args};
 
 static const char * _CGLUnlockContext_args[1] = {"ctx"};
-static const trace::FunctionSig _CGLUnlockContext_sig = {2635, "CGLUnlockContext", 1, _CGLUnlockContext_args};
+static const trace::FunctionSig _CGLUnlockContext_sig = {2636, "CGLUnlockContext", 1, _CGLUnlockContext_args};
 
 static const char * _CGLGetVersion_args[2] = {"majorvers", "minorvers"};
-static const trace::FunctionSig _CGLGetVersion_sig = {2636, "CGLGetVersion", 2, _CGLGetVersion_args};
+static const trace::FunctionSig _CGLGetVersion_sig = {2637, "CGLGetVersion", 2, _CGLGetVersion_args};
 
 static const char * _CGLErrorString_args[1] = {"error"};
-static const trace::FunctionSig _CGLErrorString_sig = {2637, "CGLErrorString", 1, _CGLErrorString_args};
+static const trace::FunctionSig _CGLErrorString_sig = {2638, "CGLErrorString", 1, _CGLErrorString_args};
 
 static const char * _CGLTexImageIOSurface2D_args[9] = {"ctx", "target", "internal_format", "width", "height", "format", "type", "ioSurface", "plane"};
-static const trace::FunctionSig _CGLTexImageIOSurface2D_sig = {2638, "CGLTexImageIOSurface2D", 9, _CGLTexImageIOSurface2D_args};
+static const trace::FunctionSig _CGLTexImageIOSurface2D_sig = {2639, "CGLTexImageIOSurface2D", 9, _CGLTexImageIOSurface2D_args};
 
 static const char * _CGLGetShareGroup_args[1] = {"ctx"};
-static const trace::FunctionSig _CGLGetShareGroup_sig = {2639, "CGLGetShareGroup", 1, _CGLGetShareGroup_args};
+static const trace::FunctionSig _CGLGetShareGroup_sig = {2640, "CGLGetShareGroup", 1, _CGLGetShareGroup_args};
 
 static const char * _CGLSetSurface_args[4] = {"ctx", "cid", "wid", "sid"};
-static const trace::FunctionSig _CGLSetSurface_sig = {2640, "CGLSetSurface", 4, _CGLSetSurface_args};
+static const trace::FunctionSig _CGLSetSurface_sig = {2641, "CGLSetSurface", 4, _CGLSetSurface_args};
 
 static const char * _CGLGetSurface_args[4] = {"ctx", "cid", "wid", "sid"};
-static const trace::FunctionSig _CGLGetSurface_sig = {2641, "CGLGetSurface", 4, _CGLGetSurface_args};
+static const trace::FunctionSig _CGLGetSurface_sig = {2642, "CGLGetSurface", 4, _CGLGetSurface_args};
 
 static const char * _CGLUpdateContext_args[1] = {"ctx"};
-static const trace::FunctionSig _CGLUpdateContext_sig = {2642, "CGLUpdateContext", 1, _CGLUpdateContext_args};
+static const trace::FunctionSig _CGLUpdateContext_sig = {2643, "CGLUpdateContext", 1, _CGLUpdateContext_args};
 
 #endif // REGAL_SYS_OSX
 
 #if REGAL_SYS_EGL
 static const char ** _eglGetError_args = NULL;
-static const trace::FunctionSig _eglGetError_sig = {2643, "eglGetError", 0, _eglGetError_args};
+static const trace::FunctionSig _eglGetError_sig = {2644, "eglGetError", 0, _eglGetError_args};
 
 static const char * _eglGetDisplay_args[1] = {"display_id"};
-static const trace::FunctionSig _eglGetDisplay_sig = {2644, "eglGetDisplay", 1, _eglGetDisplay_args};
+static const trace::FunctionSig _eglGetDisplay_sig = {2645, "eglGetDisplay", 1, _eglGetDisplay_args};
 
 static const char * _eglInitialize_args[3] = {"dpy", "major", "minor"};
-static const trace::FunctionSig _eglInitialize_sig = {2645, "eglInitialize", 3, _eglInitialize_args};
+static const trace::FunctionSig _eglInitialize_sig = {2646, "eglInitialize", 3, _eglInitialize_args};
 
 static const char * _eglTerminate_args[1] = {"dpy"};
-static const trace::FunctionSig _eglTerminate_sig = {2646, "eglTerminate", 1, _eglTerminate_args};
+static const trace::FunctionSig _eglTerminate_sig = {2647, "eglTerminate", 1, _eglTerminate_args};
 
 static const char * _eglQueryString_args[2] = {"dpy", "name"};
-static const trace::FunctionSig _eglQueryString_sig = {2647, "eglQueryString", 2, _eglQueryString_args};
+static const trace::FunctionSig _eglQueryString_sig = {2648, "eglQueryString", 2, _eglQueryString_args};
 
 static const char * _eglGetConfigs_args[4] = {"dpy", "configs", "config_size", "num_config"};
-static const trace::FunctionSig _eglGetConfigs_sig = {2648, "eglGetConfigs", 4, _eglGetConfigs_args};
+static const trace::FunctionSig _eglGetConfigs_sig = {2649, "eglGetConfigs", 4, _eglGetConfigs_args};
 
 static const char * _eglChooseConfig_args[5] = {"dpy", "attrib_list", "configs", "config_size", "num_config"};
-static const trace::FunctionSig _eglChooseConfig_sig = {2649, "eglChooseConfig", 5, _eglChooseConfig_args};
+static const trace::FunctionSig _eglChooseConfig_sig = {2650, "eglChooseConfig", 5, _eglChooseConfig_args};
 
 static const char * _eglGetConfigAttrib_args[4] = {"dpy", "config", "attribute", "value"};
-static const trace::FunctionSig _eglGetConfigAttrib_sig = {2650, "eglGetConfigAttrib", 4, _eglGetConfigAttrib_args};
+static const trace::FunctionSig _eglGetConfigAttrib_sig = {2651, "eglGetConfigAttrib", 4, _eglGetConfigAttrib_args};
 
 static const char * _eglCreateWindowSurface_args[4] = {"dpy", "config", "win", "attrib_list"};
-static const trace::FunctionSig _eglCreateWindowSurface_sig = {2651, "eglCreateWindowSurface", 4, _eglCreateWindowSurface_args};
+static const trace::FunctionSig _eglCreateWindowSurface_sig = {2652, "eglCreateWindowSurface", 4, _eglCreateWindowSurface_args};
 
 static const char * _eglCreatePbufferSurface_args[3] = {"dpy", "config", "attrib_list"};
-static const trace::FunctionSig _eglCreatePbufferSurface_sig = {2652, "eglCreatePbufferSurface", 3, _eglCreatePbufferSurface_args};
+static const trace::FunctionSig _eglCreatePbufferSurface_sig = {2653, "eglCreatePbufferSurface", 3, _eglCreatePbufferSurface_args};
 
 static const char * _eglCreatePixmapSurface_args[4] = {"dpy", "config", "pixmap", "attrib_list"};
-static const trace::FunctionSig _eglCreatePixmapSurface_sig = {2653, "eglCreatePixmapSurface", 4, _eglCreatePixmapSurface_args};
+static const trace::FunctionSig _eglCreatePixmapSurface_sig = {2654, "eglCreatePixmapSurface", 4, _eglCreatePixmapSurface_args};
 
 static const char * _eglDestroySurface_args[2] = {"dpy", "surface"};
-static const trace::FunctionSig _eglDestroySurface_sig = {2654, "eglDestroySurface", 2, _eglDestroySurface_args};
+static const trace::FunctionSig _eglDestroySurface_sig = {2655, "eglDestroySurface", 2, _eglDestroySurface_args};
 
 static const char * _eglQuerySurface_args[4] = {"dpy", "surface", "attribute", "value"};
-static const trace::FunctionSig _eglQuerySurface_sig = {2655, "eglQuerySurface", 4, _eglQuerySurface_args};
+static const trace::FunctionSig _eglQuerySurface_sig = {2656, "eglQuerySurface", 4, _eglQuerySurface_args};
 
 static const char * _eglBindAPI_args[1] = {"api"};
-static const trace::FunctionSig _eglBindAPI_sig = {2656, "eglBindAPI", 1, _eglBindAPI_args};
+static const trace::FunctionSig _eglBindAPI_sig = {2657, "eglBindAPI", 1, _eglBindAPI_args};
 
 static const char ** _eglQueryAPI_args = NULL;
-static const trace::FunctionSig _eglQueryAPI_sig = {2657, "eglQueryAPI", 0, _eglQueryAPI_args};
+static const trace::FunctionSig _eglQueryAPI_sig = {2658, "eglQueryAPI", 0, _eglQueryAPI_args};
 
 static const char ** _eglWaitClient_args = NULL;
-static const trace::FunctionSig _eglWaitClient_sig = {2658, "eglWaitClient", 0, _eglWaitClient_args};
+static const trace::FunctionSig _eglWaitClient_sig = {2659, "eglWaitClient", 0, _eglWaitClient_args};
 
 static const char ** _eglReleaseThread_args = NULL;
-static const trace::FunctionSig _eglReleaseThread_sig = {2659, "eglReleaseThread", 0, _eglReleaseThread_args};
+static const trace::FunctionSig _eglReleaseThread_sig = {2660, "eglReleaseThread", 0, _eglReleaseThread_args};
 
 static const char * _eglCreatePbufferFromClientBuffer_args[5] = {"dpy", "buftype", "buffer", "config", "attrib_list"};
-static const trace::FunctionSig _eglCreatePbufferFromClientBuffer_sig = {2660, "eglCreatePbufferFromClientBuffer", 5, _eglCreatePbufferFromClientBuffer_args};
+static const trace::FunctionSig _eglCreatePbufferFromClientBuffer_sig = {2661, "eglCreatePbufferFromClientBuffer", 5, _eglCreatePbufferFromClientBuffer_args};
 
 static const char * _eglSurfaceAttrib_args[4] = {"dpy", "surface", "attribute", "value"};
-static const trace::FunctionSig _eglSurfaceAttrib_sig = {2661, "eglSurfaceAttrib", 4, _eglSurfaceAttrib_args};
+static const trace::FunctionSig _eglSurfaceAttrib_sig = {2662, "eglSurfaceAttrib", 4, _eglSurfaceAttrib_args};
 
 static const char * _eglBindTexImage_args[3] = {"dpy", "surface", "buffer"};
-static const trace::FunctionSig _eglBindTexImage_sig = {2662, "eglBindTexImage", 3, _eglBindTexImage_args};
+static const trace::FunctionSig _eglBindTexImage_sig = {2663, "eglBindTexImage", 3, _eglBindTexImage_args};
 
 static const char * _eglReleaseTexImage_args[3] = {"dpy", "surface", "buffer"};
-static const trace::FunctionSig _eglReleaseTexImage_sig = {2663, "eglReleaseTexImage", 3, _eglReleaseTexImage_args};
+static const trace::FunctionSig _eglReleaseTexImage_sig = {2664, "eglReleaseTexImage", 3, _eglReleaseTexImage_args};
 
 static const char * _eglSwapInterval_args[2] = {"dpy", "interval"};
-static const trace::FunctionSig _eglSwapInterval_sig = {2664, "eglSwapInterval", 2, _eglSwapInterval_args};
+static const trace::FunctionSig _eglSwapInterval_sig = {2665, "eglSwapInterval", 2, _eglSwapInterval_args};
 
 static const char * _eglCreateContext_args[4] = {"dpy", "config", "share_context", "attrib_list"};
-static const trace::FunctionSig _eglCreateContext_sig = {2665, "eglCreateContext", 4, _eglCreateContext_args};
+static const trace::FunctionSig _eglCreateContext_sig = {2666, "eglCreateContext", 4, _eglCreateContext_args};
 
 static const char * _eglDestroyContext_args[2] = {"dpy", "ctx"};
-static const trace::FunctionSig _eglDestroyContext_sig = {2666, "eglDestroyContext", 2, _eglDestroyContext_args};
+static const trace::FunctionSig _eglDestroyContext_sig = {2667, "eglDestroyContext", 2, _eglDestroyContext_args};
 
 static const char * _eglMakeCurrent_args[4] = {"dpy", "draw", "read", "ctx"};
-static const trace::FunctionSig _eglMakeCurrent_sig = {2667, "eglMakeCurrent", 4, _eglMakeCurrent_args};
+static const trace::FunctionSig _eglMakeCurrent_sig = {2668, "eglMakeCurrent", 4, _eglMakeCurrent_args};
 
 static const char ** _eglGetCurrentContext_args = NULL;
-static const trace::FunctionSig _eglGetCurrentContext_sig = {2668, "eglGetCurrentContext", 0, _eglGetCurrentContext_args};
+static const trace::FunctionSig _eglGetCurrentContext_sig = {2669, "eglGetCurrentContext", 0, _eglGetCurrentContext_args};
 
 static const char * _eglGetCurrentSurface_args[1] = {"readdraw"};
-static const trace::FunctionSig _eglGetCurrentSurface_sig = {2669, "eglGetCurrentSurface", 1, _eglGetCurrentSurface_args};
+static const trace::FunctionSig _eglGetCurrentSurface_sig = {2670, "eglGetCurrentSurface", 1, _eglGetCurrentSurface_args};
 
 static const char ** _eglGetCurrentDisplay_args = NULL;
-static const trace::FunctionSig _eglGetCurrentDisplay_sig = {2670, "eglGetCurrentDisplay", 0, _eglGetCurrentDisplay_args};
+static const trace::FunctionSig _eglGetCurrentDisplay_sig = {2671, "eglGetCurrentDisplay", 0, _eglGetCurrentDisplay_args};
 
 static const char * _eglQueryContext_args[4] = {"dpy", "ctx", "attribute", "value"};
-static const trace::FunctionSig _eglQueryContext_sig = {2671, "eglQueryContext", 4, _eglQueryContext_args};
+static const trace::FunctionSig _eglQueryContext_sig = {2672, "eglQueryContext", 4, _eglQueryContext_args};
 
 static const char ** _eglWaitGL_args = NULL;
-static const trace::FunctionSig _eglWaitGL_sig = {2672, "eglWaitGL", 0, _eglWaitGL_args};
+static const trace::FunctionSig _eglWaitGL_sig = {2673, "eglWaitGL", 0, _eglWaitGL_args};
 
 static const char * _eglWaitNative_args[1] = {"engine"};
-static const trace::FunctionSig _eglWaitNative_sig = {2673, "eglWaitNative", 1, _eglWaitNative_args};
+static const trace::FunctionSig _eglWaitNative_sig = {2674, "eglWaitNative", 1, _eglWaitNative_args};
 
 static const char * _eglSwapBuffers_args[2] = {"dpy", "surface"};
-static const trace::FunctionSig _eglSwapBuffers_sig = {2674, "eglSwapBuffers", 2, _eglSwapBuffers_args};
+static const trace::FunctionSig _eglSwapBuffers_sig = {2675, "eglSwapBuffers", 2, _eglSwapBuffers_args};
 
 static const char * _eglCopyBuffers_args[3] = {"dpy", "surface", "target"};
-static const trace::FunctionSig _eglCopyBuffers_sig = {2675, "eglCopyBuffers", 3, _eglCopyBuffers_args};
+static const trace::FunctionSig _eglCopyBuffers_sig = {2676, "eglCopyBuffers", 3, _eglCopyBuffers_args};
 
 static const char * _eglGetProcAddress_args[1] = {"procname"};
-static const trace::FunctionSig _eglGetProcAddress_sig = {2676, "eglGetProcAddress", 1, _eglGetProcAddress_args};
+static const trace::FunctionSig _eglGetProcAddress_sig = {2677, "eglGetProcAddress", 1, _eglGetProcAddress_args};
 
 static const char * _eglLockSurfaceKHR_args[3] = {"display", "surface", "attrib_list"};
-static const trace::FunctionSig _eglLockSurfaceKHR_sig = {2677, "eglLockSurfaceKHR", 3, _eglLockSurfaceKHR_args};
+static const trace::FunctionSig _eglLockSurfaceKHR_sig = {2678, "eglLockSurfaceKHR", 3, _eglLockSurfaceKHR_args};
 
 static const char * _eglUnlockSurfaceKHR_args[2] = {"display", "surface"};
-static const trace::FunctionSig _eglUnlockSurfaceKHR_sig = {2678, "eglUnlockSurfaceKHR", 2, _eglUnlockSurfaceKHR_args};
+static const trace::FunctionSig _eglUnlockSurfaceKHR_sig = {2679, "eglUnlockSurfaceKHR", 2, _eglUnlockSurfaceKHR_args};
 
 static const char * _eglCreateImageKHR_args[5] = {"dpy", "ctx", "target", "buffer", "attrib_list"};
-static const trace::FunctionSig _eglCreateImageKHR_sig = {2679, "eglCreateImageKHR", 5, _eglCreateImageKHR_args};
+static const trace::FunctionSig _eglCreateImageKHR_sig = {2680, "eglCreateImageKHR", 5, _eglCreateImageKHR_args};
 
 static const char * _eglDestroyImageKHR_args[2] = {"dpy", "image"};
-static const trace::FunctionSig _eglDestroyImageKHR_sig = {2680, "eglDestroyImageKHR", 2, _eglDestroyImageKHR_args};
+static const trace::FunctionSig _eglDestroyImageKHR_sig = {2681, "eglDestroyImageKHR", 2, _eglDestroyImageKHR_args};
 
 static const char * _eglCreateSyncKHR_args[3] = {"dpy", "type", "attrib_list"};
-static const trace::FunctionSig _eglCreateSyncKHR_sig = {2681, "eglCreateSyncKHR", 3, _eglCreateSyncKHR_args};
+static const trace::FunctionSig _eglCreateSyncKHR_sig = {2682, "eglCreateSyncKHR", 3, _eglCreateSyncKHR_args};
 
 static const char * _eglDestroySyncKHR_args[2] = {"dpy", "sync"};
-static const trace::FunctionSig _eglDestroySyncKHR_sig = {2682, "eglDestroySyncKHR", 2, _eglDestroySyncKHR_args};
+static const trace::FunctionSig _eglDestroySyncKHR_sig = {2683, "eglDestroySyncKHR", 2, _eglDestroySyncKHR_args};
 
 static const char * _eglClientWaitSyncKHR_args[4] = {"dpy", "sync", "flags", "timeout"};
-static const trace::FunctionSig _eglClientWaitSyncKHR_sig = {2683, "eglClientWaitSyncKHR", 4, _eglClientWaitSyncKHR_args};
+static const trace::FunctionSig _eglClientWaitSyncKHR_sig = {2684, "eglClientWaitSyncKHR", 4, _eglClientWaitSyncKHR_args};
 
 static const char * _eglSignalSyncKHR_args[3] = {"dpy", "sync", "mode"};
-static const trace::FunctionSig _eglSignalSyncKHR_sig = {2684, "eglSignalSyncKHR", 3, _eglSignalSyncKHR_args};
+static const trace::FunctionSig _eglSignalSyncKHR_sig = {2685, "eglSignalSyncKHR", 3, _eglSignalSyncKHR_args};
 
 static const char * _eglGetSyncAttribKHR_args[4] = {"dpy", "sync", "attribute", "value"};
-static const trace::FunctionSig _eglGetSyncAttribKHR_sig = {2685, "eglGetSyncAttribKHR", 4, _eglGetSyncAttribKHR_args};
+static const trace::FunctionSig _eglGetSyncAttribKHR_sig = {2686, "eglGetSyncAttribKHR", 4, _eglGetSyncAttribKHR_args};
 
 static const char * _eglCreateFenceSyncNV_args[3] = {"dpy", "condition", "attrib_list"};
-static const trace::FunctionSig _eglCreateFenceSyncNV_sig = {2686, "eglCreateFenceSyncNV", 3, _eglCreateFenceSyncNV_args};
+static const trace::FunctionSig _eglCreateFenceSyncNV_sig = {2687, "eglCreateFenceSyncNV", 3, _eglCreateFenceSyncNV_args};
 
 static const char * _eglDestroySyncNV_args[1] = {"sync"};
-static const trace::FunctionSig _eglDestroySyncNV_sig = {2687, "eglDestroySyncNV", 1, _eglDestroySyncNV_args};
+static const trace::FunctionSig _eglDestroySyncNV_sig = {2688, "eglDestroySyncNV", 1, _eglDestroySyncNV_args};
 
 static const char * _eglFenceNV_args[1] = {"sync"};
-static const trace::FunctionSig _eglFenceNV_sig = {2688, "eglFenceNV", 1, _eglFenceNV_args};
+static const trace::FunctionSig _eglFenceNV_sig = {2689, "eglFenceNV", 1, _eglFenceNV_args};
 
 static const char * _eglClientWaitSyncNV_args[3] = {"sync", "flags", "timeout"};
-static const trace::FunctionSig _eglClientWaitSyncNV_sig = {2689, "eglClientWaitSyncNV", 3, _eglClientWaitSyncNV_args};
+static const trace::FunctionSig _eglClientWaitSyncNV_sig = {2690, "eglClientWaitSyncNV", 3, _eglClientWaitSyncNV_args};
 
 static const char * _eglSignalSyncNV_args[2] = {"sync", "mode"};
-static const trace::FunctionSig _eglSignalSyncNV_sig = {2690, "eglSignalSyncNV", 2, _eglSignalSyncNV_args};
+static const trace::FunctionSig _eglSignalSyncNV_sig = {2691, "eglSignalSyncNV", 2, _eglSignalSyncNV_args};
 
 static const char * _eglGetSyncAttribNV_args[3] = {"sync", "attribute", "value"};
-static const trace::FunctionSig _eglGetSyncAttribNV_sig = {2691, "eglGetSyncAttribNV", 3, _eglGetSyncAttribNV_args};
+static const trace::FunctionSig _eglGetSyncAttribNV_sig = {2692, "eglGetSyncAttribNV", 3, _eglGetSyncAttribNV_args};
 
 static const char * _eglCreatePixmapSurfaceHI_args[3] = {"dpy", "config", "pixmap"};
-static const trace::FunctionSig _eglCreatePixmapSurfaceHI_sig = {2692, "eglCreatePixmapSurfaceHI", 3, _eglCreatePixmapSurfaceHI_args};
+static const trace::FunctionSig _eglCreatePixmapSurfaceHI_sig = {2693, "eglCreatePixmapSurfaceHI", 3, _eglCreatePixmapSurfaceHI_args};
 
 static const char * _eglCreateDRMImageMESA_args[2] = {"dpy", "attrib_list"};
-static const trace::FunctionSig _eglCreateDRMImageMESA_sig = {2693, "eglCreateDRMImageMESA", 2, _eglCreateDRMImageMESA_args};
+static const trace::FunctionSig _eglCreateDRMImageMESA_sig = {2694, "eglCreateDRMImageMESA", 2, _eglCreateDRMImageMESA_args};
 
 static const char * _eglExportDRMImageMESA_args[5] = {"dpy", "image", "name", "handle", "stride"};
-static const trace::FunctionSig _eglExportDRMImageMESA_sig = {2694, "eglExportDRMImageMESA", 5, _eglExportDRMImageMESA_args};
+static const trace::FunctionSig _eglExportDRMImageMESA_sig = {2695, "eglExportDRMImageMESA", 5, _eglExportDRMImageMESA_args};
 
 static const char * _eglPostSubBufferNV_args[6] = {"dpy", "surface", "x", "y", "width", "height"};
-static const trace::FunctionSig _eglPostSubBufferNV_sig = {2695, "eglPostSubBufferNV", 6, _eglPostSubBufferNV_args};
+static const trace::FunctionSig _eglPostSubBufferNV_sig = {2696, "eglPostSubBufferNV", 6, _eglPostSubBufferNV_args};
 
 static const char * _eglQuerySurfacePointerANGLE_args[4] = {"dpy", "surface", "attribute", "value"};
-static const trace::FunctionSig _eglQuerySurfacePointerANGLE_sig = {2696, "eglQuerySurfacePointerANGLE", 4, _eglQuerySurfacePointerANGLE_args};
+static const trace::FunctionSig _eglQuerySurfacePointerANGLE_sig = {2697, "eglQuerySurfacePointerANGLE", 4, _eglQuerySurfacePointerANGLE_args};
 
 static const char ** _eglGetSystemTimeFrequencyNV_args = NULL;
-static const trace::FunctionSig _eglGetSystemTimeFrequencyNV_sig = {2697, "eglGetSystemTimeFrequencyNV", 0, _eglGetSystemTimeFrequencyNV_args};
+static const trace::FunctionSig _eglGetSystemTimeFrequencyNV_sig = {2698, "eglGetSystemTimeFrequencyNV", 0, _eglGetSystemTimeFrequencyNV_args};
 
 static const char ** _eglGetSystemTimeNV_args = NULL;
-static const trace::FunctionSig _eglGetSystemTimeNV_sig = {2698, "eglGetSystemTimeNV", 0, _eglGetSystemTimeNV_args};
+static const trace::FunctionSig _eglGetSystemTimeNV_sig = {2699, "eglGetSystemTimeNV", 0, _eglGetSystemTimeNV_args};
 
 static const char * _glEGLImageTargetTexture2DOES_args[2] = {"target", "image"};
-static const trace::FunctionSig _glEGLImageTargetTexture2DOES_sig = {2699, "glEGLImageTargetTexture2DOES", 2, _glEGLImageTargetTexture2DOES_args};
+static const trace::FunctionSig _glEGLImageTargetTexture2DOES_sig = {2700, "glEGLImageTargetTexture2DOES", 2, _glEGLImageTargetTexture2DOES_args};
 
 static const char * _glEGLImageTargetRenderbufferStorageOES_args[2] = {"target", "image"};
-static const trace::FunctionSig _glEGLImageTargetRenderbufferStorageOES_sig = {2700, "glEGLImageTargetRenderbufferStorageOES", 2, _glEGLImageTargetRenderbufferStorageOES_args};
+static const trace::FunctionSig _glEGLImageTargetRenderbufferStorageOES_sig = {2701, "glEGLImageTargetRenderbufferStorageOES", 2, _glEGLImageTargetRenderbufferStorageOES_args};
 
 #endif // REGAL_SYS_EGL
 
 #if REGAL_SYS_GLX
 static const char * _glXChooseVisual_args[3] = {"dpy", "screen", "attribList"};
-static const trace::FunctionSig _glXChooseVisual_sig = {2701, "glXChooseVisual", 3, _glXChooseVisual_args};
+static const trace::FunctionSig _glXChooseVisual_sig = {2702, "glXChooseVisual", 3, _glXChooseVisual_args};
 
 static const char * _glXCreateContext_args[4] = {"dpy", "vis", "shareList", "direct"};
-static const trace::FunctionSig _glXCreateContext_sig = {2702, "glXCreateContext", 4, _glXCreateContext_args};
+static const trace::FunctionSig _glXCreateContext_sig = {2703, "glXCreateContext", 4, _glXCreateContext_args};
 
 static const char * _glXDestroyContext_args[2] = {"dpy", "ctx"};
-static const trace::FunctionSig _glXDestroyContext_sig = {2703, "glXDestroyContext", 2, _glXDestroyContext_args};
+static const trace::FunctionSig _glXDestroyContext_sig = {2704, "glXDestroyContext", 2, _glXDestroyContext_args};
 
 static const char * _glXMakeCurrent_args[3] = {"dpy", "drawable", "ctx"};
-static const trace::FunctionSig _glXMakeCurrent_sig = {2704, "glXMakeCurrent", 3, _glXMakeCurrent_args};
+static const trace::FunctionSig _glXMakeCurrent_sig = {2705, "glXMakeCurrent", 3, _glXMakeCurrent_args};
 
 static const char * _glXCopyContext_args[4] = {"dpy", "src", "dst", "mask"};
-static const trace::FunctionSig _glXCopyContext_sig = {2705, "glXCopyContext", 4, _glXCopyContext_args};
+static const trace::FunctionSig _glXCopyContext_sig = {2706, "glXCopyContext", 4, _glXCopyContext_args};
 
 static const char * _glXSwapBuffers_args[2] = {"dpy", "drawable"};
-static const trace::FunctionSig _glXSwapBuffers_sig = {2706, "glXSwapBuffers", 2, _glXSwapBuffers_args};
+static const trace::FunctionSig _glXSwapBuffers_sig = {2707, "glXSwapBuffers", 2, _glXSwapBuffers_args};
 
 static const char * _glXCreateGLXPixmap_args[3] = {"dpy", "visual", "pixmap"};
-static const trace::FunctionSig _glXCreateGLXPixmap_sig = {2707, "glXCreateGLXPixmap", 3, _glXCreateGLXPixmap_args};
+static const trace::FunctionSig _glXCreateGLXPixmap_sig = {2708, "glXCreateGLXPixmap", 3, _glXCreateGLXPixmap_args};
 
 static const char * _glXDestroyGLXPixmap_args[2] = {"dpy", "pixmap"};
-static const trace::FunctionSig _glXDestroyGLXPixmap_sig = {2708, "glXDestroyGLXPixmap", 2, _glXDestroyGLXPixmap_args};
+static const trace::FunctionSig _glXDestroyGLXPixmap_sig = {2709, "glXDestroyGLXPixmap", 2, _glXDestroyGLXPixmap_args};
 
 static const char * _glXQueryExtension_args[3] = {"dpy", "errorb", "event"};
-static const trace::FunctionSig _glXQueryExtension_sig = {2709, "glXQueryExtension", 3, _glXQueryExtension_args};
+static const trace::FunctionSig _glXQueryExtension_sig = {2710, "glXQueryExtension", 3, _glXQueryExtension_args};
 
 static const char * _glXQueryVersion_args[3] = {"dpy", "maj", "min"};
-static const trace::FunctionSig _glXQueryVersion_sig = {2710, "glXQueryVersion", 3, _glXQueryVersion_args};
+static const trace::FunctionSig _glXQueryVersion_sig = {2711, "glXQueryVersion", 3, _glXQueryVersion_args};
 
 static const char * _glXIsDirect_args[2] = {"dpy", "ctx"};
-static const trace::FunctionSig _glXIsDirect_sig = {2711, "glXIsDirect", 2, _glXIsDirect_args};
+static const trace::FunctionSig _glXIsDirect_sig = {2712, "glXIsDirect", 2, _glXIsDirect_args};
 
 static const char * _glXGetConfig_args[4] = {"dpy", "visual", "attrib", "value"};
-static const trace::FunctionSig _glXGetConfig_sig = {2712, "glXGetConfig", 4, _glXGetConfig_args};
+static const trace::FunctionSig _glXGetConfig_sig = {2713, "glXGetConfig", 4, _glXGetConfig_args};
 
 static const char ** _glXGetCurrentContext_args = NULL;
-static const trace::FunctionSig _glXGetCurrentContext_sig = {2713, "glXGetCurrentContext", 0, _glXGetCurrentContext_args};
+static const trace::FunctionSig _glXGetCurrentContext_sig = {2714, "glXGetCurrentContext", 0, _glXGetCurrentContext_args};
 
 static const char ** _glXGetCurrentDrawable_args = NULL;
-static const trace::FunctionSig _glXGetCurrentDrawable_sig = {2714, "glXGetCurrentDrawable", 0, _glXGetCurrentDrawable_args};
+static const trace::FunctionSig _glXGetCurrentDrawable_sig = {2715, "glXGetCurrentDrawable", 0, _glXGetCurrentDrawable_args};
 
 static const char ** _glXWaitGL_args = NULL;
-static const trace::FunctionSig _glXWaitGL_sig = {2715, "glXWaitGL", 0, _glXWaitGL_args};
+static const trace::FunctionSig _glXWaitGL_sig = {2716, "glXWaitGL", 0, _glXWaitGL_args};
 
 static const char ** _glXWaitX_args = NULL;
-static const trace::FunctionSig _glXWaitX_sig = {2716, "glXWaitX", 0, _glXWaitX_args};
+static const trace::FunctionSig _glXWaitX_sig = {2717, "glXWaitX", 0, _glXWaitX_args};
 
 static const char * _glXUseXFont_args[4] = {"font", "first", "count", "list"};
-static const trace::FunctionSig _glXUseXFont_sig = {2717, "glXUseXFont", 4, _glXUseXFont_args};
+static const trace::FunctionSig _glXUseXFont_sig = {2718, "glXUseXFont", 4, _glXUseXFont_args};
 
 static const char * _glXQueryExtensionsString_args[2] = {"dpy", "screen"};
-static const trace::FunctionSig _glXQueryExtensionsString_sig = {2718, "glXQueryExtensionsString", 2, _glXQueryExtensionsString_args};
+static const trace::FunctionSig _glXQueryExtensionsString_sig = {2719, "glXQueryExtensionsString", 2, _glXQueryExtensionsString_args};
 
 static const char * _glXQueryServerString_args[3] = {"dpy", "screen", "name"};
-static const trace::FunctionSig _glXQueryServerString_sig = {2719, "glXQueryServerString", 3, _glXQueryServerString_args};
+static const trace::FunctionSig _glXQueryServerString_sig = {2720, "glXQueryServerString", 3, _glXQueryServerString_args};
 
 static const char * _glXGetClientString_args[2] = {"dpy", "name"};
-static const trace::FunctionSig _glXGetClientString_sig = {2720, "glXGetClientString", 2, _glXGetClientString_args};
+static const trace::FunctionSig _glXGetClientString_sig = {2721, "glXGetClientString", 2, _glXGetClientString_args};
 
 static const char ** _glXGetCurrentDisplay_args = NULL;
-static const trace::FunctionSig _glXGetCurrentDisplay_sig = {2721, "glXGetCurrentDisplay", 0, _glXGetCurrentDisplay_args};
+static const trace::FunctionSig _glXGetCurrentDisplay_sig = {2722, "glXGetCurrentDisplay", 0, _glXGetCurrentDisplay_args};
 
 static const char * _glXChooseFBConfig_args[4] = {"dpy", "screen", "attribList", "nitems"};
-static const trace::FunctionSig _glXChooseFBConfig_sig = {2722, "glXChooseFBConfig", 4, _glXChooseFBConfig_args};
+static const trace::FunctionSig _glXChooseFBConfig_sig = {2723, "glXChooseFBConfig", 4, _glXChooseFBConfig_args};
 
 static const char * _glXGetFBConfigAttrib_args[4] = {"dpy", "config", "attribute", "value"};
-static const trace::FunctionSig _glXGetFBConfigAttrib_sig = {2723, "glXGetFBConfigAttrib", 4, _glXGetFBConfigAttrib_args};
+static const trace::FunctionSig _glXGetFBConfigAttrib_sig = {2724, "glXGetFBConfigAttrib", 4, _glXGetFBConfigAttrib_args};
 
 static const char * _glXGetFBConfigs_args[3] = {"dpy", "screen", "nelements"};
-static const trace::FunctionSig _glXGetFBConfigs_sig = {2724, "glXGetFBConfigs", 3, _glXGetFBConfigs_args};
+static const trace::FunctionSig _glXGetFBConfigs_sig = {2725, "glXGetFBConfigs", 3, _glXGetFBConfigs_args};
 
 static const char * _glXGetVisualFromFBConfig_args[2] = {"dpy", "config"};
-static const trace::FunctionSig _glXGetVisualFromFBConfig_sig = {2725, "glXGetVisualFromFBConfig", 2, _glXGetVisualFromFBConfig_args};
+static const trace::FunctionSig _glXGetVisualFromFBConfig_sig = {2726, "glXGetVisualFromFBConfig", 2, _glXGetVisualFromFBConfig_args};
 
 static const char * _glXCreateWindow_args[4] = {"dpy", "config", "win", "attribList"};
-static const trace::FunctionSig _glXCreateWindow_sig = {2726, "glXCreateWindow", 4, _glXCreateWindow_args};
+static const trace::FunctionSig _glXCreateWindow_sig = {2727, "glXCreateWindow", 4, _glXCreateWindow_args};
 
 static const char * _glXDestroyWindow_args[2] = {"dpy", "window"};
-static const trace::FunctionSig _glXDestroyWindow_sig = {2727, "glXDestroyWindow", 2, _glXDestroyWindow_args};
+static const trace::FunctionSig _glXDestroyWindow_sig = {2728, "glXDestroyWindow", 2, _glXDestroyWindow_args};
 
 static const char * _glXCreatePixmap_args[4] = {"dpy", "config", "pixmap", "attribList"};
-static const trace::FunctionSig _glXCreatePixmap_sig = {2728, "glXCreatePixmap", 4, _glXCreatePixmap_args};
+static const trace::FunctionSig _glXCreatePixmap_sig = {2729, "glXCreatePixmap", 4, _glXCreatePixmap_args};
 
 static const char * _glXDestroyPixmap_args[2] = {"dpy", "pixmap"};
-static const trace::FunctionSig _glXDestroyPixmap_sig = {2729, "glXDestroyPixmap", 2, _glXDestroyPixmap_args};
+static const trace::FunctionSig _glXDestroyPixmap_sig = {2730, "glXDestroyPixmap", 2, _glXDestroyPixmap_args};
 
 static const char * _glXCreatePbuffer_args[3] = {"dpy", "config", "attribList"};
-static const trace::FunctionSig _glXCreatePbuffer_sig = {2730, "glXCreatePbuffer", 3, _glXCreatePbuffer_args};
+static const trace::FunctionSig _glXCreatePbuffer_sig = {2731, "glXCreatePbuffer", 3, _glXCreatePbuffer_args};
 
 static const char * _glXDestroyPbuffer_args[2] = {"dpy", "pbuf"};
-static const trace::FunctionSig _glXDestroyPbuffer_sig = {2731, "glXDestroyPbuffer", 2, _glXDestroyPbuffer_args};
+static const trace::FunctionSig _glXDestroyPbuffer_sig = {2732, "glXDestroyPbuffer", 2, _glXDestroyPbuffer_args};
 
 static const char * _glXQueryDrawable_args[4] = {"dpy", "draw", "attribute", "value"};
-static const trace::FunctionSig _glXQueryDrawable_sig = {2732, "glXQueryDrawable", 4, _glXQueryDrawable_args};
+static const trace::FunctionSig _glXQueryDrawable_sig = {2733, "glXQueryDrawable", 4, _glXQueryDrawable_args};
 
 static const char * _glXCreateNewContext_args[5] = {"dpy", "config", "renderType", "shareList", "direct"};
-static const trace::FunctionSig _glXCreateNewContext_sig = {2733, "glXCreateNewContext", 5, _glXCreateNewContext_args};
+static const trace::FunctionSig _glXCreateNewContext_sig = {2734, "glXCreateNewContext", 5, _glXCreateNewContext_args};
 
 static const char * _glXMakeContextCurrent_args[4] = {"dpy", "draw", "read", "ctx"};
-static const trace::FunctionSig _glXMakeContextCurrent_sig = {2734, "glXMakeContextCurrent", 4, _glXMakeContextCurrent_args};
+static const trace::FunctionSig _glXMakeContextCurrent_sig = {2735, "glXMakeContextCurrent", 4, _glXMakeContextCurrent_args};
 
 static const char ** _glXGetCurrentReadDrawable_args = NULL;
-static const trace::FunctionSig _glXGetCurrentReadDrawable_sig = {2735, "glXGetCurrentReadDrawable", 0, _glXGetCurrentReadDrawable_args};
+static const trace::FunctionSig _glXGetCurrentReadDrawable_sig = {2736, "glXGetCurrentReadDrawable", 0, _glXGetCurrentReadDrawable_args};
 
 static const char * _glXQueryContext_args[4] = {"dpy", "ctx", "attribute", "value"};
-static const trace::FunctionSig _glXQueryContext_sig = {2736, "glXQueryContext", 4, _glXQueryContext_args};
+static const trace::FunctionSig _glXQueryContext_sig = {2737, "glXQueryContext", 4, _glXQueryContext_args};
 
 static const char * _glXSelectEvent_args[3] = {"dpy", "drawable", "mask"};
-static const trace::FunctionSig _glXSelectEvent_sig = {2737, "glXSelectEvent", 3, _glXSelectEvent_args};
+static const trace::FunctionSig _glXSelectEvent_sig = {2738, "glXSelectEvent", 3, _glXSelectEvent_args};
 
 static const char * _glXGetSelectedEvent_args[3] = {"dpy", "drawable", "mask"};
-static const trace::FunctionSig _glXGetSelectedEvent_sig = {2738, "glXGetSelectedEvent", 3, _glXGetSelectedEvent_args};
+static const trace::FunctionSig _glXGetSelectedEvent_sig = {2739, "glXGetSelectedEvent", 3, _glXGetSelectedEvent_args};
 
 static const char * _glXCreateContextAttribsARB_args[5] = {"dpy", "config", "share_context", "direct", "attrib_list"};
-static const trace::FunctionSig _glXCreateContextAttribsARB_sig = {2739, "glXCreateContextAttribsARB", 5, _glXCreateContextAttribsARB_args};
+static const trace::FunctionSig _glXCreateContextAttribsARB_sig = {2740, "glXCreateContextAttribsARB", 5, _glXCreateContextAttribsARB_args};
 
 static const char * _glXSwapIntervalSGI_args[1] = {"interval"};
-static const trace::FunctionSig _glXSwapIntervalSGI_sig = {2740, "glXSwapIntervalSGI", 1, _glXSwapIntervalSGI_args};
+static const trace::FunctionSig _glXSwapIntervalSGI_sig = {2741, "glXSwapIntervalSGI", 1, _glXSwapIntervalSGI_args};
 
 static const char * _glXGetVideoSyncSGI_args[1] = {"count"};
-static const trace::FunctionSig _glXGetVideoSyncSGI_sig = {2741, "glXGetVideoSyncSGI", 1, _glXGetVideoSyncSGI_args};
+static const trace::FunctionSig _glXGetVideoSyncSGI_sig = {2742, "glXGetVideoSyncSGI", 1, _glXGetVideoSyncSGI_args};
 
 static const char * _glXWaitVideoSyncSGI_args[3] = {"divisor", "remainder", "count"};
-static const trace::FunctionSig _glXWaitVideoSyncSGI_sig = {2742, "glXWaitVideoSyncSGI", 3, _glXWaitVideoSyncSGI_args};
+static const trace::FunctionSig _glXWaitVideoSyncSGI_sig = {2743, "glXWaitVideoSyncSGI", 3, _glXWaitVideoSyncSGI_args};
 
 static const char * _glXMakeCurrentReadSGI_args[4] = {"dpy", "draw", "read", "ctx"};
-static const trace::FunctionSig _glXMakeCurrentReadSGI_sig = {2743, "glXMakeCurrentReadSGI", 4, _glXMakeCurrentReadSGI_args};
+static const trace::FunctionSig _glXMakeCurrentReadSGI_sig = {2744, "glXMakeCurrentReadSGI", 4, _glXMakeCurrentReadSGI_args};
 
 static const char ** _glXGetCurrentReadDrawableSGI_args = NULL;
-static const trace::FunctionSig _glXGetCurrentReadDrawableSGI_sig = {2744, "glXGetCurrentReadDrawableSGI", 0, _glXGetCurrentReadDrawableSGI_args};
+static const trace::FunctionSig _glXGetCurrentReadDrawableSGI_sig = {2745, "glXGetCurrentReadDrawableSGI", 0, _glXGetCurrentReadDrawableSGI_args};
 
 static const char ** _glXGetCurrentDisplayEXT_args = NULL;
-static const trace::FunctionSig _glXGetCurrentDisplayEXT_sig = {2745, "glXGetCurrentDisplayEXT", 0, _glXGetCurrentDisplayEXT_args};
+static const trace::FunctionSig _glXGetCurrentDisplayEXT_sig = {2746, "glXGetCurrentDisplayEXT", 0, _glXGetCurrentDisplayEXT_args};
 
 static const char * _glXQueryContextInfoEXT_args[4] = {"dpy", "context", "attribute", "value"};
-static const trace::FunctionSig _glXQueryContextInfoEXT_sig = {2746, "glXQueryContextInfoEXT", 4, _glXQueryContextInfoEXT_args};
+static const trace::FunctionSig _glXQueryContextInfoEXT_sig = {2747, "glXQueryContextInfoEXT", 4, _glXQueryContextInfoEXT_args};
 
 static const char * _glXGetContextIDEXT_args[1] = {"context"};
-static const trace::FunctionSig _glXGetContextIDEXT_sig = {2747, "glXGetContextIDEXT", 1, _glXGetContextIDEXT_args};
+static const trace::FunctionSig _glXGetContextIDEXT_sig = {2748, "glXGetContextIDEXT", 1, _glXGetContextIDEXT_args};
 
 static const char * _glXImportContextEXT_args[2] = {"dpy", "contextID"};
-static const trace::FunctionSig _glXImportContextEXT_sig = {2748, "glXImportContextEXT", 2, _glXImportContextEXT_args};
+static const trace::FunctionSig _glXImportContextEXT_sig = {2749, "glXImportContextEXT", 2, _glXImportContextEXT_args};
 
 static const char * _glXFreeContextEXT_args[2] = {"dpy", "context"};
-static const trace::FunctionSig _glXFreeContextEXT_sig = {2749, "glXFreeContextEXT", 2, _glXFreeContextEXT_args};
+static const trace::FunctionSig _glXFreeContextEXT_sig = {2750, "glXFreeContextEXT", 2, _glXFreeContextEXT_args};
 
 static const char * _glXGetFBConfigAttribSGIX_args[4] = {"dpy", "config", "attribute", "value"};
-static const trace::FunctionSig _glXGetFBConfigAttribSGIX_sig = {2750, "glXGetFBConfigAttribSGIX", 4, _glXGetFBConfigAttribSGIX_args};
+static const trace::FunctionSig _glXGetFBConfigAttribSGIX_sig = {2751, "glXGetFBConfigAttribSGIX", 4, _glXGetFBConfigAttribSGIX_args};
 
 static const char * _glXChooseFBConfigSGIX_args[4] = {"dpy", "screen", "attrib_list", "nelements"};
-static const trace::FunctionSig _glXChooseFBConfigSGIX_sig = {2751, "glXChooseFBConfigSGIX", 4, _glXChooseFBConfigSGIX_args};
+static const trace::FunctionSig _glXChooseFBConfigSGIX_sig = {2752, "glXChooseFBConfigSGIX", 4, _glXChooseFBConfigSGIX_args};
 
 static const char * _glXCreateGLXPixmapWithConfigSGIX_args[3] = {"dpy", "config", "pixmap"};
-static const trace::FunctionSig _glXCreateGLXPixmapWithConfigSGIX_sig = {2752, "glXCreateGLXPixmapWithConfigSGIX", 3, _glXCreateGLXPixmapWithConfigSGIX_args};
+static const trace::FunctionSig _glXCreateGLXPixmapWithConfigSGIX_sig = {2753, "glXCreateGLXPixmapWithConfigSGIX", 3, _glXCreateGLXPixmapWithConfigSGIX_args};
 
 static const char * _glXCreateContextWithConfigSGIX_args[5] = {"dpy", "config", "render_type", "share_list", "direct"};
-static const trace::FunctionSig _glXCreateContextWithConfigSGIX_sig = {2753, "glXCreateContextWithConfigSGIX", 5, _glXCreateContextWithConfigSGIX_args};
+static const trace::FunctionSig _glXCreateContextWithConfigSGIX_sig = {2754, "glXCreateContextWithConfigSGIX", 5, _glXCreateContextWithConfigSGIX_args};
 
 static const char * _glXGetVisualFromFBConfigSGIX_args[2] = {"dpy", "config"};
-static const trace::FunctionSig _glXGetVisualFromFBConfigSGIX_sig = {2754, "glXGetVisualFromFBConfigSGIX", 2, _glXGetVisualFromFBConfigSGIX_args};
+static const trace::FunctionSig _glXGetVisualFromFBConfigSGIX_sig = {2755, "glXGetVisualFromFBConfigSGIX", 2, _glXGetVisualFromFBConfigSGIX_args};
 
 static const char * _glXGetFBConfigFromVisualSGIX_args[2] = {"dpy", "vis"};
-static const trace::FunctionSig _glXGetFBConfigFromVisualSGIX_sig = {2755, "glXGetFBConfigFromVisualSGIX", 2, _glXGetFBConfigFromVisualSGIX_args};
+static const trace::FunctionSig _glXGetFBConfigFromVisualSGIX_sig = {2756, "glXGetFBConfigFromVisualSGIX", 2, _glXGetFBConfigFromVisualSGIX_args};
 
 static const char * _glXCreateGLXPbufferSGIX_args[5] = {"dpy", "config", "width", "height", "attrib_list"};
-static const trace::FunctionSig _glXCreateGLXPbufferSGIX_sig = {2756, "glXCreateGLXPbufferSGIX", 5, _glXCreateGLXPbufferSGIX_args};
+static const trace::FunctionSig _glXCreateGLXPbufferSGIX_sig = {2757, "glXCreateGLXPbufferSGIX", 5, _glXCreateGLXPbufferSGIX_args};
 
 static const char * _glXDestroyGLXPbufferSGIX_args[2] = {"dpy", "pbuf"};
-static const trace::FunctionSig _glXDestroyGLXPbufferSGIX_sig = {2757, "glXDestroyGLXPbufferSGIX", 2, _glXDestroyGLXPbufferSGIX_args};
+static const trace::FunctionSig _glXDestroyGLXPbufferSGIX_sig = {2758, "glXDestroyGLXPbufferSGIX", 2, _glXDestroyGLXPbufferSGIX_args};
 
 static const char * _glXQueryGLXPbufferSGIX_args[4] = {"dpy", "pbuf", "attribute", "value"};
-static const trace::FunctionSig _glXQueryGLXPbufferSGIX_sig = {2758, "glXQueryGLXPbufferSGIX", 4, _glXQueryGLXPbufferSGIX_args};
+static const trace::FunctionSig _glXQueryGLXPbufferSGIX_sig = {2759, "glXQueryGLXPbufferSGIX", 4, _glXQueryGLXPbufferSGIX_args};
 
 static const char * _glXSelectEventSGIX_args[3] = {"dpy", "drawable", "mask"};
-static const trace::FunctionSig _glXSelectEventSGIX_sig = {2759, "glXSelectEventSGIX", 3, _glXSelectEventSGIX_args};
+static const trace::FunctionSig _glXSelectEventSGIX_sig = {2760, "glXSelectEventSGIX", 3, _glXSelectEventSGIX_args};
 
 static const char * _glXGetSelectedEventSGIX_args[3] = {"dpy", "drawable", "mask"};
-static const trace::FunctionSig _glXGetSelectedEventSGIX_sig = {2760, "glXGetSelectedEventSGIX", 3, _glXGetSelectedEventSGIX_args};
+static const trace::FunctionSig _glXGetSelectedEventSGIX_sig = {2761, "glXGetSelectedEventSGIX", 3, _glXGetSelectedEventSGIX_args};
 
 static const char * _glXCushionSGI_args[3] = {"dpy", "window", "cushion"};
-static const trace::FunctionSig _glXCushionSGI_sig = {2761, "glXCushionSGI", 3, _glXCushionSGI_args};
+static const trace::FunctionSig _glXCushionSGI_sig = {2762, "glXCushionSGI", 3, _glXCushionSGI_args};
 
 static const char * _glXBindChannelToWindowSGIX_args[4] = {"display", "screen", "channel", "window"};
-static const trace::FunctionSig _glXBindChannelToWindowSGIX_sig = {2762, "glXBindChannelToWindowSGIX", 4, _glXBindChannelToWindowSGIX_args};
+static const trace::FunctionSig _glXBindChannelToWindowSGIX_sig = {2763, "glXBindChannelToWindowSGIX", 4, _glXBindChannelToWindowSGIX_args};
 
 static const char * _glXChannelRectSGIX_args[7] = {"display", "screen", "channel", "x", "y", "w", "h"};
-static const trace::FunctionSig _glXChannelRectSGIX_sig = {2763, "glXChannelRectSGIX", 7, _glXChannelRectSGIX_args};
+static const trace::FunctionSig _glXChannelRectSGIX_sig = {2764, "glXChannelRectSGIX", 7, _glXChannelRectSGIX_args};
 
 static const char * _glXQueryChannelRectSGIX_args[7] = {"display", "screen", "channel", "dx", "dy", "dw", "dh"};
-static const trace::FunctionSig _glXQueryChannelRectSGIX_sig = {2764, "glXQueryChannelRectSGIX", 7, _glXQueryChannelRectSGIX_args};
+static const trace::FunctionSig _glXQueryChannelRectSGIX_sig = {2765, "glXQueryChannelRectSGIX", 7, _glXQueryChannelRectSGIX_args};
 
 static const char * _glXQueryChannelDeltasSGIX_args[7] = {"display", "screen", "channel", "x", "y", "w", "h"};
-static const trace::FunctionSig _glXQueryChannelDeltasSGIX_sig = {2765, "glXQueryChannelDeltasSGIX", 7, _glXQueryChannelDeltasSGIX_args};
+static const trace::FunctionSig _glXQueryChannelDeltasSGIX_sig = {2766, "glXQueryChannelDeltasSGIX", 7, _glXQueryChannelDeltasSGIX_args};
 
 static const char * _glXChannelRectSyncSGIX_args[4] = {"display", "screen", "channel", "synctype"};
-static const trace::FunctionSig _glXChannelRectSyncSGIX_sig = {2766, "glXChannelRectSyncSGIX", 4, _glXChannelRectSyncSGIX_args};
+static const trace::FunctionSig _glXChannelRectSyncSGIX_sig = {2767, "glXChannelRectSyncSGIX", 4, _glXChannelRectSyncSGIX_args};
 
 static const char * _glXJoinSwapGroupSGIX_args[3] = {"dpy", "drawable", "member"};
-static const trace::FunctionSig _glXJoinSwapGroupSGIX_sig = {2767, "glXJoinSwapGroupSGIX", 3, _glXJoinSwapGroupSGIX_args};
+static const trace::FunctionSig _glXJoinSwapGroupSGIX_sig = {2768, "glXJoinSwapGroupSGIX", 3, _glXJoinSwapGroupSGIX_args};
 
 static const char * _glXBindSwapBarrierSGIX_args[3] = {"dpy", "drawable", "barrier"};
-static const trace::FunctionSig _glXBindSwapBarrierSGIX_sig = {2768, "glXBindSwapBarrierSGIX", 3, _glXBindSwapBarrierSGIX_args};
+static const trace::FunctionSig _glXBindSwapBarrierSGIX_sig = {2769, "glXBindSwapBarrierSGIX", 3, _glXBindSwapBarrierSGIX_args};
 
 static const char * _glXQueryMaxSwapBarriersSGIX_args[3] = {"dpy", "screen", "max"};
-static const trace::FunctionSig _glXQueryMaxSwapBarriersSGIX_sig = {2769, "glXQueryMaxSwapBarriersSGIX", 3, _glXQueryMaxSwapBarriersSGIX_args};
+static const trace::FunctionSig _glXQueryMaxSwapBarriersSGIX_sig = {2770, "glXQueryMaxSwapBarriersSGIX", 3, _glXQueryMaxSwapBarriersSGIX_args};
 
 static const char * _glXCopySubBufferMESA_args[6] = {"dpy", "drawable", "x", "y", "width", "height"};
-static const trace::FunctionSig _glXCopySubBufferMESA_sig = {2770, "glXCopySubBufferMESA", 6, _glXCopySubBufferMESA_args};
+static const trace::FunctionSig _glXCopySubBufferMESA_sig = {2771, "glXCopySubBufferMESA", 6, _glXCopySubBufferMESA_args};
 
 static const char * _glXCreateGLXPixmapMESA_args[4] = {"dpy", "visual", "pixmap", "cmap"};
-static const trace::FunctionSig _glXCreateGLXPixmapMESA_sig = {2771, "glXCreateGLXPixmapMESA", 4, _glXCreateGLXPixmapMESA_args};
+static const trace::FunctionSig _glXCreateGLXPixmapMESA_sig = {2772, "glXCreateGLXPixmapMESA", 4, _glXCreateGLXPixmapMESA_args};
 
 static const char * _glXReleaseBuffersMESA_args[2] = {"dpy", "drawable"};
-static const trace::FunctionSig _glXReleaseBuffersMESA_sig = {2772, "glXReleaseBuffersMESA", 2, _glXReleaseBuffersMESA_args};
+static const trace::FunctionSig _glXReleaseBuffersMESA_sig = {2773, "glXReleaseBuffersMESA", 2, _glXReleaseBuffersMESA_args};
 
 static const char * _glXSet3DfxModeMESA_args[1] = {"mode"};
-static const trace::FunctionSig _glXSet3DfxModeMESA_sig = {2773, "glXSet3DfxModeMESA", 1, _glXSet3DfxModeMESA_args};
+static const trace::FunctionSig _glXSet3DfxModeMESA_sig = {2774, "glXSet3DfxModeMESA", 1, _glXSet3DfxModeMESA_args};
 
 static const char * _glXSwapIntervalMESA_args[1] = {"interval"};
-static const trace::FunctionSig _glXSwapIntervalMESA_sig = {2774, "glXSwapIntervalMESA", 1, _glXSwapIntervalMESA_args};
+static const trace::FunctionSig _glXSwapIntervalMESA_sig = {2775, "glXSwapIntervalMESA", 1, _glXSwapIntervalMESA_args};
 
 static const char ** _glXGetSwapIntervalMESA_args = NULL;
-static const trace::FunctionSig _glXGetSwapIntervalMESA_sig = {2775, "glXGetSwapIntervalMESA", 0, _glXGetSwapIntervalMESA_args};
+static const trace::FunctionSig _glXGetSwapIntervalMESA_sig = {2776, "glXGetSwapIntervalMESA", 0, _glXGetSwapIntervalMESA_args};
 
 static const char * _glXGetSyncValuesOML_args[5] = {"dpy", "drawable", "ust", "msc", "sbc"};
-static const trace::FunctionSig _glXGetSyncValuesOML_sig = {2776, "glXGetSyncValuesOML", 5, _glXGetSyncValuesOML_args};
+static const trace::FunctionSig _glXGetSyncValuesOML_sig = {2777, "glXGetSyncValuesOML", 5, _glXGetSyncValuesOML_args};
 
 static const char * _glXGetMscRateOML_args[4] = {"dpy", "drawable", "numerator", "denominator"};
-static const trace::FunctionSig _glXGetMscRateOML_sig = {2777, "glXGetMscRateOML", 4, _glXGetMscRateOML_args};
+static const trace::FunctionSig _glXGetMscRateOML_sig = {2778, "glXGetMscRateOML", 4, _glXGetMscRateOML_args};
 
 static const char * _glXSwapBuffersMscOML_args[5] = {"dpy", "drawable", "target_msc", "divisor", "remainder"};
-static const trace::FunctionSig _glXSwapBuffersMscOML_sig = {2778, "glXSwapBuffersMscOML", 5, _glXSwapBuffersMscOML_args};
+static const trace::FunctionSig _glXSwapBuffersMscOML_sig = {2779, "glXSwapBuffersMscOML", 5, _glXSwapBuffersMscOML_args};
 
 static const char * _glXWaitForMscOML_args[8] = {"dpy", "drawable", "target_msc", "divisor", "remainder", "ust", "msc", "sbc"};
-static const trace::FunctionSig _glXWaitForMscOML_sig = {2779, "glXWaitForMscOML", 8, _glXWaitForMscOML_args};
+static const trace::FunctionSig _glXWaitForMscOML_sig = {2780, "glXWaitForMscOML", 8, _glXWaitForMscOML_args};
 
 static const char * _glXWaitForSbcOML_args[6] = {"dpy", "drawable", "target_sbc", "ust", "msc", "sbc"};
-static const trace::FunctionSig _glXWaitForSbcOML_sig = {2780, "glXWaitForSbcOML", 6, _glXWaitForSbcOML_args};
+static const trace::FunctionSig _glXWaitForSbcOML_sig = {2781, "glXWaitForSbcOML", 6, _glXWaitForSbcOML_args};
 
 static const char * _glXGetAGPOffsetMESA_args[1] = {"pointer"};
-static const trace::FunctionSig _glXGetAGPOffsetMESA_sig = {2781, "glXGetAGPOffsetMESA", 1, _glXGetAGPOffsetMESA_args};
+static const trace::FunctionSig _glXGetAGPOffsetMESA_sig = {2782, "glXGetAGPOffsetMESA", 1, _glXGetAGPOffsetMESA_args};
 
 static const char * _glXBindTexImageEXT_args[4] = {"display", "drawable", "buffer", "attrib_list"};
-static const trace::FunctionSig _glXBindTexImageEXT_sig = {2782, "glXBindTexImageEXT", 4, _glXBindTexImageEXT_args};
+static const trace::FunctionSig _glXBindTexImageEXT_sig = {2783, "glXBindTexImageEXT", 4, _glXBindTexImageEXT_args};
 
 static const char * _glXReleaseTexImageEXT_args[3] = {"display", "drawable", "buffer"};
-static const trace::FunctionSig _glXReleaseTexImageEXT_sig = {2783, "glXReleaseTexImageEXT", 3, _glXReleaseTexImageEXT_args};
+static const trace::FunctionSig _glXReleaseTexImageEXT_sig = {2784, "glXReleaseTexImageEXT", 3, _glXReleaseTexImageEXT_args};
 
 static const char * _glXEnumerateVideoDevicesNV_args[3] = {"dpy", "screen", "nelements"};
-static const trace::FunctionSig _glXEnumerateVideoDevicesNV_sig = {2784, "glXEnumerateVideoDevicesNV", 3, _glXEnumerateVideoDevicesNV_args};
+static const trace::FunctionSig _glXEnumerateVideoDevicesNV_sig = {2785, "glXEnumerateVideoDevicesNV", 3, _glXEnumerateVideoDevicesNV_args};
 
 static const char * _glXBindVideoDeviceNV_args[4] = {"dpy", "video_slot", "video_device", "attrib_list"};
-static const trace::FunctionSig _glXBindVideoDeviceNV_sig = {2785, "glXBindVideoDeviceNV", 4, _glXBindVideoDeviceNV_args};
+static const trace::FunctionSig _glXBindVideoDeviceNV_sig = {2786, "glXBindVideoDeviceNV", 4, _glXBindVideoDeviceNV_args};
 
 static const char * _glXGetVideoDeviceNV_args[4] = {"dpy", "screen", "numVideoDevices", "pVideoDevice"};
-static const trace::FunctionSig _glXGetVideoDeviceNV_sig = {2786, "glXGetVideoDeviceNV", 4, _glXGetVideoDeviceNV_args};
+static const trace::FunctionSig _glXGetVideoDeviceNV_sig = {2787, "glXGetVideoDeviceNV", 4, _glXGetVideoDeviceNV_args};
 
 static const char * _glXReleaseVideoDeviceNV_args[3] = {"dpy", "screen", "VideoDevice"};
-static const trace::FunctionSig _glXReleaseVideoDeviceNV_sig = {2787, "glXReleaseVideoDeviceNV", 3, _glXReleaseVideoDeviceNV_args};
+static const trace::FunctionSig _glXReleaseVideoDeviceNV_sig = {2788, "glXReleaseVideoDeviceNV", 3, _glXReleaseVideoDeviceNV_args};
 
 static const char * _glXBindVideoImageNV_args[4] = {"dpy", "VideoDevice", "pbuf", "iVideoBuffer"};
-static const trace::FunctionSig _glXBindVideoImageNV_sig = {2788, "glXBindVideoImageNV", 4, _glXBindVideoImageNV_args};
+static const trace::FunctionSig _glXBindVideoImageNV_sig = {2789, "glXBindVideoImageNV", 4, _glXBindVideoImageNV_args};
 
 static const char * _glXReleaseVideoImageNV_args[2] = {"dpy", "pbuf"};
-static const trace::FunctionSig _glXReleaseVideoImageNV_sig = {2789, "glXReleaseVideoImageNV", 2, _glXReleaseVideoImageNV_args};
+static const trace::FunctionSig _glXReleaseVideoImageNV_sig = {2790, "glXReleaseVideoImageNV", 2, _glXReleaseVideoImageNV_args};
 
 static const char * _glXSendPbufferToVideoNV_args[5] = {"dpy", "pbuf", "iBufferType", "pulCounterPbuffer", "bBlock"};
-static const trace::FunctionSig _glXSendPbufferToVideoNV_sig = {2790, "glXSendPbufferToVideoNV", 5, _glXSendPbufferToVideoNV_args};
+static const trace::FunctionSig _glXSendPbufferToVideoNV_sig = {2791, "glXSendPbufferToVideoNV", 5, _glXSendPbufferToVideoNV_args};
 
 static const char * _glXGetVideoInfoNV_args[5] = {"dpy", "screen", "VideoDevice", "pulCounterOutputPbuffer", "pulCounterOutputVideo"};
-static const trace::FunctionSig _glXGetVideoInfoNV_sig = {2791, "glXGetVideoInfoNV", 5, _glXGetVideoInfoNV_args};
+static const trace::FunctionSig _glXGetVideoInfoNV_sig = {2792, "glXGetVideoInfoNV", 5, _glXGetVideoInfoNV_args};
 
 static const char * _glXJoinSwapGroupNV_args[3] = {"dpy", "drawable", "group"};
-static const trace::FunctionSig _glXJoinSwapGroupNV_sig = {2792, "glXJoinSwapGroupNV", 3, _glXJoinSwapGroupNV_args};
+static const trace::FunctionSig _glXJoinSwapGroupNV_sig = {2793, "glXJoinSwapGroupNV", 3, _glXJoinSwapGroupNV_args};
 
 static const char * _glXBindSwapBarrierNV_args[3] = {"dpy", "group", "barrier"};
-static const trace::FunctionSig _glXBindSwapBarrierNV_sig = {2793, "glXBindSwapBarrierNV", 3, _glXBindSwapBarrierNV_args};
+static const trace::FunctionSig _glXBindSwapBarrierNV_sig = {2794, "glXBindSwapBarrierNV", 3, _glXBindSwapBarrierNV_args};
 
 static const char * _glXQuerySwapGroupNV_args[4] = {"dpy", "drawable", "group", "barrier"};
-static const trace::FunctionSig _glXQuerySwapGroupNV_sig = {2794, "glXQuerySwapGroupNV", 4, _glXQuerySwapGroupNV_args};
+static const trace::FunctionSig _glXQuerySwapGroupNV_sig = {2795, "glXQuerySwapGroupNV", 4, _glXQuerySwapGroupNV_args};
 
 static const char * _glXQueryMaxSwapGroupsNV_args[4] = {"dpy", "screen", "maxGroups", "maxBarriers"};
-static const trace::FunctionSig _glXQueryMaxSwapGroupsNV_sig = {2795, "glXQueryMaxSwapGroupsNV", 4, _glXQueryMaxSwapGroupsNV_args};
+static const trace::FunctionSig _glXQueryMaxSwapGroupsNV_sig = {2796, "glXQueryMaxSwapGroupsNV", 4, _glXQueryMaxSwapGroupsNV_args};
 
 static const char * _glXQueryFrameCountNV_args[3] = {"dpy", "screen", "count"};
-static const trace::FunctionSig _glXQueryFrameCountNV_sig = {2796, "glXQueryFrameCountNV", 3, _glXQueryFrameCountNV_args};
+static const trace::FunctionSig _glXQueryFrameCountNV_sig = {2797, "glXQueryFrameCountNV", 3, _glXQueryFrameCountNV_args};
 
 static const char * _glXResetFrameCountNV_args[2] = {"dpy", "screen"};
-static const trace::FunctionSig _glXResetFrameCountNV_sig = {2797, "glXResetFrameCountNV", 2, _glXResetFrameCountNV_args};
+static const trace::FunctionSig _glXResetFrameCountNV_sig = {2798, "glXResetFrameCountNV", 2, _glXResetFrameCountNV_args};
 
 static const char * _glXBindVideoCaptureDeviceNV_args[3] = {"dpy", "video_capture_slot", "device"};
-static const trace::FunctionSig _glXBindVideoCaptureDeviceNV_sig = {2798, "glXBindVideoCaptureDeviceNV", 3, _glXBindVideoCaptureDeviceNV_args};
+static const trace::FunctionSig _glXBindVideoCaptureDeviceNV_sig = {2799, "glXBindVideoCaptureDeviceNV", 3, _glXBindVideoCaptureDeviceNV_args};
 
 static const char * _glXEnumerateVideoCaptureDevicesNV_args[3] = {"dpy", "screen", "nelements"};
-static const trace::FunctionSig _glXEnumerateVideoCaptureDevicesNV_sig = {2799, "glXEnumerateVideoCaptureDevicesNV", 3, _glXEnumerateVideoCaptureDevicesNV_args};
+static const trace::FunctionSig _glXEnumerateVideoCaptureDevicesNV_sig = {2800, "glXEnumerateVideoCaptureDevicesNV", 3, _glXEnumerateVideoCaptureDevicesNV_args};
 
 static const char * _glXLockVideoCaptureDeviceNV_args[2] = {"dpy", "device"};
-static const trace::FunctionSig _glXLockVideoCaptureDeviceNV_sig = {2800, "glXLockVideoCaptureDeviceNV", 2, _glXLockVideoCaptureDeviceNV_args};
+static const trace::FunctionSig _glXLockVideoCaptureDeviceNV_sig = {2801, "glXLockVideoCaptureDeviceNV", 2, _glXLockVideoCaptureDeviceNV_args};
 
 static const char * _glXQueryVideoCaptureDeviceNV_args[4] = {"dpy", "device", "attribute", "value"};
-static const trace::FunctionSig _glXQueryVideoCaptureDeviceNV_sig = {2801, "glXQueryVideoCaptureDeviceNV", 4, _glXQueryVideoCaptureDeviceNV_args};
+static const trace::FunctionSig _glXQueryVideoCaptureDeviceNV_sig = {2802, "glXQueryVideoCaptureDeviceNV", 4, _glXQueryVideoCaptureDeviceNV_args};
 
 static const char * _glXReleaseVideoCaptureDeviceNV_args[2] = {"dpy", "device"};
-static const trace::FunctionSig _glXReleaseVideoCaptureDeviceNV_sig = {2802, "glXReleaseVideoCaptureDeviceNV", 2, _glXReleaseVideoCaptureDeviceNV_args};
+static const trace::FunctionSig _glXReleaseVideoCaptureDeviceNV_sig = {2803, "glXReleaseVideoCaptureDeviceNV", 2, _glXReleaseVideoCaptureDeviceNV_args};
 
 static const char * _glXSwapIntervalEXT_args[3] = {"dpy", "drawable", "interval"};
-static const trace::FunctionSig _glXSwapIntervalEXT_sig = {2803, "glXSwapIntervalEXT", 3, _glXSwapIntervalEXT_args};
+static const trace::FunctionSig _glXSwapIntervalEXT_sig = {2804, "glXSwapIntervalEXT", 3, _glXSwapIntervalEXT_args};
 
 static const char * _glXCopyImageSubDataNV_args[18] = {"dpy", "srcCtx", "srcName", "srcTarget", "srcLevel", "srcX", "srcY", "srcZ", "dstCtx", "dstName", "dstTarget", "dstLevel", "dstX", "dstY", "dstZ", "width", "height", "depth"};
-static const trace::FunctionSig _glXCopyImageSubDataNV_sig = {2804, "glXCopyImageSubDataNV", 18, _glXCopyImageSubDataNV_args};
+static const trace::FunctionSig _glXCopyImageSubDataNV_sig = {2805, "glXCopyImageSubDataNV", 18, _glXCopyImageSubDataNV_args};
 
 static const char * _glXAllocateMemoryNV_args[4] = {"size", "readfreq", "writefreq", "priority"};
-static const trace::FunctionSig _glXAllocateMemoryNV_sig = {2805, "glXAllocateMemoryNV", 4, _glXAllocateMemoryNV_args};
+static const trace::FunctionSig _glXAllocateMemoryNV_sig = {2806, "glXAllocateMemoryNV", 4, _glXAllocateMemoryNV_args};
 
 static const char * _glXFreeMemoryNV_args[1] = {"pointer"};
-static const trace::FunctionSig _glXFreeMemoryNV_sig = {2806, "glXFreeMemoryNV", 1, _glXFreeMemoryNV_args};
+static const trace::FunctionSig _glXFreeMemoryNV_sig = {2807, "glXFreeMemoryNV", 1, _glXFreeMemoryNV_args};
 
 static const char * _glXGetProcAddressARB_args[1] = {"procName"};
-static const trace::FunctionSig _glXGetProcAddressARB_sig = {2807, "glXGetProcAddressARB", 1, _glXGetProcAddressARB_args};
+static const trace::FunctionSig _glXGetProcAddressARB_sig = {2808, "glXGetProcAddressARB", 1, _glXGetProcAddressARB_args};
 
 static const char * _glXGetProcAddress_args[1] = {"procName"};
-static const trace::FunctionSig _glXGetProcAddress_sig = {2808, "glXGetProcAddress", 1, _glXGetProcAddress_args};
+static const trace::FunctionSig _glXGetProcAddress_sig = {2809, "glXGetProcAddress", 1, _glXGetProcAddress_args};
 
 #endif // REGAL_SYS_GLX
 
 #if REGAL_SYS_WGL
 static const char * _wglCreateContext_args[1] = {"hdc"};
-static const trace::FunctionSig _wglCreateContext_sig = {2809, "wglCreateContext", 1, _wglCreateContext_args};
+static const trace::FunctionSig _wglCreateContext_sig = {2810, "wglCreateContext", 1, _wglCreateContext_args};
 
 static const char * _wglDeleteContext_args[1] = {"hglrc"};
-static const trace::FunctionSig _wglDeleteContext_sig = {2810, "wglDeleteContext", 1, _wglDeleteContext_args};
+static const trace::FunctionSig _wglDeleteContext_sig = {2811, "wglDeleteContext", 1, _wglDeleteContext_args};
 
 static const char ** _wglGetCurrentContext_args = NULL;
-static const trace::FunctionSig _wglGetCurrentContext_sig = {2811, "wglGetCurrentContext", 0, _wglGetCurrentContext_args};
+static const trace::FunctionSig _wglGetCurrentContext_sig = {2812, "wglGetCurrentContext", 0, _wglGetCurrentContext_args};
 
 static const char * _wglMakeCurrent_args[2] = {"hdc", "hglrc"};
-static const trace::FunctionSig _wglMakeCurrent_sig = {2812, "wglMakeCurrent", 2, _wglMakeCurrent_args};
+static const trace::FunctionSig _wglMakeCurrent_sig = {2813, "wglMakeCurrent", 2, _wglMakeCurrent_args};
 
 static const char * _wglCopyContext_args[3] = {"hglrcSrc", "hglrcDst", "mask"};
-static const trace::FunctionSig _wglCopyContext_sig = {2813, "wglCopyContext", 3, _wglCopyContext_args};
+static const trace::FunctionSig _wglCopyContext_sig = {2814, "wglCopyContext", 3, _wglCopyContext_args};
 
 static const char * _wglChoosePixelFormat_args[2] = {"hdc", "ppfd"};
-static const trace::FunctionSig _wglChoosePixelFormat_sig = {2814, "wglChoosePixelFormat", 2, _wglChoosePixelFormat_args};
+static const trace::FunctionSig _wglChoosePixelFormat_sig = {2815, "wglChoosePixelFormat", 2, _wglChoosePixelFormat_args};
 
 static const char * _wglDescribePixelFormat_args[4] = {"hdc", "iPixelFormat", "nBytes", "ppfd"};
-static const trace::FunctionSig _wglDescribePixelFormat_sig = {2815, "wglDescribePixelFormat", 4, _wglDescribePixelFormat_args};
+static const trace::FunctionSig _wglDescribePixelFormat_sig = {2816, "wglDescribePixelFormat", 4, _wglDescribePixelFormat_args};
 
 static const char ** _wglGetCurrentDC_args = NULL;
-static const trace::FunctionSig _wglGetCurrentDC_sig = {2816, "wglGetCurrentDC", 0, _wglGetCurrentDC_args};
+static const trace::FunctionSig _wglGetCurrentDC_sig = {2817, "wglGetCurrentDC", 0, _wglGetCurrentDC_args};
 
 static const char * _wglGetDefaultProcAddress_args[1] = {"lpszProc"};
-static const trace::FunctionSig _wglGetDefaultProcAddress_sig = {2817, "wglGetDefaultProcAddress", 1, _wglGetDefaultProcAddress_args};
+static const trace::FunctionSig _wglGetDefaultProcAddress_sig = {2818, "wglGetDefaultProcAddress", 1, _wglGetDefaultProcAddress_args};
 
 static const char * _wglGetPixelFormat_args[1] = {"hdc"};
-static const trace::FunctionSig _wglGetPixelFormat_sig = {2818, "wglGetPixelFormat", 1, _wglGetPixelFormat_args};
+static const trace::FunctionSig _wglGetPixelFormat_sig = {2819, "wglGetPixelFormat", 1, _wglGetPixelFormat_args};
 
 static const char * _wglSetPixelFormat_args[3] = {"hdc", "iPixelFormat", "ppfd"};
-static const trace::FunctionSig _wglSetPixelFormat_sig = {2819, "wglSetPixelFormat", 3, _wglSetPixelFormat_args};
+static const trace::FunctionSig _wglSetPixelFormat_sig = {2820, "wglSetPixelFormat", 3, _wglSetPixelFormat_args};
 
 static const char * _wglSwapBuffers_args[1] = {"hdc"};
-static const trace::FunctionSig _wglSwapBuffers_sig = {2820, "wglSwapBuffers", 1, _wglSwapBuffers_args};
+static const trace::FunctionSig _wglSwapBuffers_sig = {2821, "wglSwapBuffers", 1, _wglSwapBuffers_args};
 
 static const char * _wglShareLists_args[2] = {"hglrc1", "hglrc2"};
-static const trace::FunctionSig _wglShareLists_sig = {2821, "wglShareLists", 2, _wglShareLists_args};
+static const trace::FunctionSig _wglShareLists_sig = {2822, "wglShareLists", 2, _wglShareLists_args};
 
 static const char * _wglCreateLayerContext_args[2] = {"hdc", "iLayerPlane"};
-static const trace::FunctionSig _wglCreateLayerContext_sig = {2822, "wglCreateLayerContext", 2, _wglCreateLayerContext_args};
+static const trace::FunctionSig _wglCreateLayerContext_sig = {2823, "wglCreateLayerContext", 2, _wglCreateLayerContext_args};
 
 static const char * _wglDescribeLayerPlane_args[5] = {"hdc", "iPixelFormat", "iLayerPlane", "nBytes", "plpd"};
-static const trace::FunctionSig _wglDescribeLayerPlane_sig = {2823, "wglDescribeLayerPlane", 5, _wglDescribeLayerPlane_args};
+static const trace::FunctionSig _wglDescribeLayerPlane_sig = {2824, "wglDescribeLayerPlane", 5, _wglDescribeLayerPlane_args};
 
 static const char * _wglSetLayerPaletteEntries_args[5] = {"hdc", "iLayerPlane", "iStart", "cEntries", "pcr"};
-static const trace::FunctionSig _wglSetLayerPaletteEntries_sig = {2824, "wglSetLayerPaletteEntries", 5, _wglSetLayerPaletteEntries_args};
+static const trace::FunctionSig _wglSetLayerPaletteEntries_sig = {2825, "wglSetLayerPaletteEntries", 5, _wglSetLayerPaletteEntries_args};
 
 static const char * _wglGetLayerPaletteEntries_args[5] = {"hdc", "iLayerPlane", "iStart", "cEntries", "pcr"};
-static const trace::FunctionSig _wglGetLayerPaletteEntries_sig = {2825, "wglGetLayerPaletteEntries", 5, _wglGetLayerPaletteEntries_args};
+static const trace::FunctionSig _wglGetLayerPaletteEntries_sig = {2826, "wglGetLayerPaletteEntries", 5, _wglGetLayerPaletteEntries_args};
 
 static const char * _wglRealizeLayerPalette_args[3] = {"hdc", "iLayerPlane", "bRealize"};
-static const trace::FunctionSig _wglRealizeLayerPalette_sig = {2826, "wglRealizeLayerPalette", 3, _wglRealizeLayerPalette_args};
+static const trace::FunctionSig _wglRealizeLayerPalette_sig = {2827, "wglRealizeLayerPalette", 3, _wglRealizeLayerPalette_args};
 
 static const char * _wglSwapLayerBuffers_args[2] = {"hdc", "fuPlanes"};
-static const trace::FunctionSig _wglSwapLayerBuffers_sig = {2827, "wglSwapLayerBuffers", 2, _wglSwapLayerBuffers_args};
+static const trace::FunctionSig _wglSwapLayerBuffers_sig = {2828, "wglSwapLayerBuffers", 2, _wglSwapLayerBuffers_args};
 
 static const char * _wglUseFontBitmapsA_args[4] = {"hdc", "first", "count", "listBase"};
-static const trace::FunctionSig _wglUseFontBitmapsA_sig = {2828, "wglUseFontBitmapsA", 4, _wglUseFontBitmapsA_args};
+static const trace::FunctionSig _wglUseFontBitmapsA_sig = {2829, "wglUseFontBitmapsA", 4, _wglUseFontBitmapsA_args};
 
 static const char * _wglUseFontBitmapsW_args[4] = {"hdc", "first", "count", "listBase"};
-static const trace::FunctionSig _wglUseFontBitmapsW_sig = {2829, "wglUseFontBitmapsW", 4, _wglUseFontBitmapsW_args};
+static const trace::FunctionSig _wglUseFontBitmapsW_sig = {2830, "wglUseFontBitmapsW", 4, _wglUseFontBitmapsW_args};
 
 static const char * _wglSwapMultipleBuffers_args[2] = {"n", "ps"};
-static const trace::FunctionSig _wglSwapMultipleBuffers_sig = {2830, "wglSwapMultipleBuffers", 2, _wglSwapMultipleBuffers_args};
+static const trace::FunctionSig _wglSwapMultipleBuffers_sig = {2831, "wglSwapMultipleBuffers", 2, _wglSwapMultipleBuffers_args};
 
 static const char * _wglUseFontOutlinesA_args[8] = {"hdc", "first", "count", "listBase", "deviation", "extrusion", "format", "lpgmf"};
-static const trace::FunctionSig _wglUseFontOutlinesA_sig = {2831, "wglUseFontOutlinesA", 8, _wglUseFontOutlinesA_args};
+static const trace::FunctionSig _wglUseFontOutlinesA_sig = {2832, "wglUseFontOutlinesA", 8, _wglUseFontOutlinesA_args};
 
 static const char * _wglUseFontOutlinesW_args[8] = {"hdc", "first", "count", "listBase", "deviation", "extrusion", "format", "lpgmf"};
-static const trace::FunctionSig _wglUseFontOutlinesW_sig = {2832, "wglUseFontOutlinesW", 8, _wglUseFontOutlinesW_args};
+static const trace::FunctionSig _wglUseFontOutlinesW_sig = {2833, "wglUseFontOutlinesW", 8, _wglUseFontOutlinesW_args};
 
 static const char * _wglCreateBufferRegionARB_args[3] = {"hDC", "iLayerPlane", "uType"};
-static const trace::FunctionSig _wglCreateBufferRegionARB_sig = {2833, "wglCreateBufferRegionARB", 3, _wglCreateBufferRegionARB_args};
+static const trace::FunctionSig _wglCreateBufferRegionARB_sig = {2834, "wglCreateBufferRegionARB", 3, _wglCreateBufferRegionARB_args};
 
 static const char * _wglDeleteBufferRegionARB_args[1] = {"hRegion"};
-static const trace::FunctionSig _wglDeleteBufferRegionARB_sig = {2834, "wglDeleteBufferRegionARB", 1, _wglDeleteBufferRegionARB_args};
+static const trace::FunctionSig _wglDeleteBufferRegionARB_sig = {2835, "wglDeleteBufferRegionARB", 1, _wglDeleteBufferRegionARB_args};
 
 static const char * _wglSaveBufferRegionARB_args[5] = {"hRegion", "x", "y", "width", "height"};
-static const trace::FunctionSig _wglSaveBufferRegionARB_sig = {2835, "wglSaveBufferRegionARB", 5, _wglSaveBufferRegionARB_args};
+static const trace::FunctionSig _wglSaveBufferRegionARB_sig = {2836, "wglSaveBufferRegionARB", 5, _wglSaveBufferRegionARB_args};
 
 static const char * _wglRestoreBufferRegionARB_args[7] = {"hRegion", "x", "y", "width", "height", "xSrc", "ySrc"};
-static const trace::FunctionSig _wglRestoreBufferRegionARB_sig = {2836, "wglRestoreBufferRegionARB", 7, _wglRestoreBufferRegionARB_args};
+static const trace::FunctionSig _wglRestoreBufferRegionARB_sig = {2837, "wglRestoreBufferRegionARB", 7, _wglRestoreBufferRegionARB_args};
 
 static const char * _wglGetExtensionsStringARB_args[1] = {"hdc"};
-static const trace::FunctionSig _wglGetExtensionsStringARB_sig = {2837, "wglGetExtensionsStringARB", 1, _wglGetExtensionsStringARB_args};
+static const trace::FunctionSig _wglGetExtensionsStringARB_sig = {2838, "wglGetExtensionsStringARB", 1, _wglGetExtensionsStringARB_args};
 
 static const char * _wglGetPixelFormatAttribivARB_args[6] = {"hdc", "iPixelFormat", "iLayerPlane", "nAttributes", "piAttributes", "piValues"};
-static const trace::FunctionSig _wglGetPixelFormatAttribivARB_sig = {2838, "wglGetPixelFormatAttribivARB", 6, _wglGetPixelFormatAttribivARB_args};
+static const trace::FunctionSig _wglGetPixelFormatAttribivARB_sig = {2839, "wglGetPixelFormatAttribivARB", 6, _wglGetPixelFormatAttribivARB_args};
 
 static const char * _wglGetPixelFormatAttribfvARB_args[6] = {"hdc", "iPixelFormat", "iLayerPlane", "nAttributes", "piAttributes", "pfValues"};
-static const trace::FunctionSig _wglGetPixelFormatAttribfvARB_sig = {2839, "wglGetPixelFormatAttribfvARB", 6, _wglGetPixelFormatAttribfvARB_args};
+static const trace::FunctionSig _wglGetPixelFormatAttribfvARB_sig = {2840, "wglGetPixelFormatAttribfvARB", 6, _wglGetPixelFormatAttribfvARB_args};
 
 static const char * _wglChoosePixelFormatARB_args[6] = {"hdc", "piAttribIList", "pfAttribFList", "nMaxFormats", "piFormats", "nNumFormats"};
-static const trace::FunctionSig _wglChoosePixelFormatARB_sig = {2840, "wglChoosePixelFormatARB", 6, _wglChoosePixelFormatARB_args};
+static const trace::FunctionSig _wglChoosePixelFormatARB_sig = {2841, "wglChoosePixelFormatARB", 6, _wglChoosePixelFormatARB_args};
 
 static const char * _wglMakeContextCurrentARB_args[3] = {"hDrawDC", "hReadDC", "hglrc"};
-static const trace::FunctionSig _wglMakeContextCurrentARB_sig = {2841, "wglMakeContextCurrentARB", 3, _wglMakeContextCurrentARB_args};
+static const trace::FunctionSig _wglMakeContextCurrentARB_sig = {2842, "wglMakeContextCurrentARB", 3, _wglMakeContextCurrentARB_args};
 
 static const char ** _wglGetCurrentReadDCARB_args = NULL;
-static const trace::FunctionSig _wglGetCurrentReadDCARB_sig = {2842, "wglGetCurrentReadDCARB", 0, _wglGetCurrentReadDCARB_args};
+static const trace::FunctionSig _wglGetCurrentReadDCARB_sig = {2843, "wglGetCurrentReadDCARB", 0, _wglGetCurrentReadDCARB_args};
 
 static const char * _wglCreatePbufferARB_args[5] = {"hDC", "iPixelFormat", "iWidth", "iHeight", "piAttribList"};
-static const trace::FunctionSig _wglCreatePbufferARB_sig = {2843, "wglCreatePbufferARB", 5, _wglCreatePbufferARB_args};
+static const trace::FunctionSig _wglCreatePbufferARB_sig = {2844, "wglCreatePbufferARB", 5, _wglCreatePbufferARB_args};
 
 static const char * _wglGetPbufferDCARB_args[1] = {"hPbuffer"};
-static const trace::FunctionSig _wglGetPbufferDCARB_sig = {2844, "wglGetPbufferDCARB", 1, _wglGetPbufferDCARB_args};
+static const trace::FunctionSig _wglGetPbufferDCARB_sig = {2845, "wglGetPbufferDCARB", 1, _wglGetPbufferDCARB_args};
 
 static const char * _wglReleasePbufferDCARB_args[2] = {"hPbuffer", "hDC"};
-static const trace::FunctionSig _wglReleasePbufferDCARB_sig = {2845, "wglReleasePbufferDCARB", 2, _wglReleasePbufferDCARB_args};
+static const trace::FunctionSig _wglReleasePbufferDCARB_sig = {2846, "wglReleasePbufferDCARB", 2, _wglReleasePbufferDCARB_args};
 
 static const char * _wglDestroyPbufferARB_args[1] = {"hPbuffer"};
-static const trace::FunctionSig _wglDestroyPbufferARB_sig = {2846, "wglDestroyPbufferARB", 1, _wglDestroyPbufferARB_args};
+static const trace::FunctionSig _wglDestroyPbufferARB_sig = {2847, "wglDestroyPbufferARB", 1, _wglDestroyPbufferARB_args};
 
 static const char * _wglQueryPbufferARB_args[3] = {"hPbuffer", "iAttribute", "piValue"};
-static const trace::FunctionSig _wglQueryPbufferARB_sig = {2847, "wglQueryPbufferARB", 3, _wglQueryPbufferARB_args};
+static const trace::FunctionSig _wglQueryPbufferARB_sig = {2848, "wglQueryPbufferARB", 3, _wglQueryPbufferARB_args};
 
 static const char * _wglBindTexImageARB_args[2] = {"hPbuffer", "iBuffer"};
-static const trace::FunctionSig _wglBindTexImageARB_sig = {2848, "wglBindTexImageARB", 2, _wglBindTexImageARB_args};
+static const trace::FunctionSig _wglBindTexImageARB_sig = {2849, "wglBindTexImageARB", 2, _wglBindTexImageARB_args};
 
 static const char * _wglReleaseTexImageARB_args[2] = {"hPbuffer", "iBuffer"};
-static const trace::FunctionSig _wglReleaseTexImageARB_sig = {2849, "wglReleaseTexImageARB", 2, _wglReleaseTexImageARB_args};
+static const trace::FunctionSig _wglReleaseTexImageARB_sig = {2850, "wglReleaseTexImageARB", 2, _wglReleaseTexImageARB_args};
 
 static const char * _wglSetPbufferAttribARB_args[2] = {"hPbuffer", "piAttribList"};
-static const trace::FunctionSig _wglSetPbufferAttribARB_sig = {2850, "wglSetPbufferAttribARB", 2, _wglSetPbufferAttribARB_args};
+static const trace::FunctionSig _wglSetPbufferAttribARB_sig = {2851, "wglSetPbufferAttribARB", 2, _wglSetPbufferAttribARB_args};
 
 static const char * _wglCreateContextAttribsARB_args[3] = {"hDC", "hShareContext", "attribList"};
-static const trace::FunctionSig _wglCreateContextAttribsARB_sig = {2851, "wglCreateContextAttribsARB", 3, _wglCreateContextAttribsARB_args};
+static const trace::FunctionSig _wglCreateContextAttribsARB_sig = {2852, "wglCreateContextAttribsARB", 3, _wglCreateContextAttribsARB_args};
 
 static const char * _wglCreateDisplayColorTableEXT_args[1] = {"id"};
-static const trace::FunctionSig _wglCreateDisplayColorTableEXT_sig = {2852, "wglCreateDisplayColorTableEXT", 1, _wglCreateDisplayColorTableEXT_args};
+static const trace::FunctionSig _wglCreateDisplayColorTableEXT_sig = {2853, "wglCreateDisplayColorTableEXT", 1, _wglCreateDisplayColorTableEXT_args};
 
 static const char * _wglLoadDisplayColorTableEXT_args[2] = {"table", "length"};
-static const trace::FunctionSig _wglLoadDisplayColorTableEXT_sig = {2853, "wglLoadDisplayColorTableEXT", 2, _wglLoadDisplayColorTableEXT_args};
+static const trace::FunctionSig _wglLoadDisplayColorTableEXT_sig = {2854, "wglLoadDisplayColorTableEXT", 2, _wglLoadDisplayColorTableEXT_args};
 
 static const char * _wglBindDisplayColorTableEXT_args[1] = {"id"};
-static const trace::FunctionSig _wglBindDisplayColorTableEXT_sig = {2854, "wglBindDisplayColorTableEXT", 1, _wglBindDisplayColorTableEXT_args};
+static const trace::FunctionSig _wglBindDisplayColorTableEXT_sig = {2855, "wglBindDisplayColorTableEXT", 1, _wglBindDisplayColorTableEXT_args};
 
 static const char * _wglDestroyDisplayColorTableEXT_args[1] = {"id"};
-static const trace::FunctionSig _wglDestroyDisplayColorTableEXT_sig = {2855, "wglDestroyDisplayColorTableEXT", 1, _wglDestroyDisplayColorTableEXT_args};
+static const trace::FunctionSig _wglDestroyDisplayColorTableEXT_sig = {2856, "wglDestroyDisplayColorTableEXT", 1, _wglDestroyDisplayColorTableEXT_args};
 
 static const char ** _wglGetExtensionsStringEXT_args = NULL;
-static const trace::FunctionSig _wglGetExtensionsStringEXT_sig = {2856, "wglGetExtensionsStringEXT", 0, _wglGetExtensionsStringEXT_args};
+static const trace::FunctionSig _wglGetExtensionsStringEXT_sig = {2857, "wglGetExtensionsStringEXT", 0, _wglGetExtensionsStringEXT_args};
 
 static const char * _wglMakeContextCurrentEXT_args[3] = {"hDrawDC", "hReadDC", "hglrc"};
-static const trace::FunctionSig _wglMakeContextCurrentEXT_sig = {2857, "wglMakeContextCurrentEXT", 3, _wglMakeContextCurrentEXT_args};
+static const trace::FunctionSig _wglMakeContextCurrentEXT_sig = {2858, "wglMakeContextCurrentEXT", 3, _wglMakeContextCurrentEXT_args};
 
 static const char ** _wglGetCurrentReadDCEXT_args = NULL;
-static const trace::FunctionSig _wglGetCurrentReadDCEXT_sig = {2858, "wglGetCurrentReadDCEXT", 0, _wglGetCurrentReadDCEXT_args};
+static const trace::FunctionSig _wglGetCurrentReadDCEXT_sig = {2859, "wglGetCurrentReadDCEXT", 0, _wglGetCurrentReadDCEXT_args};
 
 static const char * _wglCreatePbufferEXT_args[5] = {"hDC", "iPixelFormat", "iWidth", "iHeight", "piAttribList"};
-static const trace::FunctionSig _wglCreatePbufferEXT_sig = {2859, "wglCreatePbufferEXT", 5, _wglCreatePbufferEXT_args};
+static const trace::FunctionSig _wglCreatePbufferEXT_sig = {2860, "wglCreatePbufferEXT", 5, _wglCreatePbufferEXT_args};
 
 static const char * _wglGetPbufferDCEXT_args[1] = {"hPbuffer"};
-static const trace::FunctionSig _wglGetPbufferDCEXT_sig = {2860, "wglGetPbufferDCEXT", 1, _wglGetPbufferDCEXT_args};
+static const trace::FunctionSig _wglGetPbufferDCEXT_sig = {2861, "wglGetPbufferDCEXT", 1, _wglGetPbufferDCEXT_args};
 
 static const char * _wglReleasePbufferDCEXT_args[2] = {"hPbuffer", "hDC"};
-static const trace::FunctionSig _wglReleasePbufferDCEXT_sig = {2861, "wglReleasePbufferDCEXT", 2, _wglReleasePbufferDCEXT_args};
+static const trace::FunctionSig _wglReleasePbufferDCEXT_sig = {2862, "wglReleasePbufferDCEXT", 2, _wglReleasePbufferDCEXT_args};
 
 static const char * _wglDestroyPbufferEXT_args[1] = {"hPbuffer"};
-static const trace::FunctionSig _wglDestroyPbufferEXT_sig = {2862, "wglDestroyPbufferEXT", 1, _wglDestroyPbufferEXT_args};
+static const trace::FunctionSig _wglDestroyPbufferEXT_sig = {2863, "wglDestroyPbufferEXT", 1, _wglDestroyPbufferEXT_args};
 
 static const char * _wglQueryPbufferEXT_args[3] = {"hPbuffer", "iAttribute", "piValue"};
-static const trace::FunctionSig _wglQueryPbufferEXT_sig = {2863, "wglQueryPbufferEXT", 3, _wglQueryPbufferEXT_args};
+static const trace::FunctionSig _wglQueryPbufferEXT_sig = {2864, "wglQueryPbufferEXT", 3, _wglQueryPbufferEXT_args};
 
 static const char * _wglGetPixelFormatAttribivEXT_args[6] = {"hdc", "iPixelFormat", "iLayerPlane", "nAttributes", "piAttributes", "piValues"};
-static const trace::FunctionSig _wglGetPixelFormatAttribivEXT_sig = {2864, "wglGetPixelFormatAttribivEXT", 6, _wglGetPixelFormatAttribivEXT_args};
+static const trace::FunctionSig _wglGetPixelFormatAttribivEXT_sig = {2865, "wglGetPixelFormatAttribivEXT", 6, _wglGetPixelFormatAttribivEXT_args};
 
 static const char * _wglGetPixelFormatAttribfvEXT_args[6] = {"hdc", "iPixelFormat", "iLayerPlane", "nAttributes", "piAttributes", "pfValues"};
-static const trace::FunctionSig _wglGetPixelFormatAttribfvEXT_sig = {2865, "wglGetPixelFormatAttribfvEXT", 6, _wglGetPixelFormatAttribfvEXT_args};
+static const trace::FunctionSig _wglGetPixelFormatAttribfvEXT_sig = {2866, "wglGetPixelFormatAttribfvEXT", 6, _wglGetPixelFormatAttribfvEXT_args};
 
 static const char * _wglChoosePixelFormatEXT_args[6] = {"hdc", "piAttribIList", "pfAttribFList", "nMaxFormats", "piFormats", "nNumFormats"};
-static const trace::FunctionSig _wglChoosePixelFormatEXT_sig = {2866, "wglChoosePixelFormatEXT", 6, _wglChoosePixelFormatEXT_args};
+static const trace::FunctionSig _wglChoosePixelFormatEXT_sig = {2867, "wglChoosePixelFormatEXT", 6, _wglChoosePixelFormatEXT_args};
 
 static const char * _wglSwapIntervalEXT_args[1] = {"interval"};
-static const trace::FunctionSig _wglSwapIntervalEXT_sig = {2867, "wglSwapIntervalEXT", 1, _wglSwapIntervalEXT_args};
+static const trace::FunctionSig _wglSwapIntervalEXT_sig = {2868, "wglSwapIntervalEXT", 1, _wglSwapIntervalEXT_args};
 
 static const char ** _wglGetSwapIntervalEXT_args = NULL;
-static const trace::FunctionSig _wglGetSwapIntervalEXT_sig = {2868, "wglGetSwapIntervalEXT", 0, _wglGetSwapIntervalEXT_args};
+static const trace::FunctionSig _wglGetSwapIntervalEXT_sig = {2869, "wglGetSwapIntervalEXT", 0, _wglGetSwapIntervalEXT_args};
 
 static const char * _wglAllocateMemoryNV_args[4] = {"size", "readfreq", "writefreq", "priority"};
-static const trace::FunctionSig _wglAllocateMemoryNV_sig = {2869, "wglAllocateMemoryNV", 4, _wglAllocateMemoryNV_args};
+static const trace::FunctionSig _wglAllocateMemoryNV_sig = {2870, "wglAllocateMemoryNV", 4, _wglAllocateMemoryNV_args};
 
 static const char * _wglFreeMemoryNV_args[1] = {"pointer"};
-static const trace::FunctionSig _wglFreeMemoryNV_sig = {2870, "wglFreeMemoryNV", 1, _wglFreeMemoryNV_args};
+static const trace::FunctionSig _wglFreeMemoryNV_sig = {2871, "wglFreeMemoryNV", 1, _wglFreeMemoryNV_args};
 
 static const char * _wglGetSyncValuesOML_args[4] = {"hdc", "ust", "msc", "sbc"};
-static const trace::FunctionSig _wglGetSyncValuesOML_sig = {2871, "wglGetSyncValuesOML", 4, _wglGetSyncValuesOML_args};
+static const trace::FunctionSig _wglGetSyncValuesOML_sig = {2872, "wglGetSyncValuesOML", 4, _wglGetSyncValuesOML_args};
 
 static const char * _wglGetMscRateOML_args[3] = {"hdc", "numerator", "denominator"};
-static const trace::FunctionSig _wglGetMscRateOML_sig = {2872, "wglGetMscRateOML", 3, _wglGetMscRateOML_args};
+static const trace::FunctionSig _wglGetMscRateOML_sig = {2873, "wglGetMscRateOML", 3, _wglGetMscRateOML_args};
 
 static const char * _wglSwapBuffersMscOML_args[4] = {"hdc", "target_msc", "divisor", "remainder"};
-static const trace::FunctionSig _wglSwapBuffersMscOML_sig = {2873, "wglSwapBuffersMscOML", 4, _wglSwapBuffersMscOML_args};
+static const trace::FunctionSig _wglSwapBuffersMscOML_sig = {2874, "wglSwapBuffersMscOML", 4, _wglSwapBuffersMscOML_args};
 
 static const char * _wglSwapLayerBuffersMscOML_args[5] = {"hdc", "fuPlanes", "target_msc", "divisor", "remainder"};
-static const trace::FunctionSig _wglSwapLayerBuffersMscOML_sig = {2874, "wglSwapLayerBuffersMscOML", 5, _wglSwapLayerBuffersMscOML_args};
+static const trace::FunctionSig _wglSwapLayerBuffersMscOML_sig = {2875, "wglSwapLayerBuffersMscOML", 5, _wglSwapLayerBuffersMscOML_args};
 
 static const char * _wglWaitForMscOML_args[7] = {"hdc", "target_msc", "divisor", "remainder", "ust", "msc", "sbc"};
-static const trace::FunctionSig _wglWaitForMscOML_sig = {2875, "wglWaitForMscOML", 7, _wglWaitForMscOML_args};
+static const trace::FunctionSig _wglWaitForMscOML_sig = {2876, "wglWaitForMscOML", 7, _wglWaitForMscOML_args};
 
 static const char * _wglWaitForSbcOML_args[5] = {"hdc", "target_sbc", "ust", "msc", "sbc"};
-static const trace::FunctionSig _wglWaitForSbcOML_sig = {2876, "wglWaitForSbcOML", 5, _wglWaitForSbcOML_args};
+static const trace::FunctionSig _wglWaitForSbcOML_sig = {2877, "wglWaitForSbcOML", 5, _wglWaitForSbcOML_args};
 
 static const char * _wglGetDigitalVideoParametersI3D_args[3] = {"hDC", "iAttribute", "piValue"};
-static const trace::FunctionSig _wglGetDigitalVideoParametersI3D_sig = {2877, "wglGetDigitalVideoParametersI3D", 3, _wglGetDigitalVideoParametersI3D_args};
+static const trace::FunctionSig _wglGetDigitalVideoParametersI3D_sig = {2878, "wglGetDigitalVideoParametersI3D", 3, _wglGetDigitalVideoParametersI3D_args};
 
 static const char * _wglSetDigitalVideoParametersI3D_args[3] = {"hDC", "iAttribute", "piValue"};
-static const trace::FunctionSig _wglSetDigitalVideoParametersI3D_sig = {2878, "wglSetDigitalVideoParametersI3D", 3, _wglSetDigitalVideoParametersI3D_args};
+static const trace::FunctionSig _wglSetDigitalVideoParametersI3D_sig = {2879, "wglSetDigitalVideoParametersI3D", 3, _wglSetDigitalVideoParametersI3D_args};
 
 static const char * _wglGetGammaTableParametersI3D_args[3] = {"hDC", "iAttribute", "piValue"};
-static const trace::FunctionSig _wglGetGammaTableParametersI3D_sig = {2879, "wglGetGammaTableParametersI3D", 3, _wglGetGammaTableParametersI3D_args};
+static const trace::FunctionSig _wglGetGammaTableParametersI3D_sig = {2880, "wglGetGammaTableParametersI3D", 3, _wglGetGammaTableParametersI3D_args};
 
 static const char * _wglSetGammaTableParametersI3D_args[3] = {"hDC", "iAttribute", "piValue"};
-static const trace::FunctionSig _wglSetGammaTableParametersI3D_sig = {2880, "wglSetGammaTableParametersI3D", 3, _wglSetGammaTableParametersI3D_args};
+static const trace::FunctionSig _wglSetGammaTableParametersI3D_sig = {2881, "wglSetGammaTableParametersI3D", 3, _wglSetGammaTableParametersI3D_args};
 
 static const char * _wglGetGammaTableI3D_args[5] = {"hDC", "iEntries", "puRed", "puGreen", "puBlue"};
-static const trace::FunctionSig _wglGetGammaTableI3D_sig = {2881, "wglGetGammaTableI3D", 5, _wglGetGammaTableI3D_args};
+static const trace::FunctionSig _wglGetGammaTableI3D_sig = {2882, "wglGetGammaTableI3D", 5, _wglGetGammaTableI3D_args};
 
 static const char * _wglSetGammaTableI3D_args[5] = {"hDC", "iEntries", "puRed", "puGreen", "puBlue"};
-static const trace::FunctionSig _wglSetGammaTableI3D_sig = {2882, "wglSetGammaTableI3D", 5, _wglSetGammaTableI3D_args};
+static const trace::FunctionSig _wglSetGammaTableI3D_sig = {2883, "wglSetGammaTableI3D", 5, _wglSetGammaTableI3D_args};
 
 static const char * _wglEnableGenlockI3D_args[1] = {"hDC"};
-static const trace::FunctionSig _wglEnableGenlockI3D_sig = {2883, "wglEnableGenlockI3D", 1, _wglEnableGenlockI3D_args};
+static const trace::FunctionSig _wglEnableGenlockI3D_sig = {2884, "wglEnableGenlockI3D", 1, _wglEnableGenlockI3D_args};
 
 static const char * _wglDisableGenlockI3D_args[1] = {"hDC"};
-static const trace::FunctionSig _wglDisableGenlockI3D_sig = {2884, "wglDisableGenlockI3D", 1, _wglDisableGenlockI3D_args};
+static const trace::FunctionSig _wglDisableGenlockI3D_sig = {2885, "wglDisableGenlockI3D", 1, _wglDisableGenlockI3D_args};
 
 static const char * _wglIsEnabledGenlockI3D_args[2] = {"hDC", "pFlag"};
-static const trace::FunctionSig _wglIsEnabledGenlockI3D_sig = {2885, "wglIsEnabledGenlockI3D", 2, _wglIsEnabledGenlockI3D_args};
+static const trace::FunctionSig _wglIsEnabledGenlockI3D_sig = {2886, "wglIsEnabledGenlockI3D", 2, _wglIsEnabledGenlockI3D_args};
 
 static const char * _wglGenlockSourceI3D_args[2] = {"hDC", "uSource"};
-static const trace::FunctionSig _wglGenlockSourceI3D_sig = {2886, "wglGenlockSourceI3D", 2, _wglGenlockSourceI3D_args};
+static const trace::FunctionSig _wglGenlockSourceI3D_sig = {2887, "wglGenlockSourceI3D", 2, _wglGenlockSourceI3D_args};
 
 static const char * _wglGetGenlockSourceI3D_args[2] = {"hDC", "uSource"};
-static const trace::FunctionSig _wglGetGenlockSourceI3D_sig = {2887, "wglGetGenlockSourceI3D", 2, _wglGetGenlockSourceI3D_args};
+static const trace::FunctionSig _wglGetGenlockSourceI3D_sig = {2888, "wglGetGenlockSourceI3D", 2, _wglGetGenlockSourceI3D_args};
 
 static const char * _wglGenlockSourceEdgeI3D_args[2] = {"hDC", "uEdge"};
-static const trace::FunctionSig _wglGenlockSourceEdgeI3D_sig = {2888, "wglGenlockSourceEdgeI3D", 2, _wglGenlockSourceEdgeI3D_args};
+static const trace::FunctionSig _wglGenlockSourceEdgeI3D_sig = {2889, "wglGenlockSourceEdgeI3D", 2, _wglGenlockSourceEdgeI3D_args};
 
 static const char * _wglGetGenlockSourceEdgeI3D_args[2] = {"hDC", "uEdge"};
-static const trace::FunctionSig _wglGetGenlockSourceEdgeI3D_sig = {2889, "wglGetGenlockSourceEdgeI3D", 2, _wglGetGenlockSourceEdgeI3D_args};
+static const trace::FunctionSig _wglGetGenlockSourceEdgeI3D_sig = {2890, "wglGetGenlockSourceEdgeI3D", 2, _wglGetGenlockSourceEdgeI3D_args};
 
 static const char * _wglGenlockSampleRateI3D_args[2] = {"hDC", "uRate"};
-static const trace::FunctionSig _wglGenlockSampleRateI3D_sig = {2890, "wglGenlockSampleRateI3D", 2, _wglGenlockSampleRateI3D_args};
+static const trace::FunctionSig _wglGenlockSampleRateI3D_sig = {2891, "wglGenlockSampleRateI3D", 2, _wglGenlockSampleRateI3D_args};
 
 static const char * _wglGetGenlockSampleRateI3D_args[2] = {"hDC", "uRate"};
-static const trace::FunctionSig _wglGetGenlockSampleRateI3D_sig = {2891, "wglGetGenlockSampleRateI3D", 2, _wglGetGenlockSampleRateI3D_args};
+static const trace::FunctionSig _wglGetGenlockSampleRateI3D_sig = {2892, "wglGetGenlockSampleRateI3D", 2, _wglGetGenlockSampleRateI3D_args};
 
 static const char * _wglGenlockSourceDelayI3D_args[2] = {"hDC", "uDelay"};
-static const trace::FunctionSig _wglGenlockSourceDelayI3D_sig = {2892, "wglGenlockSourceDelayI3D", 2, _wglGenlockSourceDelayI3D_args};
+static const trace::FunctionSig _wglGenlockSourceDelayI3D_sig = {2893, "wglGenlockSourceDelayI3D", 2, _wglGenlockSourceDelayI3D_args};
 
 static const char * _wglGetGenlockSourceDelayI3D_args[2] = {"hDC", "uDelay"};
-static const trace::FunctionSig _wglGetGenlockSourceDelayI3D_sig = {2893, "wglGetGenlockSourceDelayI3D", 2, _wglGetGenlockSourceDelayI3D_args};
+static const trace::FunctionSig _wglGetGenlockSourceDelayI3D_sig = {2894, "wglGetGenlockSourceDelayI3D", 2, _wglGetGenlockSourceDelayI3D_args};
 
 static const char * _wglQueryGenlockMaxSourceDelayI3D_args[3] = {"hDC", "uMaxLineDelay", "uMaxPixelDelay"};
-static const trace::FunctionSig _wglQueryGenlockMaxSourceDelayI3D_sig = {2894, "wglQueryGenlockMaxSourceDelayI3D", 3, _wglQueryGenlockMaxSourceDelayI3D_args};
+static const trace::FunctionSig _wglQueryGenlockMaxSourceDelayI3D_sig = {2895, "wglQueryGenlockMaxSourceDelayI3D", 3, _wglQueryGenlockMaxSourceDelayI3D_args};
 
 static const char * _wglCreateImageBufferI3D_args[3] = {"hDC", "dwSize", "uFlags"};
-static const trace::FunctionSig _wglCreateImageBufferI3D_sig = {2895, "wglCreateImageBufferI3D", 3, _wglCreateImageBufferI3D_args};
+static const trace::FunctionSig _wglCreateImageBufferI3D_sig = {2896, "wglCreateImageBufferI3D", 3, _wglCreateImageBufferI3D_args};
 
 static const char * _wglDestroyImageBufferI3D_args[2] = {"hDC", "pAddress"};
-static const trace::FunctionSig _wglDestroyImageBufferI3D_sig = {2896, "wglDestroyImageBufferI3D", 2, _wglDestroyImageBufferI3D_args};
+static const trace::FunctionSig _wglDestroyImageBufferI3D_sig = {2897, "wglDestroyImageBufferI3D", 2, _wglDestroyImageBufferI3D_args};
 
 static const char * _wglAssociateImageBufferEventsI3D_args[5] = {"hDC", "pEvent", "pAddress", "pSize", "count"};
-static const trace::FunctionSig _wglAssociateImageBufferEventsI3D_sig = {2897, "wglAssociateImageBufferEventsI3D", 5, _wglAssociateImageBufferEventsI3D_args};
+static const trace::FunctionSig _wglAssociateImageBufferEventsI3D_sig = {2898, "wglAssociateImageBufferEventsI3D", 5, _wglAssociateImageBufferEventsI3D_args};
 
 static const char * _wglReleaseImageBufferEventsI3D_args[3] = {"hDC", "pAddress", "count"};
-static const trace::FunctionSig _wglReleaseImageBufferEventsI3D_sig = {2898, "wglReleaseImageBufferEventsI3D", 3, _wglReleaseImageBufferEventsI3D_args};
+static const trace::FunctionSig _wglReleaseImageBufferEventsI3D_sig = {2899, "wglReleaseImageBufferEventsI3D", 3, _wglReleaseImageBufferEventsI3D_args};
 
 static const char ** _wglEnableFrameLockI3D_args = NULL;
-static const trace::FunctionSig _wglEnableFrameLockI3D_sig = {2899, "wglEnableFrameLockI3D", 0, _wglEnableFrameLockI3D_args};
+static const trace::FunctionSig _wglEnableFrameLockI3D_sig = {2900, "wglEnableFrameLockI3D", 0, _wglEnableFrameLockI3D_args};
 
 static const char ** _wglDisableFrameLockI3D_args = NULL;
-static const trace::FunctionSig _wglDisableFrameLockI3D_sig = {2900, "wglDisableFrameLockI3D", 0, _wglDisableFrameLockI3D_args};
+static const trace::FunctionSig _wglDisableFrameLockI3D_sig = {2901, "wglDisableFrameLockI3D", 0, _wglDisableFrameLockI3D_args};
 
 static const char * _wglIsEnabledFrameLockI3D_args[1] = {"pFlag"};
-static const trace::FunctionSig _wglIsEnabledFrameLockI3D_sig = {2901, "wglIsEnabledFrameLockI3D", 1, _wglIsEnabledFrameLockI3D_args};
+static const trace::FunctionSig _wglIsEnabledFrameLockI3D_sig = {2902, "wglIsEnabledFrameLockI3D", 1, _wglIsEnabledFrameLockI3D_args};
 
 static const char * _wglQueryFrameLockMasterI3D_args[1] = {"pFlag"};
-static const trace::FunctionSig _wglQueryFrameLockMasterI3D_sig = {2902, "wglQueryFrameLockMasterI3D", 1, _wglQueryFrameLockMasterI3D_args};
+static const trace::FunctionSig _wglQueryFrameLockMasterI3D_sig = {2903, "wglQueryFrameLockMasterI3D", 1, _wglQueryFrameLockMasterI3D_args};
 
 static const char * _wglGetFrameUsageI3D_args[1] = {"pUsage"};
-static const trace::FunctionSig _wglGetFrameUsageI3D_sig = {2903, "wglGetFrameUsageI3D", 1, _wglGetFrameUsageI3D_args};
+static const trace::FunctionSig _wglGetFrameUsageI3D_sig = {2904, "wglGetFrameUsageI3D", 1, _wglGetFrameUsageI3D_args};
 
 static const char ** _wglBeginFrameTrackingI3D_args = NULL;
-static const trace::FunctionSig _wglBeginFrameTrackingI3D_sig = {2904, "wglBeginFrameTrackingI3D", 0, _wglBeginFrameTrackingI3D_args};
+static const trace::FunctionSig _wglBeginFrameTrackingI3D_sig = {2905, "wglBeginFrameTrackingI3D", 0, _wglBeginFrameTrackingI3D_args};
 
 static const char ** _wglEndFrameTrackingI3D_args = NULL;
-static const trace::FunctionSig _wglEndFrameTrackingI3D_sig = {2905, "wglEndFrameTrackingI3D", 0, _wglEndFrameTrackingI3D_args};
+static const trace::FunctionSig _wglEndFrameTrackingI3D_sig = {2906, "wglEndFrameTrackingI3D", 0, _wglEndFrameTrackingI3D_args};
 
 static const char * _wglQueryFrameTrackingI3D_args[3] = {"pFrameCount", "pMissedFrames", "pLastMissedUsage"};
-static const trace::FunctionSig _wglQueryFrameTrackingI3D_sig = {2906, "wglQueryFrameTrackingI3D", 3, _wglQueryFrameTrackingI3D_args};
+static const trace::FunctionSig _wglQueryFrameTrackingI3D_sig = {2907, "wglQueryFrameTrackingI3D", 3, _wglQueryFrameTrackingI3D_args};
 
 static const char * _wglSetStereoEmitterState3DL_args[2] = {"hDC", "uState"};
-static const trace::FunctionSig _wglSetStereoEmitterState3DL_sig = {2907, "wglSetStereoEmitterState3DL", 2, _wglSetStereoEmitterState3DL_args};
+static const trace::FunctionSig _wglSetStereoEmitterState3DL_sig = {2908, "wglSetStereoEmitterState3DL", 2, _wglSetStereoEmitterState3DL_args};
 
 static const char * _wglEnumerateVideoDevicesNV_args[2] = {"hDC", "phDeviceList"};
-static const trace::FunctionSig _wglEnumerateVideoDevicesNV_sig = {2908, "wglEnumerateVideoDevicesNV", 2, _wglEnumerateVideoDevicesNV_args};
+static const trace::FunctionSig _wglEnumerateVideoDevicesNV_sig = {2909, "wglEnumerateVideoDevicesNV", 2, _wglEnumerateVideoDevicesNV_args};
 
 static const char * _wglBindVideoDeviceNV_args[4] = {"hDC", "uVideoSlot", "hVideoDevice", "piAttribList"};
-static const trace::FunctionSig _wglBindVideoDeviceNV_sig = {2909, "wglBindVideoDeviceNV", 4, _wglBindVideoDeviceNV_args};
+static const trace::FunctionSig _wglBindVideoDeviceNV_sig = {2910, "wglBindVideoDeviceNV", 4, _wglBindVideoDeviceNV_args};
 
 static const char * _wglQueryCurrentContextNV_args[2] = {"iAttribute", "piValue"};
-static const trace::FunctionSig _wglQueryCurrentContextNV_sig = {2910, "wglQueryCurrentContextNV", 2, _wglQueryCurrentContextNV_args};
+static const trace::FunctionSig _wglQueryCurrentContextNV_sig = {2911, "wglQueryCurrentContextNV", 2, _wglQueryCurrentContextNV_args};
 
 static const char * _wglGetVideoDeviceNV_args[3] = {"hDC", "numDevices", "hVideoDevice"};
-static const trace::FunctionSig _wglGetVideoDeviceNV_sig = {2911, "wglGetVideoDeviceNV", 3, _wglGetVideoDeviceNV_args};
+static const trace::FunctionSig _wglGetVideoDeviceNV_sig = {2912, "wglGetVideoDeviceNV", 3, _wglGetVideoDeviceNV_args};
 
 static const char * _wglReleaseVideoDeviceNV_args[1] = {"hVideoDevice"};
-static const trace::FunctionSig _wglReleaseVideoDeviceNV_sig = {2912, "wglReleaseVideoDeviceNV", 1, _wglReleaseVideoDeviceNV_args};
+static const trace::FunctionSig _wglReleaseVideoDeviceNV_sig = {2913, "wglReleaseVideoDeviceNV", 1, _wglReleaseVideoDeviceNV_args};
 
 static const char * _wglBindVideoImageNV_args[3] = {"hVideoDevice", "hPbuffer", "iVideoBuffer"};
-static const trace::FunctionSig _wglBindVideoImageNV_sig = {2913, "wglBindVideoImageNV", 3, _wglBindVideoImageNV_args};
+static const trace::FunctionSig _wglBindVideoImageNV_sig = {2914, "wglBindVideoImageNV", 3, _wglBindVideoImageNV_args};
 
 static const char * _wglReleaseVideoImageNV_args[2] = {"hPbuffer", "iVideoBuffer"};
-static const trace::FunctionSig _wglReleaseVideoImageNV_sig = {2914, "wglReleaseVideoImageNV", 2, _wglReleaseVideoImageNV_args};
+static const trace::FunctionSig _wglReleaseVideoImageNV_sig = {2915, "wglReleaseVideoImageNV", 2, _wglReleaseVideoImageNV_args};
 
 static const char * _wglSendPbufferToVideoNV_args[4] = {"hPbuffer", "iBufferType", "pulCounterPbuffer", "bBlock"};
-static const trace::FunctionSig _wglSendPbufferToVideoNV_sig = {2915, "wglSendPbufferToVideoNV", 4, _wglSendPbufferToVideoNV_args};
+static const trace::FunctionSig _wglSendPbufferToVideoNV_sig = {2916, "wglSendPbufferToVideoNV", 4, _wglSendPbufferToVideoNV_args};
 
 static const char * _wglGetVideoInfoNV_args[3] = {"hpVideoDevice", "pulCounterOutputPbuffer", "pulCounterOutputVideo"};
-static const trace::FunctionSig _wglGetVideoInfoNV_sig = {2916, "wglGetVideoInfoNV", 3, _wglGetVideoInfoNV_args};
+static const trace::FunctionSig _wglGetVideoInfoNV_sig = {2917, "wglGetVideoInfoNV", 3, _wglGetVideoInfoNV_args};
 
 static const char * _wglJoinSwapGroupNV_args[2] = {"hDC", "group"};
-static const trace::FunctionSig _wglJoinSwapGroupNV_sig = {2917, "wglJoinSwapGroupNV", 2, _wglJoinSwapGroupNV_args};
+static const trace::FunctionSig _wglJoinSwapGroupNV_sig = {2918, "wglJoinSwapGroupNV", 2, _wglJoinSwapGroupNV_args};
 
 static const char * _wglBindSwapBarrierNV_args[2] = {"group", "barrier"};
-static const trace::FunctionSig _wglBindSwapBarrierNV_sig = {2918, "wglBindSwapBarrierNV", 2, _wglBindSwapBarrierNV_args};
+static const trace::FunctionSig _wglBindSwapBarrierNV_sig = {2919, "wglBindSwapBarrierNV", 2, _wglBindSwapBarrierNV_args};
 
 static const char * _wglQuerySwapGroupNV_args[3] = {"hDC", "group", "barrier"};
-static const trace::FunctionSig _wglQuerySwapGroupNV_sig = {2919, "wglQuerySwapGroupNV", 3, _wglQuerySwapGroupNV_args};
+static const trace::FunctionSig _wglQuerySwapGroupNV_sig = {2920, "wglQuerySwapGroupNV", 3, _wglQuerySwapGroupNV_args};
 
 static const char * _wglQueryMaxSwapGroupsNV_args[3] = {"hDC", "maxGroups", "maxBarriers"};
-static const trace::FunctionSig _wglQueryMaxSwapGroupsNV_sig = {2920, "wglQueryMaxSwapGroupsNV", 3, _wglQueryMaxSwapGroupsNV_args};
+static const trace::FunctionSig _wglQueryMaxSwapGroupsNV_sig = {2921, "wglQueryMaxSwapGroupsNV", 3, _wglQueryMaxSwapGroupsNV_args};
 
 static const char * _wglQueryFrameCountNV_args[2] = {"hDC", "count"};
-static const trace::FunctionSig _wglQueryFrameCountNV_sig = {2921, "wglQueryFrameCountNV", 2, _wglQueryFrameCountNV_args};
+static const trace::FunctionSig _wglQueryFrameCountNV_sig = {2922, "wglQueryFrameCountNV", 2, _wglQueryFrameCountNV_args};
 
 static const char * _wglResetFrameCountNV_args[1] = {"hDC"};
-static const trace::FunctionSig _wglResetFrameCountNV_sig = {2922, "wglResetFrameCountNV", 1, _wglResetFrameCountNV_args};
+static const trace::FunctionSig _wglResetFrameCountNV_sig = {2923, "wglResetFrameCountNV", 1, _wglResetFrameCountNV_args};
 
 static const char * _wglEnumGpusNV_args[2] = {"iGpuIndex", "phGpu"};
-static const trace::FunctionSig _wglEnumGpusNV_sig = {2923, "wglEnumGpusNV", 2, _wglEnumGpusNV_args};
+static const trace::FunctionSig _wglEnumGpusNV_sig = {2924, "wglEnumGpusNV", 2, _wglEnumGpusNV_args};
 
 static const char * _wglEnumGpuDevicesNV_args[3] = {"hGpu", "iDeviceIndex", "lpGpuDevice"};
-static const trace::FunctionSig _wglEnumGpuDevicesNV_sig = {2924, "wglEnumGpuDevicesNV", 3, _wglEnumGpuDevicesNV_args};
+static const trace::FunctionSig _wglEnumGpuDevicesNV_sig = {2925, "wglEnumGpuDevicesNV", 3, _wglEnumGpuDevicesNV_args};
 
 static const char * _wglCreateAffinityDCNV_args[1] = {"phGpuList"};
-static const trace::FunctionSig _wglCreateAffinityDCNV_sig = {2925, "wglCreateAffinityDCNV", 1, _wglCreateAffinityDCNV_args};
+static const trace::FunctionSig _wglCreateAffinityDCNV_sig = {2926, "wglCreateAffinityDCNV", 1, _wglCreateAffinityDCNV_args};
 
 static const char * _wglEnumGpusFromAffinityDCNV_args[3] = {"hAffinityDC", "iGpuIndex", "hGpu"};
-static const trace::FunctionSig _wglEnumGpusFromAffinityDCNV_sig = {2926, "wglEnumGpusFromAffinityDCNV", 3, _wglEnumGpusFromAffinityDCNV_args};
+static const trace::FunctionSig _wglEnumGpusFromAffinityDCNV_sig = {2927, "wglEnumGpusFromAffinityDCNV", 3, _wglEnumGpusFromAffinityDCNV_args};
 
 static const char * _wglDeleteDCNV_args[1] = {"hdc"};
-static const trace::FunctionSig _wglDeleteDCNV_sig = {2927, "wglDeleteDCNV", 1, _wglDeleteDCNV_args};
+static const trace::FunctionSig _wglDeleteDCNV_sig = {2928, "wglDeleteDCNV", 1, _wglDeleteDCNV_args};
 
 static const char * _wglGetGPUIDsAMD_args[2] = {"maxCount", "ids"};
-static const trace::FunctionSig _wglGetGPUIDsAMD_sig = {2928, "wglGetGPUIDsAMD", 2, _wglGetGPUIDsAMD_args};
+static const trace::FunctionSig _wglGetGPUIDsAMD_sig = {2929, "wglGetGPUIDsAMD", 2, _wglGetGPUIDsAMD_args};
 
 static const char * _wglGetGPUInfoAMD_args[5] = {"id", "property", "dataType", "size", "data"};
-static const trace::FunctionSig _wglGetGPUInfoAMD_sig = {2929, "wglGetGPUInfoAMD", 5, _wglGetGPUInfoAMD_args};
+static const trace::FunctionSig _wglGetGPUInfoAMD_sig = {2930, "wglGetGPUInfoAMD", 5, _wglGetGPUInfoAMD_args};
 
 static const char * _wglGetContextGPUIDAMD_args[1] = {"hglrc"};
-static const trace::FunctionSig _wglGetContextGPUIDAMD_sig = {2930, "wglGetContextGPUIDAMD", 1, _wglGetContextGPUIDAMD_args};
+static const trace::FunctionSig _wglGetContextGPUIDAMD_sig = {2931, "wglGetContextGPUIDAMD", 1, _wglGetContextGPUIDAMD_args};
 
 static const char * _wglCreateAssociatedContextAMD_args[1] = {"id"};
-static const trace::FunctionSig _wglCreateAssociatedContextAMD_sig = {2931, "wglCreateAssociatedContextAMD", 1, _wglCreateAssociatedContextAMD_args};
+static const trace::FunctionSig _wglCreateAssociatedContextAMD_sig = {2932, "wglCreateAssociatedContextAMD", 1, _wglCreateAssociatedContextAMD_args};
 
 static const char * _wglCreateAssociatedContextAttribsAMD_args[3] = {"id", "hShareContext", "attribList"};
-static const trace::FunctionSig _wglCreateAssociatedContextAttribsAMD_sig = {2932, "wglCreateAssociatedContextAttribsAMD", 3, _wglCreateAssociatedContextAttribsAMD_args};
+static const trace::FunctionSig _wglCreateAssociatedContextAttribsAMD_sig = {2933, "wglCreateAssociatedContextAttribsAMD", 3, _wglCreateAssociatedContextAttribsAMD_args};
 
 static const char * _wglDeleteAssociatedContextAMD_args[1] = {"hglrc"};
-static const trace::FunctionSig _wglDeleteAssociatedContextAMD_sig = {2933, "wglDeleteAssociatedContextAMD", 1, _wglDeleteAssociatedContextAMD_args};
+static const trace::FunctionSig _wglDeleteAssociatedContextAMD_sig = {2934, "wglDeleteAssociatedContextAMD", 1, _wglDeleteAssociatedContextAMD_args};
 
 static const char * _wglMakeAssociatedContextCurrentAMD_args[1] = {"hglrc"};
-static const trace::FunctionSig _wglMakeAssociatedContextCurrentAMD_sig = {2934, "wglMakeAssociatedContextCurrentAMD", 1, _wglMakeAssociatedContextCurrentAMD_args};
+static const trace::FunctionSig _wglMakeAssociatedContextCurrentAMD_sig = {2935, "wglMakeAssociatedContextCurrentAMD", 1, _wglMakeAssociatedContextCurrentAMD_args};
 
 static const char ** _wglGetCurrentAssociatedContextAMD_args = NULL;
-static const trace::FunctionSig _wglGetCurrentAssociatedContextAMD_sig = {2935, "wglGetCurrentAssociatedContextAMD", 0, _wglGetCurrentAssociatedContextAMD_args};
+static const trace::FunctionSig _wglGetCurrentAssociatedContextAMD_sig = {2936, "wglGetCurrentAssociatedContextAMD", 0, _wglGetCurrentAssociatedContextAMD_args};
 
 static const char * _wglBlitContextFramebufferAMD_args[11] = {"dstCtx", "srcX0", "srcY0", "srcX1", "srcY1", "dstX0", "dstY0", "dstX1", "dstY1", "mask", "filter"};
-static const trace::FunctionSig _wglBlitContextFramebufferAMD_sig = {2936, "wglBlitContextFramebufferAMD", 11, _wglBlitContextFramebufferAMD_args};
+static const trace::FunctionSig _wglBlitContextFramebufferAMD_sig = {2937, "wglBlitContextFramebufferAMD", 11, _wglBlitContextFramebufferAMD_args};
 
 static const char * _wglBindVideoCaptureDeviceNV_args[2] = {"uVideoSlot", "hDevice"};
-static const trace::FunctionSig _wglBindVideoCaptureDeviceNV_sig = {2937, "wglBindVideoCaptureDeviceNV", 2, _wglBindVideoCaptureDeviceNV_args};
+static const trace::FunctionSig _wglBindVideoCaptureDeviceNV_sig = {2938, "wglBindVideoCaptureDeviceNV", 2, _wglBindVideoCaptureDeviceNV_args};
 
 static const char * _wglEnumerateVideoCaptureDevicesNV_args[2] = {"hDc", "phDeviceList"};
-static const trace::FunctionSig _wglEnumerateVideoCaptureDevicesNV_sig = {2938, "wglEnumerateVideoCaptureDevicesNV", 2, _wglEnumerateVideoCaptureDevicesNV_args};
+static const trace::FunctionSig _wglEnumerateVideoCaptureDevicesNV_sig = {2939, "wglEnumerateVideoCaptureDevicesNV", 2, _wglEnumerateVideoCaptureDevicesNV_args};
 
 static const char * _wglLockVideoCaptureDeviceNV_args[2] = {"hDc", "hDevice"};
-static const trace::FunctionSig _wglLockVideoCaptureDeviceNV_sig = {2939, "wglLockVideoCaptureDeviceNV", 2, _wglLockVideoCaptureDeviceNV_args};
+static const trace::FunctionSig _wglLockVideoCaptureDeviceNV_sig = {2940, "wglLockVideoCaptureDeviceNV", 2, _wglLockVideoCaptureDeviceNV_args};
 
 static const char * _wglQueryVideoCaptureDeviceNV_args[4] = {"hDc", "hDevice", "iAttribute", "piValue"};
-static const trace::FunctionSig _wglQueryVideoCaptureDeviceNV_sig = {2940, "wglQueryVideoCaptureDeviceNV", 4, _wglQueryVideoCaptureDeviceNV_args};
+static const trace::FunctionSig _wglQueryVideoCaptureDeviceNV_sig = {2941, "wglQueryVideoCaptureDeviceNV", 4, _wglQueryVideoCaptureDeviceNV_args};
 
 static const char * _wglReleaseVideoCaptureDeviceNV_args[2] = {"hDc", "hDevice"};
-static const trace::FunctionSig _wglReleaseVideoCaptureDeviceNV_sig = {2941, "wglReleaseVideoCaptureDeviceNV", 2, _wglReleaseVideoCaptureDeviceNV_args};
+static const trace::FunctionSig _wglReleaseVideoCaptureDeviceNV_sig = {2942, "wglReleaseVideoCaptureDeviceNV", 2, _wglReleaseVideoCaptureDeviceNV_args};
 
 static const char * _wglCopyImageSubDataNV_args[17] = {"hSrcRC", "srcName", "srcTarget", "srcLevel", "srcX", "srcY", "srcZ", "hDstRC", "dstName", "dstTarget", "dstLevel", "dstX", "dstY", "dstZ", "width", "height", "depth"};
-static const trace::FunctionSig _wglCopyImageSubDataNV_sig = {2942, "wglCopyImageSubDataNV", 17, _wglCopyImageSubDataNV_args};
+static const trace::FunctionSig _wglCopyImageSubDataNV_sig = {2943, "wglCopyImageSubDataNV", 17, _wglCopyImageSubDataNV_args};
 
 static const char * _wglDXSetResourceShareHandleNV_args[2] = {"dxObject", "shareHandle"};
-static const trace::FunctionSig _wglDXSetResourceShareHandleNV_sig = {2943, "wglDXSetResourceShareHandleNV", 2, _wglDXSetResourceShareHandleNV_args};
+static const trace::FunctionSig _wglDXSetResourceShareHandleNV_sig = {2944, "wglDXSetResourceShareHandleNV", 2, _wglDXSetResourceShareHandleNV_args};
 
 static const char * _wglDXOpenDeviceNV_args[1] = {"dxDevice"};
-static const trace::FunctionSig _wglDXOpenDeviceNV_sig = {2944, "wglDXOpenDeviceNV", 1, _wglDXOpenDeviceNV_args};
+static const trace::FunctionSig _wglDXOpenDeviceNV_sig = {2945, "wglDXOpenDeviceNV", 1, _wglDXOpenDeviceNV_args};
 
 static const char * _wglDXCloseDeviceNV_args[1] = {"hDevice"};
-static const trace::FunctionSig _wglDXCloseDeviceNV_sig = {2945, "wglDXCloseDeviceNV", 1, _wglDXCloseDeviceNV_args};
+static const trace::FunctionSig _wglDXCloseDeviceNV_sig = {2946, "wglDXCloseDeviceNV", 1, _wglDXCloseDeviceNV_args};
 
 static const char * _wglDXRegisterObjectNV_args[5] = {"hDevice", "dxObject", "name", "type", "access"};
-static const trace::FunctionSig _wglDXRegisterObjectNV_sig = {2946, "wglDXRegisterObjectNV", 5, _wglDXRegisterObjectNV_args};
+static const trace::FunctionSig _wglDXRegisterObjectNV_sig = {2947, "wglDXRegisterObjectNV", 5, _wglDXRegisterObjectNV_args};
 
 static const char * _wglDXUnregisterObjectNV_args[2] = {"hDevice", "hObject"};
-static const trace::FunctionSig _wglDXUnregisterObjectNV_sig = {2947, "wglDXUnregisterObjectNV", 2, _wglDXUnregisterObjectNV_args};
+static const trace::FunctionSig _wglDXUnregisterObjectNV_sig = {2948, "wglDXUnregisterObjectNV", 2, _wglDXUnregisterObjectNV_args};
 
 static const char * _wglDXObjectAccessNV_args[2] = {"hObject", "access"};
-static const trace::FunctionSig _wglDXObjectAccessNV_sig = {2948, "wglDXObjectAccessNV", 2, _wglDXObjectAccessNV_args};
+static const trace::FunctionSig _wglDXObjectAccessNV_sig = {2949, "wglDXObjectAccessNV", 2, _wglDXObjectAccessNV_args};
 
 static const char * _wglDXLockObjectsNV_args[3] = {"hDevice", "count", "hObjects"};
-static const trace::FunctionSig _wglDXLockObjectsNV_sig = {2949, "wglDXLockObjectsNV", 3, _wglDXLockObjectsNV_args};
+static const trace::FunctionSig _wglDXLockObjectsNV_sig = {2950, "wglDXLockObjectsNV", 3, _wglDXLockObjectsNV_args};
 
 static const char * _wglDXUnlockObjectsNV_args[3] = {"hDevice", "count", "hObjects"};
-static const trace::FunctionSig _wglDXUnlockObjectsNV_sig = {2950, "wglDXUnlockObjectsNV", 3, _wglDXUnlockObjectsNV_args};
+static const trace::FunctionSig _wglDXUnlockObjectsNV_sig = {2951, "wglDXUnlockObjectsNV", 3, _wglDXUnlockObjectsNV_args};
 
 static const char * _wglGetProcAddress_args[1] = {"lpszProc"};
-static const trace::FunctionSig _wglGetProcAddress_sig = {2951, "wglGetProcAddress", 1, _wglGetProcAddress_args};
+static const trace::FunctionSig _wglGetProcAddress_sig = {2952, "wglGetProcAddress", 1, _wglGetProcAddress_args};
 
 #endif // REGAL_SYS_WGL
 
@@ -44454,7 +44457,7 @@
     trace::localWriter.endLeave();
 }
 
-void glClearNamedBufferSubDataEXT( GLuint buffer, GLenum internalformat, GLenum format, GLenum type, GLsizeiptr offset, GLsizeiptr size, const void * data ) {
+void glClearNamedBufferSubDataEXT( GLuint buffer, GLenum internalformat, GLsizeiptr offset, GLsizeiptr size, GLenum format, GLenum type, const void * data ) {
     unsigned _call = trace::localWriter.beginEnter(&_glClearNamedBufferSubDataEXT_sig);
     trace::localWriter.beginArg(0);
     trace::localWriter.writeUInt(buffer);
@@ -44463,22 +44466,22 @@
     trace::localWriter.writeEnum(&_enumGLenum_sig, internalformat);
     trace::localWriter.endArg();
     trace::localWriter.beginArg(2);
-    trace::localWriter.writeEnum(&_enumGLenum_sig, format);
-    trace::localWriter.endArg();
-    trace::localWriter.beginArg(3);
-    trace::localWriter.writeEnum(&_enumGLenum_sig, type);
-    trace::localWriter.endArg();
-    trace::localWriter.beginArg(4);
     trace::localWriter.writeSInt(offset);
     trace::localWriter.endArg();
-    trace::localWriter.beginArg(5);
+    trace::localWriter.beginArg(3);
     trace::localWriter.writeSInt(size);
     trace::localWriter.endArg();
+    trace::localWriter.beginArg(4);
+    trace::localWriter.writeEnum(&_enumGLenum_sig, format);
+    trace::localWriter.endArg();
+    trace::localWriter.beginArg(5);
+    trace::localWriter.writeEnum(&_enumGLenum_sig, type);
+    trace::localWriter.endArg();
     trace::localWriter.beginArg(6);
     trace::localWriter.writeBlob(data, _glClearBufferData_size(format, type));
     trace::localWriter.endArg();
     trace::localWriter.endEnter();
-    _glClearNamedBufferSubDataEXT(buffer, internalformat, format, type, offset, size, data);
+    _glClearNamedBufferSubDataEXT(buffer, internalformat, offset, size, format, type, data);
     trace::localWriter.beginLeave(_call);
     if (true) {
     }
@@ -78062,6 +78065,46 @@
     trace::localWriter.endLeave();
 }
 
+void glBlitFramebufferNV( GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter ) {
+    unsigned _call = trace::localWriter.beginEnter(&_glBlitFramebufferNV_sig);
+    trace::localWriter.beginArg(0);
+    trace::localWriter.writeSInt(srcX0);
+    trace::localWriter.endArg();
+    trace::localWriter.beginArg(1);
+    trace::localWriter.writeSInt(srcY0);
+    trace::localWriter.endArg();
+    trace::localWriter.beginArg(2);
+    trace::localWriter.writeSInt(srcX1);
+    trace::localWriter.endArg();
+    trace::localWriter.beginArg(3);
+    trace::localWriter.writeSInt(srcY1);
+    trace::localWriter.endArg();
+    trace::localWriter.beginArg(4);
+    trace::localWriter.writeSInt(dstX0);
+    trace::localWriter.endArg();
+    trace::localWriter.beginArg(5);
+    trace::localWriter.writeSInt(dstY0);
+    trace::localWriter.endArg();
+    trace::localWriter.beginArg(6);
+    trace::localWriter.writeSInt(dstX1);
+    trace::localWriter.endArg();
+    trace::localWriter.beginArg(7);
+    trace::localWriter.writeSInt(dstY1);
+    trace::localWriter.endArg();
+    trace::localWriter.beginArg(8);
+    trace::localWriter.writeBitmask(&_bitmaskGLbitfield1_sig, mask);
+    trace::localWriter.endArg();
+    trace::localWriter.beginArg(9);
+    trace::localWriter.writeEnum(&_enumGLenum_sig, filter);
+    trace::localWriter.endArg();
+    trace::localWriter.endEnter();
+    _glBlitFramebufferNV(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter);
+    trace::localWriter.beginLeave(_call);
+    if (true) {
+    }
+    trace::localWriter.endLeave();
+}
+
 GLuint glNewBufferRegion( GLenum type ) {
     GLuint _result;
     unsigned _call = trace::localWriter.beginEnter(&_glNewBufferRegion_sig);
diff --git a/src/civetweb/CREDITS.md b/src/civetweb/CREDITS.md
new file mode 100644
index 0000000..4322dfd
--- /dev/null
+++ b/src/civetweb/CREDITS.md
@@ -0,0 +1,68 @@
+# Civetweb Contributors
+
+* Alex Kozlov
+* bel2125
+* celeron55
+* Daniel Oaks
+* F-Secure Corporation
+* Brian Spratke
+* HariKamath Kamath
+* Kimmo Mustonen
+* Morgan McGuire
+* No Face Press
+* Paul Sokolovsky
+* Thomas Davis
+* Toni Wilk
+* William Greathouse
+
+# Mongoose Contributors
+The following users contributed to the original Mongoose release between 2010 and 2013.  Civitweb is based on the Mongoose code.  This list was generated from the Mongoose GIT logs.  There is no record for contributors prior to 2010.
+
+* Sergey Lyubka
+* Arnout Vandecappelle (Essensium/Mind)
+* Benoît Amiaux
+* Cody Hanson
+* Colin Leitner
+* Daniel Oaks
+* Eric Bakan
+* Erik Oomen
+* Filipp Kovalev
+* Ger Hobbelt
+* Hendrik Polczynski
+* Henrique Mendonça
+* Igor Okulist
+* Jay
+* Joe Mucchiello
+* John Safranek
+* Joseph Mainwaring
+* José Miguel Gonçalves
+* KIU Shueng Chuan
+* Katerina Blinova
+* Konstantin Sorokin
+* Marin Atanasov Nikolov
+* Matt Healy
+* Miguel Morales
+* Mikhail Nikalyukin
+* MikieMorales
+* Mitch Hendrickson
+* Nigel Stewart
+* Pavel
+* Pavel Khlebovich
+* Rogerz Zhang
+* Sebastian Reinhard
+* Stefan Doehla
+* Thileepan
+* abadc0de
+* arvidn
+* bick
+* ff.feng
+* jmucchiello
+* jwang
+* lsm
+* migal
+* mlamb
+* nullable.type
+* shantanugadgil
+* tayS
+* test
+* valenok
diff --git a/src/civetweb/LICENSE.md b/src/civetweb/LICENSE.md
new file mode 100644
index 0000000..ed35993
--- /dev/null
+++ b/src/civetweb/LICENSE.md
@@ -0,0 +1,113 @@
+ALL LICENSES
+=====
+
+This document includes several copyright licenses for different
+aspects of the software.  Not all licenses may apply depending
+on the features chosen.
+
+Civetweb License
+-----
+
+### Included with all features.
+
+> Copyright (c) 2004-2013 Sergey Lyubka
+>
+> Copyright (c) 2013 No Face Press, LLC (Thomas Davis)
+>
+> Copyright (c) 2013 F-Secure Corporation
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+> 
+> The above copyright notice and this permission notice shall be included in
+> all copies or substantial portions of the Software.
+> 
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+> THE SOFTWARE.
+
+Lua License
+------
+
+### Included only if built with Lua support.
+
+http://www.lua.org/license.html
+
+> Copyright � 1994-2013 Lua.org, PUC-Rio.
+> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+> 
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+
+SQLite3 License
+------
+
+### Included only if built with Lua support.
+
+http://www.sqlite.org/copyright.html
+
+> 2001 September 15
+>
+> The author disclaims copyright to this source code.  In place of
+> a legal notice, here is a blessing:
+>
+>    May you do good and not evil.
+>    May you find forgiveness for yourself and forgive others.
+>    May you share freely, never taking more than you give.
+
+lsqlite3 License
+------
+
+### Included only if built with Lua support.
+
+> lsqlite3                                                              
+> Copyright (C) 2002-2007 Tiago Dionizio, Doug Currie                   
+> All rights reserved.                                                  
+> Author    : Tiago Dionizio <tiago.dionizio@ist.utl.pt>                
+> Author    : Doug Currie <doug.currie@alum.mit.edu>                    
+> Library   : lsqlite3 - a SQLite 3 database binding for Lua 5          
+>                                                                      
+> Permission is hereby granted, free of charge, to any person obtaining 
+> a copy of this software and associated documentation files (the       
+> "Software"), to deal in the Software without restriction, including   
+> without limitation the rights to use, copy, modify, merge, publish,   
+> distribute, sublicense, and/or sell copies of the Software, and to    
+> permit persons to whom the Software is furnished to do so, subject to 
+> the following conditions:                                             
+>                                                                      
+> The above copyright notice and this permission notice shall be        
+> included in all copies or substantial portions of the Software.       
+>                                                                      
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       
+> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    
+> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  
+> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  
+> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     
+> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                
+
+Lua File System License
+------
+
+### Included only if built with Lua support.
+
+http://keplerproject.github.io/luafilesystem/license.html
+
+> Copyright © 2003 Kepler Project.
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+> 
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
diff --git a/src/civetweb/README.md b/src/civetweb/README.md
new file mode 100644
index 0000000..25ddeb0
--- /dev/null
+++ b/src/civetweb/README.md
@@ -0,0 +1,102 @@
+![Civetweb](https://raw.github.com/bel2125/civetweb/master/resources/civetweb_64x64.png "Civetweb") Civetweb
+=======
+
+There is a new home!!!
+-----------------
+https://github.com/bel2125/civetweb
+Bel has been taking the lead on Civetweb, so teh official repositiory 
+is being moved under his control for ease of maintanence.
+
+Project Mission
+-----------------
+
+Project mission is to provide easy to use, powerful, C/C++ embeddable web server with optional CGI, SSL and Lua support.
+Civetweb has a MIT license so you can innovate without restrictions.
+
+Where to find the official version?
+-----------------------------------
+
+End users can download Civetweb at SourceForge
+https://sourceforge.net/projects/civetweb/
+
+Developers can contribute to CivetWeb via GitHub
+https://github.com/bel2125/civetweb
+
+Trouble tickets should be filed on GitHub
+https://github.com/bel2125/civetweb/issues
+
+Discussion group is at Google Groups
+https://groups.google.com/d/forum/civetweb
+
+Quick start documentation
+--------------------------
+
+- [docs/Installing.md](https://github.com/bel2125/civetweb/blob/master/docs/Installing.md) - Install Guide
+- [docs/UserManual.md](https://github.com/bel2125/civetweb/blob/master/docs/UserManual.md) - End User Guide
+- [docs/Building.md](https://github.com/bel2125/civetweb/blob/master/docs/Building.md) - Buildiing the Server Quick Start
+- [docs/Embedding.md](https://github.com/bel2125/civetweb/blob/master/docs/Embedding.md) - Embedding Quick Start
+- [RELEASE_NOTES.md](https://github.com/bel2125/civetweb/blob/master/RELEASE_NOTES.md) - Release Notes
+- [LICENSE.md](https://github.com/bel2125/civetweb/blob/master/LICENSE.md) - Copyright License
+
+Overview
+--------
+
+Civetweb keeps the balance between functionality and
+simplicity by carefully selected list of features:
+
+- Liberal, commercial-friendly, permissive,
+  [MIT license](http://en.wikipedia.org/wiki/MIT_License)
+- Free from copy-left licenses, like GPL, because you should innovate without restrictions.
+- Based on [Mongoose](https://code.google.com/p/mongoose/)
+- Works on Windows, Mac, UNIX, iPhone, Android, Buildroot, and many other platforms
+- Scripting and database support (Lua Server Pages + Sqlite
+  which provides ready to go, powerful web development platform in
+  one single-click executable with **no dependencies**: forget LAMP!
+- Support for CGI, SSL, SSI, Digest (MD5) authorization, Websocket, WEbDAV
+- Resumed download, URL rewrite, file blacklist, IP-based ACL, Windows service
+- Download speed limit based on client subnet or URI pattern
+- Simple and clean embedding API,
+  The source is in single file
+  to make things easy. Embedding examples included.
+- HTTP client capable of sending arbitrary HTTP/HTTPS requests
+
+
+### Other optionally included software
+
+<a href="http://lua.org">
+![Lua](https://raw.github.com/bel2125/civetweb/master/resources/lua-logo.jpg "Lua Logo")
+</a>
+<a href="http://sqlite.org">
+![Sqlite3](https://raw.github.com/bel2125/civetweb/master/resources/sqlite3-logo.jpg "Sqlite3 Logo")
+</a>
+
+Support
+-------
+
+The original Mongoose project is recommended if support is needed.  However,
+this is very easy to install and use. 
+
+Contributions
+---------------
+
+Contributions are welcome provided all contributions carry the MIT license.
+
+DO NOT APPLY fixes copied from Mongoose to this project to prevent GPL tainting.
+
+### Author
+
+The original Author was Sergey Lyubka.  He still controls the original
+Mongoose project.  However, he has changed or said he would 
+change licenses after writing and distributing the original code this
+project is based on.
+
+Using this project ensures the MIT licenses terms are applied and
+GPL cannot be imposed on any of this code as long as it is sourced from
+here.
+
+For the latest and greatest code and features, please use the Mongoose
+code from Sergey Lyubka.  However, doing so will require adherence to
+the new licenses.
+
+This project ensures that GPL license cannot be applied to this code.
+This code will remain free with the MIT license protection.
diff --git a/src/civetweb/RELEASE_NOTES.md b/src/civetweb/RELEASE_NOTES.md
new file mode 100644
index 0000000..d6f6714
--- /dev/null
+++ b/src/civetweb/RELEASE_NOTES.md
@@ -0,0 +1,181 @@
+Release Notes v1.6 (Under Development)
+===
+### Objectives: *???*
+
+Changes
+-------
+
+- Win32: Replace dll.def file by export macros in civetweb.h (CSTAJ)
+- Base64 encode and decode functions for Lua (bel)
+- Support pre-loaded files for the Lua environment (bel)
+- Server should check the nonce for http digest access authentication (bel)
+- Hide read-only flag in file dialogs opened by the Edit Settings dialog for the Windows executable (bel)
+- Add all functions to dll.def, that are in the header (bel)
+- Added Lua extensions: send_file, get_var, get_mime_type, get_cookie, url_decode, url_encode (bel)
+- mg_set_request_handler() mod to use pattern (bel, Patch from Toni Wilk)
+- Solved, tested and documented SSL support for Windows (bel)
+- Fixed: select for Linux needs the nfds parameter set correctly  (bel) 
+- Add methods for returning the ports civetweb is listening on (keithel)
+- Fixes for Lua Server Pages, as described within the google groups thread. (bel)
+- Added support for plain Lua Scripts, and an example script. (bel)
+- A completely new, and more illustrative websocket example for C. (bel)
+- An implementation of "Websocket for Lua", which allows to configure an optional websocket_root directory, incl. URL rewriting. Added an example. The Lua interface may change if the threading model changes.  (bel)
+- Update of SQLite3 to 3.8.1. (bel)
+- Add "date" header field to replies, according to the requirements of RFC 2616 (the HTTP standard), Section 14.18 (bel)
+- Fix websocket long pull (celeron55)
+- Updated API documentation (Alex Kozlov)
+- Fixed Posix locking functions for Windows (bel2125)
+- Updated version number
+
+Release Notes v1.5
+===
+### Objectives: *Bug fixes and updates, repository restoration*
+
+Changes
+-------
+
+- Corrected bad mask flag/opcode passing to websocket callback (William Greathouse)
+- Moved CEVITWEB_VERSION define into civetweb.h
+- Added new simple zip deployment build for Windows. 
+- Removed windows install package build.
+- Fixes page violation in mod_lua.inl (apkbox)
+- Use C style comments to enable compiling most of civetweb with -ansi. (F-Secure Corporation)
+- Allow directories with non ASCII characters in Windows in UTF-8 encoded (bel2125)
+- Added Lua File System support (bel2125)
+- Added mongoose history back in repository thanks to (Paul Sokolovsky)
+- Fixed keep alive (bel2125)
+- Updated of MIME types (bel2125)
+- Updated lsqlite (bel2125)
+- Fixed master thread priority (bel2125)
+- Fixed IPV6 defines under Windowe (grenclave)
+- Fixed potential dead lock in connection_close() (Morgan McGuire)
+- Added WebSocket example using asynchronous server messages (William Greathouse)
+- Fixed the getcwd() warning (William Greathouse)
+- Implemented the connection_close() callback (William Greathouse)
+- Fixed support URL's in civetweb.c (Daniel Oaks)
+- Allow port number to be zero to use a random free port (F-Secure Corporation)
+- Wait for threads to finish when stopping for a clean shutdown (F-Secure Corporation)
+- More static analysis fixes against Coverity tool (F-Secure Corporation)
+- Travis automated build testing support added (Daniel Oaks)
+- Updated version numbers.
+- Added contributor credits file.
+
+Release Notes v1.4
+===
+### Objectives: *New URI handler interface, feature enhancements, C++ extensions*
+The main idea behind this release is to bring about API consistency. All changes
+are backward compatible and have been kept to a minimum.
+
+Changes
+-------
+
+- Added mg_set_request_handler() which provides a URI mapping for callbacks.
+   This is a new alternative to overriding callbacks.begin_request.
+- Externalized mg_url_encode()
+- Externalized mg_strncasecmp() for utiliy
+- Added CivetServer::getParam methods
+- Added CivetServer::urlDecode methods
+- Added CivetServer::urlEncode methods
+- Dealt with compiler warnings and some static analysis hits.
+- Added mg_get_var2() to parse repeated query variables
+- Externalized logging function cry() as mg_cry()
+- Added CivetServer::getCookie method (Hariprasad Kamath)
+- Added CivetServer::getHeader method (Hariprasad Kamath)
+- Added new basic C embedding example
+- Conformed source files to UNIX line endings for consistency.
+- Unified the coding style to improve reability.
+
+Release Notes v1.3 
+===
+### Objectives: *Buildroot Integration*
+
+Changes
+-------
+
+- Made option to put initial HTMLDIR in a different place
+- Validated build without SQLITE3 large file support
+- Updated documentation
+- Updated Buildroot config example
+
+Release Notes v1.2 
+===
+### Objectives: *Installation Improvements, buildroot, cross compile support*
+The objective of this release is to make installation seamless.
+
+Changes
+-------
+
+- Create an installation guide
+- Created both 32 and 64 bit windows installations
+- Added install for windows distribution
+- Added 64 bit build profiles for VS 2012.
+- Created a buildroot patch
+- Updated makefile to better support buildroot
+- Made doc root and ports configurable during the make install.
+- Updated Linux Install
+- Updated OS X Package
+- Improved install scheme with welcome web page
+
+Known Issues
+-----
+
+- The prebuilt Window's version requires [Visual C++ Redistributable for Visual Studio 2012](http://www.microsoft.com/en-us/download/details.aspx?id=30679)
+
+Release Notes v1.1 
+===
+### Objectives: *Build, Documentation, License Improvements*
+The objective of this release is to establish a maintable code base, ensure MIT license rights and improve usability and documentation.
+
+Changes
+-------
+
+- Reorangized build directories to make them more intuitive
+- Added new build rules for lib and slib with option to include C++ class
+- Upgraded Lua from 5.2.1 to 5.2.2
+- Added fallback configuration file path for Linux systems.
+    + Good for having a system wide default configuration /usr/local/etc/civetweb.conf
+- Added new C++ abstraction class CivetServer
+- Added thread safety for and fixed websocket defects (Morgan McGuire)
+- Created PKGBUILD to use Arch distribution (Daniel Oaks)
+- Created new documentation on Embeddeding, Building and yaSSL (see docs/).
+- Updated License file to include all licenses.
+- Replaced MD5 implementation due to questionable license.
+     + This requires new source file md5.inl
+- Changed UNIX/OSX build to conform to common practices.
+     + Supports build, install and clean rules.
+     + Supports cross compiling
+     + Features can be chosen in make options
+- Moved Cocoa/OSX build and packaging to a separate file.
+     + This actually a second build variant for OSX.
+     + Removed yaSSL from the OSX build, not needed.
+- Added new Visual Studio projects for Windows builds.
+     + Removed Windows support from Makefiles
+     + Provided additional, examples with Lua, and another with yaSSL. 
+- Changed Zombie Reaping policy to not ignore SIGCHLD.
+     + The previous method caused trouble in applciations that spawn children.
+
+Known Issues
+-----
+
+- Build support for VS6 and some other has been deprecated.
+    + This does not impact embedded programs, just the stand-alone build.
+    + The old Makefile was renamed to Makefile.deprecated.
+    + This is partcially do to lack fo testing. 
+    + Need to find out what is actually in demand.
+- Build changes may impact current users.
+    + As with any change of this type, changes may impact some users.
+
+Release Notes v1.0
+===
+
+### Objectives: *MIT License Preservation, Rebranding*
+The objective of this release is to establish a version of the Mongoose software distribution that still retains the MIT license.
+
+Changes
+-------
+
+- Renamed Mongoose to Civetweb in the code and documentation.
+- Replaced copyrighted images with new images
+- Created a new code respository at https://github.com/sunsetbrew/civetweb
+- Created a distribution site at https://sourceforge.net/projects/civetweb/
+- Basic build testing
diff --git a/src/civetweb/UserManual.md b/src/civetweb/UserManual.md
new file mode 100644
index 0000000..3e188e4
--- /dev/null
+++ b/src/civetweb/UserManual.md
@@ -0,0 +1,481 @@
+
+Overview
+=====
+
+Civetweb is small and easy to use web server. It is self-contained, and does
+not require any external software to run.
+
+Installation
+----
+
+### Some Windows users may be the install the
+[Visual C++ Redistributable for Visual Studio 2012](http://www.microsoft.com/en-us/download/details.aspx?id=30679)
+
+On Windows, civetweb iconifies itself to the system tray icon when started.
+Right-click on the icon pops up a menu, where it is possible to stop
+civetweb, or configure it, or install it as Windows service. The easiest way
+to share a folder on Windows is to copy `civetweb.exe` to a folder,
+double-click the exe, and launch a browser at
+[http://localhost:8080](http://localhost:8080). Note that 'localhost' should
+be changed to a machine's name if a folder is accessed from other computer.
+
+On UNIX and Mac, civetweb is a command line utility. Running `civetweb` in
+terminal, optionally followed by configuration parameters
+(`civetweb [OPTIONS]`) or configuration file name
+(`civetweb [config_file_name]`) starts the
+web server. Civetweb does not detach from terminal. Pressing `Ctrl-C` keys
+would stop the server.
+
+When started, civetweb first searches for the configuration file.
+If configuration file is specified explicitly in the command line, i.e.
+`civetweb path_to_config_file`, then specified configuration file is used.
+Otherwise, civetweb would search for file `civetweb.conf` in the same directory
+where binary is located, and use it. Configuration file can be absent.
+
+
+Configuration file is a sequence of lines, each line containing
+command line argument name and it's value. Empty lines, and lines beginning
+with `#`, are ignored. Here is the example of `civetweb.conf` file:
+
+    document_root c:\www
+    listening_ports 8080,8043s
+    ssl_certificate c:\civetweb\ssl_cert.pem
+
+When configuration file is processed, civetweb process command line arguments,
+if they are specified. Command line arguments therefore can override
+configuration file settings. Command line arguments must start with `-`.
+For example, if `civetweb.conf` has line
+`document_root /var/www`, and civetweb has been started as
+`civetweb -document_root /etc`, then `/etc` directory will be served as
+document root, because command line options take priority over
+configuration file. Configuration options section below provide a good
+overview of Civetweb features.
+
+Note that configuration options on the command line must start with `-`,
+but their names are the same as in the config file. All option names are
+listed in the next section. Thus, the following two setups are equivalent:
+
+    # Using command line arguments
+    $ civetweb -listening_ports 1234 -document_root /var/www
+
+    # Using config file
+    $ cat civetweb.conf
+    listening_ports 1234
+    document_root /var/www
+    $ civetweb
+
+Civetweb can also be used to modify `.htpasswd` passwords file:
+
+    civetweb -A <htpasswd_file> <realm> <user> <passwd>
+
+Unlike other web servers, civetweb does not require CGI scripts be located in
+a special directory. CGI scripts can be anywhere. CGI (and SSI) files are
+recognized by the file name pattern. Civetweb uses shell-like glob
+patterns. Pattern match starts at the beginning of the string, so essentially
+patterns are prefix patterns. Syntax is as follows:
+
+     **      Matches everything
+     *       Matches everything but slash character, '/'
+     ?       Matches any character
+     $       Matches the end of the string
+     |       Matches if pattern on the left side or the right side matches.
+
+All other characters in the pattern match themselves. Examples:
+
+    **.cgi$      Any string that ends with .cgi
+    /foo         Any string that begins with /foo
+    **a$|**b$    Any string that ends with a or b
+
+# Configuration Options
+
+Below is a list of configuration options Civetweb understands. Every option
+is followed by it's default value. If default value is not present, then
+it is empty.
+
+### cgi_pattern `**.cgi$|**.pl$|**.php$`
+All files that match `cgi_pattern` are treated as CGI files. Default pattern
+allows CGI files be anywhere. To restrict CGIs to a certain directory,
+use `/path/to/cgi-bin/**.cgi` as pattern. Note that full file path is
+matched against the pattern, not the URI.
+
+### cgi_environment
+Extra environment variables to be passed to the CGI script in
+addition to standard ones. The list must be comma-separated list
+of name=value pairs, like this: `VARIABLE1=VALUE1,VARIABLE2=VALUE2`.
+
+### put\_delete\_auth\_file
+Passwords file for PUT and DELETE requests. Without it, PUT and DELETE requests
+will fail.
+
+### cgi_interpreter
+Path to an executable to use as CGI interpreter for __all__ CGI scripts
+regardless script extension. If this option is not set (which is a default),
+Civetweb looks at first line of a CGI script,
+[shebang line](http://en.wikipedia.org/wiki/Shebang_(Unix\)), for an interpreter.
+
+For example, if both PHP and perl CGIs are used, then
+`#!/path/to/php-cgi.exe` and `#!/path/to/perl.exe` must be first lines of the
+respective CGI scripts. Note that paths should be either full file paths,
+or file paths relative to the current working directory of civetweb server.
+If civetweb is started by mouse double-click on Windows, current working
+directory is a directory where civetweb executable is located.
+
+If all CGIs use the same interpreter, for example they are all PHP, then
+`cgi_interpreter` can be set to the path to `php-cgi.exe` executable and
+shebang line in the CGI scripts can be omitted.
+Note that PHP scripts must use `php-cgi.exe` executable, not `php.exe`.
+
+### protect_uri
+Comma separated list of URI=PATH pairs, specifying that given
+URIs must be protected with respected password files. Paths must be full
+file paths.
+
+### authentication_domain `mydomain.com`
+Authorization realm used in `.htpasswd` authorization.
+
+### ssi_pattern `**.shtml$|**.shtm$`
+All files that match `ssi_pattern` are treated as SSI.
+
+Server Side Includes (SSI) is a simple interpreted server-side scripting
+language which is most commonly used to include the contents of a file into
+a web page. It can be useful when it is desirable to include a common piece
+of code throughout a website, for example, headers and footers.
+
+In order for a webpage to recognize an SSI-enabled HTML file, the filename
+should end with a special extension, by default the extension should be
+either `.shtml` or `.shtm`.
+
+Unknown SSI directives are silently ignored by civetweb. Currently, two SSI
+directives are supported, `<!--#include ...>` and
+`<!--#exec "command">`. Note that `<!--#include ...>` directive supports
+three path specifications:
+
+    <!--#include virtual="path">  Path is relative to web server root
+    <!--#include abspath="path">  Path is absolute or relative to
+                                  web server working dir
+    <!--#include file="path">,    Path is relative to current document
+    <!--#include "path">
+
+The `include` directive may be used to include the contents of a file or the
+result of running a CGI script. The `exec` directive is used to execute a
+command on a server, and show command's output. Example:
+
+    <!--#exec "ls -l" -->
+
+For more information on Server Side Includes, take a look at the Wikipedia:
+[Server Side Includes](http://en.wikipedia.org/wiki/Server_Side_Includes)
+
+### throttle
+Limit download speed for clients.  `throttle` is a comma-separated
+list of key=value pairs, where key could be:
+
+    *                   limit speed for all connections
+    x.x.x.x/mask        limit speed for specified subnet
+    uri_prefix_pattern  limit speed for given URIs
+
+The value is a floating-point number of bytes per second, optionally
+followed by a `k` or `m` character, meaning kilobytes and
+megabytes respectively. A limit of 0 means unlimited rate. The
+last matching rule wins. Examples:
+
+    *=1k,10.0.0.0/8=0   limit all accesses to 1 kilobyte per second,
+                        but give connections from 10.0.0.0/8 subnet
+                        unlimited speed
+
+    /downloads/=5k      limit accesses to all URIs in `/downloads/` to
+                        5 kilobytes per second. All other accesses are unlimited
+
+### access\_log\_file
+Path to a file for access logs. Either full path, or relative to current
+working directory. If absent (default), then accesses are not logged.
+
+### enable\_directory\_listing `yes`
+Enable directory listing, either `yes` or `no`.
+
+### error\_log\_file
+Path to a file for error logs. Either full path, or relative to current
+working directory. If absent (default), then errors are not logged.
+
+### global\_auth\_file
+Path to a global passwords file, either full path or relative to the current
+working directory. If set, per-directory `.htpasswd` files are ignored,
+and all requests are authorized against that file.
+
+The file has to include the realm set through `authentication_domain` and the password in digest format:
+
+    user:realm:digest
+    test:test.com:ce0220efc2dd2fad6185e1f1af5a4327
+
+(e.g. use [this generator](http://www.askapache.com/online-tools/htpasswd-generator))
+
+### index_files `index.html,index.htm,index.cgi,index.shtml,index.php`
+Comma-separated list of files to be treated as directory index
+files.
+
+In case built-in Lua support has been enabled, `index.lp,index.lsp,index.lua`
+are additional default files.
+
+### enable\_keep\_alive `no`
+Enable connection keep alive, either `yes` or `no`.
+
+Experimental feature. Allows clients to reuse TCP connection for
+subsequent HTTP requests, which improves performance.
+For this to work when using request handlers it's important to add the correct
+Content-Length HTTP header for each request. If this is forgotten the client
+will time out.
+
+### access\_control\_list
+An Access Control List (ACL) allows restrictions to be put on the list of IP
+addresses which have access to the web server. In the case of the Civetweb
+web server, the ACL is a comma separated list of IP subnets, where each
+subnet is pre-pended by either a `-` or a `+` sign. A plus sign means allow,
+where a minus sign means deny. If a subnet mask is omitted, such as `-1.2.3.4`,
+this means to deny only that single IP address.
+
+Subnet masks may vary from 0 to 32, inclusive. The default setting is to allow
+all accesses. On each request the full list is traversed, and
+the last match wins. Examples:
+
+    -0.0.0.0/0,+192.168/16    deny all accesses, only allow 192.168/16 subnet
+
+To learn more about subnet masks, see the
+[Wikipedia page on Subnetwork](http://en.wikipedia.org/wiki/Subnetwork)
+
+### extra\_mime\_types
+Extra mime types to recognize, in form `extension1=type1,exten-
+sion2=type2,...`. Extension must include dot.  Example:
+`.cpp=plain/text,.java=plain/text`
+
+### listening_ports `8080`
+Comma-separated list of ports to listen on. If the port is SSL, a
+letter `s` must be appended, for example, `80,443s` will open
+port 80 and port 443, and connections on port 443 will be SSL-ed.
+For non-SSL ports, it is allowed to append letter `r`, meaning 'redirect'.
+Redirect ports will redirect all their traffic to the first configured
+SSL port. For example, if `listening_ports` is `80r,443s`, then all
+HTTP traffic coming at port 80 will be redirected to HTTPS port 443.
+
+It is possible to specify an IP address to bind to. In this case,
+an IP address and a colon must be pre-pended to the port number.
+For example, to bind to a loopback interface on port 80 and to
+all interfaces on HTTPS port 443, use `127.0.0.1:80,443s`.
+
+### document_root `.`
+A directory to serve. By default, current directory is served. Current
+directory is commonly referenced as dot (`.`).
+
+### ssl_certificate
+Path to SSL certificate file. This option is only required when at least one
+of the `listening_ports` is SSL. The file must be in PEM format,
+and it must have both private key and certificate, see for example
+[ssl_cert.pem](https://github.com/sunsetbrew/civetweb/blob/master/resources/ssl_cert.pem)
+A description how to create a certificate can be found in doc/OpenSSL.md
+
+### num_threads `50`
+Number of worker threads. Civetweb handles each incoming connection in a
+separate thread. Therefore, the value of this option is effectively a number
+of concurrent HTTP connections Civetweb can handle.
+
+### run\_as\_user
+Switch to given user credentials after startup. Usually, this option is
+required when civetweb needs to bind on privileged port on UNIX. To do
+that, civetweb needs to be started as root. But running as root is a bad idea,
+therefore this option can be used to drop privileges. Example:
+
+    civetweb -listening_ports 80 -run_as_user nobody
+
+### url\_rewrite\_patterns
+Comma-separated list of URL rewrites in the form of
+`uri_pattern=file_or_directory_path`. When Civetweb receives the request,
+it constructs the file name to show by combining `document_root` and the URI.
+However, if the rewrite option is used and `uri_pattern` matches the
+requested URI, then `document_root` is ignored. Instead,
+`file_or_directory_path` is used, which should be a full path name or
+a path relative to the web server's current working directory. Note that
+`uri_pattern`, as all civetweb patterns, is a prefix pattern.
+
+This makes it possible to serve many directories outside from `document_root`,
+redirect all requests to scripts, and do other tricky things. For example,
+to redirect all accesses to `.doc` files to a special script, do:
+
+    civetweb -url_rewrite_patterns **.doc$=/path/to/cgi-bin/handle_doc.cgi
+
+Or, to imitate user home directories support, do:
+
+    civetweb -url_rewrite_patterns /~joe/=/home/joe/,/~bill=/home/bill/
+
+### hide\_files\_patterns
+A pattern for the files to hide. Files that match the pattern will not
+show up in directory listing and return `404 Not Found` if requested. Pattern
+must be for a file name only, not including directory name. Example:
+
+    civetweb -hide_files_patterns secret.txt|even_more_secret.txt
+
+### request\_timeout\_ms `30000`
+Timeout for network read and network write operations, in milliseconds.
+If client intends to keep long-running connection, either increase this value
+or use keep-alive messages.
+
+### lua_preload_file
+This configuration option can be used to specify a Lua script file, which
+is executed before the actual web page script (Lua script, Lua server page
+or Lua websocket). It can be used to modify the Lua environment of all web
+page scripts, e.g., by loading additional libraries required by all scripts
+or to achieve backward compatibility by defining obsolete functions.
+
+### lua_script_pattern `"**.lua$`
+A pattern for files that are interpreted as Lua scripts by the server.
+In contrast to Lua server pages, Lua scripts use plain Lua syntax.
+An example can be found in the test directory.
+
+### lua_server_page_pattern `**.lp$|**.lsp$`
+Files matching this pattern are treated as Lua server pages.
+In contrast to Lua scripts, the content of a Lua server pages is delivered
+directly to the client. Lua script parts are delimited from the standard
+content by including them between <? and ?> tags.
+An example can be found in the test directory.
+
+### websocket_root
+In case civetweb is built with Lua and websocket support, Lua scripts may
+be used for websockets as well. Since websockets use a different URL scheme
+(ws, wss) than other http pages (http, https), the Lua scripts used for
+websockets may also be served from a different directory. By default,
+the document_root is used as websocket_root as well.
+
+
+# Lua Scripts and Lua Server Pages
+Pre-built Windows and Mac civetweb binaries have built-in Lua scripting
+support as well as support for Lua Server Pages.
+
+Lua scripts (default extension: *.lua) use plain Lua syntax.
+The body of the script file is not sent directly to the client,
+the Lua script must send header and content of the web page by calling
+the function mg.write(text).
+
+Lua Server Pages (default extensions: *.lsp, *.lp) are html pages containing
+script elements similar to PHP, using the Lua programming language instead of
+PHP. Lua script elements must be enclosed in `<?  ?>` blocks, and can appear
+anywhere on the page. Furthermore, Lua Server Pages offer the opportunity to
+insert the content of a variable by enclosing the Lua variable name in
+`<?=  ?>` blocks, similar to PHP.
+For example, to print current weekday name and the URI of the current page,
+one can write:
+    <p>
+      <span>Today is:</span>
+      <? mg.write(os.date("%A")) ?>
+    </p>
+    <p>
+      URI is <?=mg.request_info.uri?>
+    </p>
+
+Lua is known for it's speed and small size. Civetweb uses Lua version 5.2.2,
+the documentation for it can be found at
+[Lua 5.2 reference manual](http://www.lua.org/manual/5.2/).
+
+
+Note that this example uses function `mg.write()`, which prints data to the
+web page. Using function `mg.write()` is the way to generate web content from
+inside Lua code. In addition to `mg.write()`, all standard library functions
+are accessible from the Lua code (please check reference manual for details),
+and also information about the request is available in `mg.request_info`
+object, like request method, all headers, etcetera.
+
+[page2.lua](https://github.com/sunsetbrew/civetweb/blob/master/test/page2.lua)
+is an example for a plain Lua script.
+
+[page2.lp](https://github.com/sunsetbrew/civetweb/blob/master/test/page2.lp)
+is an example for a Lua Server Page.
+
+Both examples show the content of the `mg.request_info` object as the page
+content. Please refer to `struct mg_request_info` definition in
+[civetweb.h](https://github.com/sunsetbrew/civetweb/blob/master/include/civetweb.h)
+to see additional information on the elements of the `mg.request_info` object.
+
+Civetweb also provides access to the [SQlite3 database](http://www.sqlite.org/)
+through the [LuaSQLite3 interface](http://lua.sqlite.org/index.cgi/doc/tip/doc/lsqlite3.wiki)
+in Lua. An example is given in
+[page.lp](https://github.com/sunsetbrew/civetweb/blob/master/test/page.lp).
+
+
+Civetweb exports the following functions to Lua:
+
+mg (table):
+    mg.read()                  -- reads a chunk from POST data, returns it as a string
+    mg.write(str)              -- writes string to the client
+    mg.include(path)           -- sources another Lua file
+    mg.redirect(uri)           -- internal redirect to a given URI
+    mg.onerror(msg)            -- error handler, can be overridden
+    mg.version                 -- a string that holds Civetweb version
+    mg.document_root           -- a string that holds the document root directory
+    mg.auth_domain             -- a string that holds the HTTP authentication domain
+    mg.get_var(str, varname)   -- extract variable from (query) string
+    mg.get_cookie(str, cookie) -- extract cookie from a string
+    mg.get_mime_type(filename) -- get MIME type of a file
+    mg.send_file(filename)     -- send a file, including MIME type
+    mg.url_encode(str)         -- URL encode a string
+    mg.url_decode(str)         -- URL decode a string
+    mg.base64_encode(str)      -- BASE64 encode a string
+    mg.base64_decode(str)      -- BASE64 decode a string
+    mg.md5(str)                -- return the MD5 hash of a string
+    mg.keep_alive(bool)        -- allow/forbid to use http keep-alive for this request
+    mg.request_info            -- a table with the following request information
+         .remote_addr          -- IP address of the client as string
+         .remote_port          -- remote port number
+         .server_port          -- server port number
+         .request_method       -- HTTP method (e.g.: GET, POST)
+         .http_version         -- HTTP protocol version (e.g.: 1.1)
+         .uri                  -- resource name
+         .query_string         -- query string if present, nil otherwise
+         .script_name          -- name of the Lua script
+         .https                -- true if accessed by https://, false otherwise
+         .remote_user          -- user name if authenticated, nil otherwise
+
+connect (function):
+    -- Connect to the remote TCP server. This function is an implementation
+    -- of simple socket interface. It returns a socket object with three
+    -- methods: send, recv, close, which are synchronous (blocking).
+    -- connect() throws an exception on connection error.
+    connect(host, port, use_ssl)
+
+    -- Example of using connect() interface:
+    local host = 'code.google.com'  -- IP address or domain name
+    local ok, sock = pcall(connect, host, 80, 1)
+    if ok then
+      sock:send('GET /p/civetweb/ HTTP/1.0\r\n' ..
+                'Host: ' .. host .. '\r\n\r\n')
+      local reply = sock:recv()
+      sock:close()
+      -- reply now contains the web page https://code.google.com/p/civetweb
+    end
+
+
+**IMPORTANT: Civetweb does not send HTTP headers for Lua pages. Therefore,
+every Lua Page must begin with HTTP reply line and headers**, like this:
+
+    <? print('HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n') ?>
+    <html><body>
+      ... the rest of the web page ...
+
+To serve Lua Page, civetweb creates Lua context. That context is used for
+all Lua blocks within the page. That means, all Lua blocks on the same page
+share the same context. If one block defines a variable, for example, that
+variable is visible in the block that follows.
+
+# Common Problems
+- PHP doesn't work - getting empty page, or 'File not found' error. The
+  reason for that is wrong paths to the interpreter. Remember that with PHP,
+  correct interpreter is `php-cgi.exe` (`php-cgi` on UNIX). Solution: specify
+  full path to the PHP interpreter, e.g.:
+    `civetweb -cgi_interpreter /full/path/to/php-cgi`
+
+- Civetweb fails to start. If Civetweb exits immediately when run, this
+  usually indicates a syntax error in the configuration file
+  (named `civetweb.conf` by default) or the command-line arguments.
+  Syntax checking is omitted from Civetweb to keep its size low. However,
+  the Manual should be of help. Note: the syntax changes from time to time,
+  so updating the config file might be necessary after executable update.
+
+- Embedding with OpenSSL on Windows might fail because of calling convention.
+  To force Civetweb to use `__stdcall` convention, add `/Gz` compilation
+  flag in Visual Studio compiler.
+
diff --git a/src/civetweb/civetweb.c b/src/civetweb/civetweb.c
new file mode 100644
index 0000000..7adf4af
--- /dev/null
+++ b/src/civetweb/civetweb.c
@@ -0,0 +1,6555 @@
+/* Copyright (c) 2004-2013 Sergey Lyubka
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#if defined(_WIN32)
+#if !defined(_CRT_SECURE_NO_WARNINGS)
+#define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
+#endif
+#else
+#ifdef __linux__
+#define _XOPEN_SOURCE 600     /* For flockfile() on Linux */
+#endif
+#define _LARGEFILE_SOURCE     /* For fseeko(), ftello() */
+#define _FILE_OFFSET_BITS 64  /* Use 64-bit file offsets by default */
+#define __STDC_FORMAT_MACROS  /* <inttypes.h> wants this for C++ */
+#define __STDC_LIMIT_MACROS   /* C++ wants that for INT64_MAX */
+#endif
+
+#if defined (_MSC_VER)
+/* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
+#pragma warning (disable : 4306 )
+/* conditional expression is constant: introduced by FD_SET(..) */
+#pragma warning (disable : 4127)
+/* non-constant aggregate initializer: issued due to missing C99 support */
+#pragma warning (disable : 4204)
+#endif
+
+/* Disable WIN32_LEAN_AND_MEAN.
+   This makes windows.h always include winsock2.h */
+#if defined(WIN32_LEAN_AND_MEAN)
+#undef WIN32_LEAN_AND_MEAN
+#endif
+
+#if defined USE_IPV6 && defined(_WIN32)
+#include <ws2tcpip.h>
+#endif
+
+#if defined(__SYMBIAN32__)
+#define NO_SSL /* SSL is not supported */
+#define NO_CGI /* CGI is not supported */
+#define PATH_MAX FILENAME_MAX
+#endif /* __SYMBIAN32__ */
+
+#ifndef IGNORE_UNUSED_RESULT
+#define IGNORE_UNUSED_RESULT(a) (void)((a) && 1)
+#endif
+
+#ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <errno.h>
+#include <signal.h>
+#include <fcntl.h>
+#endif /* !_WIN32_WCE */
+
+#include <time.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <assert.h>
+#include <string.h>
+#include <ctype.h>
+#include <limits.h>
+#include <stddef.h>
+#include <stdio.h>
+
+#define MAX_WORKER_THREADS 1024
+
+#if defined(_WIN32) && !defined(__SYMBIAN32__) /* Windows specific */
+#if defined(_MSC_VER) && _MSC_VER <= 1400
+#undef _WIN32_WINNT
+#define _WIN32_WINNT 0x0400 /* To make it link in VS2005 */
+#endif
+#include <windows.h>
+
+#ifndef PATH_MAX
+#define PATH_MAX MAX_PATH
+#endif
+
+#ifndef _IN_PORT_T
+#ifndef in_port_t
+#define in_port_t u_short
+#endif
+#endif
+
+#ifndef _WIN32_WCE
+#include <process.h>
+#include <direct.h>
+#include <io.h>
+#else /* _WIN32_WCE */
+#define NO_CGI /* WinCE has no pipes */
+
+typedef long off_t;
+
+#define errno   GetLastError()
+#define strerror(x)  _ultoa(x, (char *) _alloca(sizeof(x) *3 ), 10)
+#endif /* _WIN32_WCE */
+
+#define MAKEUQUAD(lo, hi) ((uint64_t)(((uint32_t)(lo)) | \
+      ((uint64_t)((uint32_t)(hi))) << 32))
+#define RATE_DIFF 10000000 /* 100 nsecs */
+#define EPOCH_DIFF MAKEUQUAD(0xd53e8000, 0x019db1de)
+#define SYS2UNIX_TIME(lo, hi) \
+  (time_t) ((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF)
+
+/* Visual Studio 6 does not know __func__ or __FUNCTION__
+   The rest of MS compilers use __FUNCTION__, not C99 __func__
+   Also use _strtoui64 on modern M$ compilers */
+#if defined(_MSC_VER) && _MSC_VER < 1300
+#define STRX(x) #x
+#define STR(x) STRX(x)
+#define __func__ __FILE__ ":" STR(__LINE__)
+#define strtoull(x, y, z) (unsigned __int64) _atoi64(x)
+#define strtoll(x, y, z) _atoi64(x)
+#else
+#define __func__  __FUNCTION__
+#define strtoull(x, y, z) _strtoui64(x, y, z)
+#define strtoll(x, y, z) _strtoi64(x, y, z)
+#endif /* _MSC_VER */
+
+#define ERRNO   GetLastError()
+#define NO_SOCKLEN_T
+#define SSL_LIB   "ssleay32.dll"
+#define CRYPTO_LIB  "libeay32.dll"
+#define O_NONBLOCK  0
+#if !defined(EWOULDBLOCK)
+#define EWOULDBLOCK  WSAEWOULDBLOCK
+#endif /* !EWOULDBLOCK */
+#define _POSIX_
+#define INT64_FMT  "I64d"
+
+#define WINCDECL __cdecl
+#define SHUT_WR 1
+#define snprintf _snprintf
+#define vsnprintf _vsnprintf
+#define mg_sleep(x) Sleep(x)
+
+#define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
+#ifndef popen
+#define popen(x, y) _popen(x, y)
+#endif
+#ifndef pclose
+#define pclose(x) _pclose(x)
+#endif
+#define close(x) _close(x)
+#define dlsym(x,y) GetProcAddress((HINSTANCE) (x), (y))
+#define RTLD_LAZY  0
+#define fseeko(x, y, z) _lseeki64(_fileno(x), (y), (z))
+#define fdopen(x, y) _fdopen((x), (y))
+#define write(x, y, z) _write((x), (y), (unsigned) z)
+#define read(x, y, z) _read((x), (y), (unsigned) z)
+#define flockfile(x) EnterCriticalSection(&global_log_file_lock)
+#define funlockfile(x) LeaveCriticalSection(&global_log_file_lock)
+#define sleep(x) Sleep((x) * 1000)
+#define rmdir(x) _rmdir(x)
+
+#if !defined(va_copy)
+#define va_copy(x, y) x = y
+#endif /* !va_copy MINGW #defines va_copy */
+
+#if !defined(fileno)
+#define fileno(x) _fileno(x)
+#endif /* !fileno MINGW #defines fileno */
+
+typedef HANDLE pthread_mutex_t;
+typedef DWORD pthread_key_t;
+typedef HANDLE pthread_t;
+typedef struct {
+    CRITICAL_SECTION threadIdSec;
+    int waitingthreadcount;        /* The number of threads queued. */
+    pthread_t *waitingthreadhdls;  /* The thread handles. */
+} pthread_cond_t;
+
+typedef DWORD clockid_t;
+#define CLOCK_MONOTONIC (1)
+#define CLOCK_REALTIME  (2)
+
+struct timespec {
+    time_t   tv_sec;        /* seconds */
+    long     tv_nsec;       /* nanoseconds */
+};
+
+#define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
+
+static int pthread_mutex_lock(pthread_mutex_t *);
+static int pthread_mutex_unlock(pthread_mutex_t *);
+static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len);
+struct file;
+static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p);
+
+#if defined(HAVE_STDINT)
+#include <stdint.h>
+#else
+typedef unsigned int  uint32_t;
+typedef unsigned short  uint16_t;
+typedef unsigned __int64 uint64_t;
+typedef __int64   int64_t;
+#define INT64_MAX  9223372036854775807
+#endif /* HAVE_STDINT */
+
+/* POSIX dirent interface */
+struct dirent {
+    char d_name[PATH_MAX];
+};
+
+typedef struct DIR {
+    HANDLE   handle;
+    WIN32_FIND_DATAW info;
+    struct dirent  result;
+} DIR;
+
+#if !defined(USE_IPV6) && defined(_WIN32)
+#ifndef HAVE_POLL
+struct pollfd {
+    SOCKET fd;
+    short events;
+    short revents;
+};
+#define POLLIN 1
+#endif
+#endif
+
+/* Mark required libraries */
+#ifdef _MSC_VER
+#pragma comment(lib, "Ws2_32.lib")
+#endif
+
+#else    /* UNIX  specific */
+#include <sys/wait.h>
+#include <sys/socket.h>
+#include <sys/poll.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <sys/time.h>
+#include <stdint.h>
+#include <inttypes.h>
+#include <netdb.h>
+
+#if defined(ANDROID)
+typedef unsigned short int in_port_t;
+#endif
+
+#include <pwd.h>
+#include <unistd.h>
+#include <dirent.h>
+#if !defined(NO_SSL_DL) && !defined(NO_SSL)
+#include <dlfcn.h>
+#endif
+#include <pthread.h>
+#if defined(__MACH__)
+#define SSL_LIB   "libssl.dylib"
+#define CRYPTO_LIB  "libcrypto.dylib"
+#else
+#if !defined(SSL_LIB)
+#define SSL_LIB   "libssl.so"
+#endif
+#if !defined(CRYPTO_LIB)
+#define CRYPTO_LIB  "libcrypto.so"
+#endif
+#endif
+#ifndef O_BINARY
+#define O_BINARY  0
+#endif /* O_BINARY */
+#define closesocket(a) close(a)
+#define mg_mkdir(x, y) mkdir(x, y)
+#define mg_remove(x) remove(x)
+#define mg_sleep(x) usleep((x) * 1000)
+#define ERRNO errno
+#define INVALID_SOCKET (-1)
+#define INT64_FMT PRId64
+typedef int SOCKET;
+#define WINCDECL
+
+#endif /* End of Windows and UNIX specific includes */
+
+#include "civetweb.h"
+
+#define PASSWORDS_FILE_NAME ".htpasswd"
+#define CGI_ENVIRONMENT_SIZE 4096
+#define MAX_CGI_ENVIR_VARS 64
+#define MG_BUF_LEN 8192
+#ifndef MAX_REQUEST_SIZE
+#define MAX_REQUEST_SIZE 16384
+#endif
+#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
+
+#ifdef _WIN32
+static CRITICAL_SECTION global_log_file_lock;
+static DWORD pthread_self(void)
+{
+    return GetCurrentThreadId();
+}
+
+int pthread_key_create(pthread_key_t *key, void (*_must_be_zero)(void*) /* destructor function not supported for windows */)
+{
+    assert(_must_be_zero == NULL);
+    if ((key!=0) && (_must_be_zero == NULL)) {
+        *key = TlsAlloc();
+        return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
+    }
+    return -2;
+}
+
+int pthread_key_delete(pthread_key_t key)
+{
+    return TlsFree(key) ? 0 : 1;
+}
+
+int pthread_setspecific(pthread_key_t key, void * value)
+{
+    return TlsSetValue(key, value) ? 0 : 1;
+}
+
+void *pthread_getspecific(pthread_key_t key)
+{
+    return TlsGetValue(key);
+}
+#endif /* _WIN32 */
+
+#define MD5_STATIC static
+#include "md5.inl"
+
+#ifdef DEBUG_TRACE
+#undef DEBUG_TRACE
+#define DEBUG_TRACE(x)
+#else
+#if defined(DEBUG)
+#define DEBUG_TRACE(x) do { \
+  flockfile(stdout); \
+  printf("*** %lu.%p.%s.%d: ", \
+         (unsigned long) time(NULL), (void *) pthread_self(), \
+         __func__, __LINE__); \
+  printf x; \
+  putchar('\n'); \
+  fflush(stdout); \
+  funlockfile(stdout); \
+} while (0)
+#else
+#define DEBUG_TRACE(x)
+#endif /* DEBUG */
+#endif /* DEBUG_TRACE */
+
+/* Darwin prior to 7.0 and Win32 do not have socklen_t */
+#ifdef NO_SOCKLEN_T
+typedef int socklen_t;
+#endif /* NO_SOCKLEN_T */
+#define _DARWIN_UNLIMITED_SELECT
+
+#define IP_ADDR_STR_LEN 50  /* IPv6 hex string is 46 chars */
+
+#if !defined(MSG_NOSIGNAL)
+#define MSG_NOSIGNAL 0
+#endif
+
+#if !defined(SOMAXCONN)
+#define SOMAXCONN 100
+#endif
+
+#if !defined(PATH_MAX)
+#define PATH_MAX 4096
+#endif
+
+/* Size of the accepted socket queue */
+#if !defined(MGSQLEN)
+#define MGSQLEN 20
+#endif
+
+static const char *http_500_error = "Internal Server Error";
+
+#if defined(NO_SSL_DL)
+#include <openssl/ssl.h>
+#include <openssl/err.h>
+#else
+/* SSL loaded dynamically from DLL.
+   I put the prototypes here to be independent from OpenSSL source
+   installation. */
+
+typedef struct ssl_st SSL;
+typedef struct ssl_method_st SSL_METHOD;
+typedef struct ssl_ctx_st SSL_CTX;
+
+struct ssl_func {
+    const char *name;   /* SSL function name */
+    void  (*ptr)(void); /* Function pointer */
+};
+
+#define SSL_free (* (void (*)(SSL *)) ssl_sw[0].ptr)
+#define SSL_accept (* (int (*)(SSL *)) ssl_sw[1].ptr)
+#define SSL_connect (* (int (*)(SSL *)) ssl_sw[2].ptr)
+#define SSL_read (* (int (*)(SSL *, void *, int)) ssl_sw[3].ptr)
+#define SSL_write (* (int (*)(SSL *, const void *,int)) ssl_sw[4].ptr)
+#define SSL_get_error (* (int (*)(SSL *, int)) ssl_sw[5].ptr)
+#define SSL_set_fd (* (int (*)(SSL *, SOCKET)) ssl_sw[6].ptr)
+#define SSL_new (* (SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
+#define SSL_CTX_new (* (SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
+#define SSLv23_server_method (* (SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
+#define SSL_library_init (* (int (*)(void)) ssl_sw[10].ptr)
+#define SSL_CTX_use_PrivateKey_file (* (int (*)(SSL_CTX *, \
+        const char *, int)) ssl_sw[11].ptr)
+#define SSL_CTX_use_certificate_file (* (int (*)(SSL_CTX *, \
+        const char *, int)) ssl_sw[12].ptr)
+#define SSL_CTX_set_default_passwd_cb \
+  (* (void (*)(SSL_CTX *, mg_callback_t)) ssl_sw[13].ptr)
+#define SSL_CTX_free (* (void (*)(SSL_CTX *)) ssl_sw[14].ptr)
+#define SSL_load_error_strings (* (void (*)(void)) ssl_sw[15].ptr)
+#define SSL_CTX_use_certificate_chain_file \
+  (* (int (*)(SSL_CTX *, const char *)) ssl_sw[16].ptr)
+#define SSLv23_client_method (* (SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
+#define SSL_pending (* (int (*)(SSL *)) ssl_sw[18].ptr)
+#define SSL_CTX_set_verify (* (void (*)(SSL_CTX *, int, int)) ssl_sw[19].ptr)
+#define SSL_shutdown (* (int (*)(SSL *)) ssl_sw[20].ptr)
+
+#define CRYPTO_num_locks (* (int (*)(void)) crypto_sw[0].ptr)
+#define CRYPTO_set_locking_callback \
+  (* (void (*)(void (*)(int, int, const char *, int))) crypto_sw[1].ptr)
+#define CRYPTO_set_id_callback \
+  (* (void (*)(unsigned long (*)(void))) crypto_sw[2].ptr)
+#define ERR_get_error (* (unsigned long (*)(void)) crypto_sw[3].ptr)
+#define ERR_error_string (* (char * (*)(unsigned long,char *)) crypto_sw[4].ptr)
+
+/* set_ssl_option() function updates this array.
+   It loads SSL library dynamically and changes NULLs to the actual addresses
+   of respective functions. The macros above (like SSL_connect()) are really
+   just calling these functions indirectly via the pointer. */
+static struct ssl_func ssl_sw[] = {
+    {"SSL_free",   NULL},
+    {"SSL_accept",   NULL},
+    {"SSL_connect",   NULL},
+    {"SSL_read",   NULL},
+    {"SSL_write",   NULL},
+    {"SSL_get_error",  NULL},
+    {"SSL_set_fd",   NULL},
+    {"SSL_new",   NULL},
+    {"SSL_CTX_new",   NULL},
+    {"SSLv23_server_method", NULL},
+    {"SSL_library_init",  NULL},
+    {"SSL_CTX_use_PrivateKey_file", NULL},
+    {"SSL_CTX_use_certificate_file",NULL},
+    {"SSL_CTX_set_default_passwd_cb",NULL},
+    {"SSL_CTX_free",  NULL},
+    {"SSL_load_error_strings", NULL},
+    {"SSL_CTX_use_certificate_chain_file", NULL},
+    {"SSLv23_client_method", NULL},
+    {"SSL_pending", NULL},
+    {"SSL_CTX_set_verify", NULL},
+    {"SSL_shutdown",   NULL},
+    {NULL,    NULL}
+};
+
+/* Similar array as ssl_sw. These functions could be located in different
+   lib. */
+#if !defined(NO_SSL)
+static struct ssl_func crypto_sw[] = {
+    {"CRYPTO_num_locks",  NULL},
+    {"CRYPTO_set_locking_callback", NULL},
+    {"CRYPTO_set_id_callback", NULL},
+    {"ERR_get_error",  NULL},
+    {"ERR_error_string", NULL},
+    {NULL,    NULL}
+};
+#endif /* NO_SSL */
+#endif /* NO_SSL_DL */
+
+static const char *month_names[] = {
+    "Jan", "Feb", "Mar", "Apr", "May", "Jun",
+    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
+};
+
+/* Unified socket address. For IPv6 support, add IPv6 address structure
+   in the union u. */
+union usa {
+    struct sockaddr sa;
+    struct sockaddr_in sin;
+#if defined(USE_IPV6)
+    struct sockaddr_in6 sin6;
+#endif
+};
+
+/* Describes a string (chunk of memory). */
+struct vec {
+    const char *ptr;
+    size_t len;
+};
+
+struct file {
+    int is_directory;
+    time_t modification_time;
+    int64_t size;
+    FILE *fp;
+    const char *membuf;   /* Non-NULL if file data is in memory */
+    /* set to 1 if the content is gzipped
+       in which case we need a content-encoding: gzip header */
+    int gzipped;
+};
+#define STRUCT_FILE_INITIALIZER {0, 0, 0, NULL, NULL, 0}
+
+/* Describes listening socket, or socket which was accept()-ed by the master
+   thread and queued for future handling by the worker thread. */
+struct socket {
+    SOCKET sock;          /* Listening socket */
+    union usa lsa;        /* Local socket address */
+    union usa rsa;        /* Remote socket address */
+    unsigned is_ssl:1;    /* Is port SSL-ed */
+    unsigned ssl_redir:1; /* Is port supposed to redirect everything to SSL
+                             port */
+};
+
+/* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
+enum {
+    CGI_EXTENSIONS, CGI_ENVIRONMENT, PUT_DELETE_PASSWORDS_FILE, CGI_INTERPRETER,
+    PROTECT_URI, AUTHENTICATION_DOMAIN, SSI_EXTENSIONS, THROTTLE,
+    ACCESS_LOG_FILE, ENABLE_DIRECTORY_LISTING, ERROR_LOG_FILE,
+    GLOBAL_PASSWORDS_FILE, INDEX_FILES, ENABLE_KEEP_ALIVE, ACCESS_CONTROL_LIST,
+    EXTRA_MIME_TYPES, LISTENING_PORTS, DOCUMENT_ROOT, SSL_CERTIFICATE,
+    NUM_THREADS, RUN_AS_USER, REWRITE, HIDE_FILES, REQUEST_TIMEOUT,
+
+#if defined(USE_LUA)
+    LUA_PRELOAD_FILE, LUA_SCRIPT_EXTENSIONS, LUA_SERVER_PAGE_EXTENSIONS,
+#endif
+#if defined(USE_WEBSOCKET)
+    WEBSOCKET_ROOT,
+#endif
+#if defined(USE_LUA) && defined(USE_WEBSOCKET)
+    LUA_WEBSOCKET_EXTENSIONS,
+#endif
+
+    NUM_OPTIONS
+};
+
+static const char *config_options[] = {
+    "cgi_pattern", "**.cgi$|**.pl$|**.php$",
+    "cgi_environment", NULL,
+    "put_delete_auth_file", NULL,
+    "cgi_interpreter", NULL,
+    "protect_uri", NULL,
+    "authentication_domain", "mydomain.com",
+    "ssi_pattern", "**.shtml$|**.shtm$",
+    "throttle", NULL,
+    "access_log_file", NULL,
+    "enable_directory_listing", "yes",
+    "error_log_file", NULL,
+    "global_auth_file", NULL,
+    "index_files",
+#ifdef USE_LUA
+    "index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,index.shtml,index.php",
+#else
+    "index.html,index.htm,index.cgi,index.shtml,index.php",
+#endif
+    "enable_keep_alive", "no",
+    "access_control_list", NULL,
+    "extra_mime_types", NULL,
+    "listening_ports", "8080",
+    "document_root",  NULL,
+    "ssl_certificate", NULL,
+    "num_threads", "50",
+    "run_as_user", NULL,
+    "url_rewrite_patterns", NULL,
+    "hide_files_patterns", NULL,
+    "request_timeout_ms", "30000",
+
+#if defined(USE_LUA)
+    "lua_preload_file", NULL,
+    "lua_script_pattern", "**.lua$",
+    "lua_server_page_pattern", "**.lp$|**.lsp$",
+#endif
+#if defined(USE_WEBSOCKET)
+    "websocket_root", NULL,
+#endif
+#if defined(USE_LUA) && defined(USE_WEBSOCKET)
+    "lua_websocket_pattern", "**.lua$",
+#endif
+
+    NULL
+};
+
+struct mg_request_handler_info {
+    char *uri;
+    size_t uri_len;
+    mg_request_handler handler;
+    void *cbdata;
+    struct mg_request_handler_info *next;
+};
+
+struct mg_context {
+    volatile int stop_flag;         /* Should we stop event loop */
+    void *ssllib_dll_handle;        /* Store the ssl library handle. */
+    void *cryptolib_dll_handle;     /* Store the crypto library handle. */
+    SSL_CTX *ssl_ctx;               /* SSL context */
+    char *config[NUM_OPTIONS];      /* Civetweb configuration parameters */
+    struct mg_callbacks callbacks;  /* User-defined callback function */
+    void *user_data;                /* User-defined data */
+
+    struct socket *listening_sockets;
+    in_port_t *listening_ports;
+    int num_listening_sockets;
+
+    volatile int num_threads;  /* Number of threads */
+    pthread_mutex_t mutex;     /* Protects (max|num)_threads */
+    pthread_cond_t  cond;      /* Condvar for tracking workers terminations */
+
+    struct socket queue[MGSQLEN];   /* Accepted sockets */
+    volatile int sq_head;      /* Head of the socket queue */
+    volatile int sq_tail;      /* Tail of the socket queue */
+    pthread_cond_t sq_full;    /* Signaled when socket is produced */
+    pthread_cond_t sq_empty;   /* Signaled when socket is consumed */
+    pthread_t masterthreadid;  /* The master thread ID. */
+    int workerthreadcount;     /* The amount of worker threads. */
+    pthread_t *workerthreadids;/* The worker thread IDs. */
+
+    unsigned long start_time;  /* Server start time, used for authentication */
+    unsigned long nonce_count; /* Used nonces, used for authentication */
+
+    /* linked list of uri handlers */
+    struct mg_request_handler_info *request_handlers;
+};
+
+struct mg_connection {
+    struct mg_request_info request_info;
+    struct mg_context *ctx;
+    SSL *ssl;                   /* SSL descriptor */
+    SSL_CTX *client_ssl_ctx;    /* SSL context for client connections */
+    struct socket client;       /* Connected client */
+    time_t birth_time;          /* Time when request was received */
+    int64_t num_bytes_sent;     /* Total bytes sent to client */
+    int64_t content_len;        /* Content-Length header value */
+    int64_t consumed_content;   /* How many bytes of content have been read */
+    char *buf;                  /* Buffer for received data */
+    char *path_info;            /* PATH_INFO part of the URL */
+    int must_close;             /* 1 if connection must be closed */
+    int buf_size;               /* Buffer size */
+    int request_len;            /* Size of the request + headers in a buffer */
+    int data_len;               /* Total size of data in a buffer */
+    int status_code;            /* HTTP reply status code, e.g. 200 */
+    int throttle;               /* Throttling, bytes/sec. <= 0 means no
+                                   throttle */
+    time_t last_throttle_time;  /* Last time throttled data was sent */
+    int64_t last_throttle_bytes;/* Bytes sent this second */
+    pthread_mutex_t mutex;      /* Used by mg_lock/mg_unlock to ensure atomic
+                                   transmissions for websockets */
+#if defined(USE_LUA) && defined(USE_WEBSOCKET)
+    void * lua_websocket_state; /* Lua_State for a websocket connection */
+#endif
+};
+
+static pthread_key_t sTlsKey;  /* Thread local storage index */
+static int sTlsInit = 0;
+
+struct mg_workerTLS {
+    int is_master;
+#if defined(_WIN32) && !defined(__SYMBIAN32__)
+    HANDLE pthread_cond_helper_mutex;
+#endif
+};
+
+/* Directory entry */
+struct de {
+    struct mg_connection *conn;
+    char *file_name;
+    struct file file;
+};
+
+#if defined(USE_WEBSOCKET)
+static int is_websocket_request(const struct mg_connection *conn);
+#endif
+
+const char **mg_get_valid_option_names(void)
+{
+    return config_options;
+}
+
+static int is_file_in_memory(struct mg_connection *conn, const char *path,
+                             struct file *filep)
+{
+    size_t size = 0;
+    if ((filep->membuf = conn->ctx->callbacks.open_file == NULL ? NULL :
+                         conn->ctx->callbacks.open_file(conn, path, &size)) != NULL) {
+        /* NOTE: override filep->size only on success. Otherwise, it might
+           break constructs like if (!mg_stat() || !mg_fopen()) ... */
+        filep->size = size;
+    }
+    return filep->membuf != NULL;
+}
+
+static int is_file_opened(const struct file *filep)
+{
+    return filep->membuf != NULL || filep->fp != NULL;
+}
+
+static int mg_fopen(struct mg_connection *conn, const char *path,
+                    const char *mode, struct file *filep)
+{
+    if (!is_file_in_memory(conn, path, filep)) {
+#ifdef _WIN32
+        wchar_t wbuf[PATH_MAX], wmode[20];
+        to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
+        MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
+        filep->fp = _wfopen(wbuf, wmode);
+#else
+        filep->fp = fopen(path, mode);
+#endif
+    }
+
+    return is_file_opened(filep);
+}
+
+static void mg_fclose(struct file *filep)
+{
+    if (filep != NULL && filep->fp != NULL) {
+        fclose(filep->fp);
+    }
+}
+
+static int get_option_index(const char *name)
+{
+    int i;
+
+    for (i = 0; config_options[i * 2] != NULL; i++) {
+        if (strcmp(config_options[i * 2], name) == 0) {
+            return i;
+        }
+    }
+    return -1;
+}
+
+const char *mg_get_option(const struct mg_context *ctx, const char *name)
+{
+    int i;
+    if ((i = get_option_index(name)) == -1) {
+        return NULL;
+    } else if (ctx->config[i] == NULL) {
+        return "";
+    } else {
+        return ctx->config[i];
+    }
+}
+
+size_t mg_get_ports(const struct mg_context *ctx, size_t size, int* ports, int* ssl)
+{
+    size_t i;
+    for (i = 0; i < size && i < (size_t)ctx->num_listening_sockets; i++)
+    {
+        ssl[i] = ctx->listening_sockets[i].is_ssl;
+        ports[i] = ctx->listening_ports[i];
+    }
+    return i;
+}
+
+static void sockaddr_to_string(char *buf, size_t len,
+                               const union usa *usa)
+{
+    buf[0] = '\0';
+#if defined(USE_IPV6)
+    inet_ntop(usa->sa.sa_family, usa->sa.sa_family == AF_INET ?
+              (void *) &usa->sin.sin_addr :
+              (void *) &usa->sin6.sin6_addr, buf, len);
+#elif defined(_WIN32)
+    /* Only Windows Vista (and newer) have inet_ntop() */
+    strncpy(buf, inet_ntoa(usa->sin.sin_addr), len);
+#else
+    inet_ntop(usa->sa.sa_family, (void *) &usa->sin.sin_addr, buf, len);
+#endif
+}
+
+/* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be included in all responses other than 100, 101, 5xx. */
+static void gmt_time_string(char *buf, size_t buf_len, time_t *t)
+{
+    struct tm *tm;
+
+    tm = gmtime(t);
+    if (tm != NULL) {
+        strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
+    } else {
+        strncpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
+        buf[buf_len - 1] = '\0';
+    }
+}
+
+/* Print error message to the opened error log stream. */
+void mg_cry(struct mg_connection *conn, const char *fmt, ...)
+{
+    char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
+    va_list ap;
+    FILE *fp;
+    time_t timestamp;
+
+    va_start(ap, fmt);
+    IGNORE_UNUSED_RESULT(vsnprintf(buf, sizeof(buf), fmt, ap));
+    va_end(ap);
+
+    /* Do not lock when getting the callback value, here and below.
+       I suppose this is fine, since function cannot disappear in the
+       same way string option can. */
+    if (conn->ctx->callbacks.log_message == NULL ||
+        conn->ctx->callbacks.log_message(conn, buf) == 0) {
+        fp = conn->ctx->config[ERROR_LOG_FILE] == NULL ? NULL :
+             fopen(conn->ctx->config[ERROR_LOG_FILE], "a+");
+
+        if (fp != NULL) {
+            flockfile(fp);
+            timestamp = time(NULL);
+
+            sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
+            fprintf(fp, "[%010lu] [error] [client %s] ", (unsigned long) timestamp,
+                    src_addr);
+
+            if (conn->request_info.request_method != NULL) {
+                fprintf(fp, "%s %s: ", conn->request_info.request_method,
+                        conn->request_info.uri);
+            }
+
+            fprintf(fp, "%s", buf);
+            fputc('\n', fp);
+            funlockfile(fp);
+            fclose(fp);
+        }
+    }
+}
+
+/* Return fake connection structure. Used for logging, if connection
+   is not applicable at the moment of logging. */
+static struct mg_connection *fc(struct mg_context *ctx)
+{
+    static struct mg_connection fake_connection;
+    fake_connection.ctx = ctx;
+    return &fake_connection;
+}
+
+const char *mg_version(void)
+{
+    return CIVETWEB_VERSION;
+}
+
+struct mg_request_info *mg_get_request_info(struct mg_connection *conn)
+{
+    return &conn->request_info;
+}
+
+static void mg_strlcpy(register char *dst, register const char *src, size_t n)
+{
+    for (; *src != '\0' && n > 1; n--) {
+        *dst++ = *src++;
+    }
+    *dst = '\0';
+}
+
+static int lowercase(const char *s)
+{
+    return tolower(* (const unsigned char *) s);
+}
+
+int mg_strncasecmp(const char *s1, const char *s2, size_t len)
+{
+    int diff = 0;
+
+    if (len > 0)
+        do {
+            diff = lowercase(s1++) - lowercase(s2++);
+        } while (diff == 0 && s1[-1] != '\0' && --len > 0);
+
+    return diff;
+}
+
+static int mg_strcasecmp(const char *s1, const char *s2)
+{
+    int diff;
+
+    do {
+        diff = lowercase(s1++) - lowercase(s2++);
+    } while (diff == 0 && s1[-1] != '\0');
+
+    return diff;
+}
+
+static char * mg_strndup(const char *ptr, size_t len)
+{
+    char *p;
+
+    if ((p = (char *) malloc(len + 1)) != NULL) {
+        mg_strlcpy(p, ptr, len + 1);
+    }
+
+    return p;
+}
+
+static char * mg_strdup(const char *str)
+{
+    return mg_strndup(str, strlen(str));
+}
+
+static const char *mg_strcasestr(const char *big_str, const char *small_str)
+{
+    int i, big_len = (int)strlen(big_str), small_len = (int)strlen(small_str);
+
+    for (i = 0; i <= big_len - small_len; i++) {
+        if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
+            return big_str + i;
+        }
+    }
+
+    return NULL;
+}
+
+/* Like snprintf(), but never returns negative value, or a value
+   that is larger than a supplied buffer.
+   Thanks to Adam Zeldis to pointing snprintf()-caused vulnerability
+   in his audit report. */
+static int mg_vsnprintf(struct mg_connection *conn, char *buf, size_t buflen,
+                        const char *fmt, va_list ap)
+{
+    int n;
+
+    if (buflen == 0)
+        return 0;
+
+    n = vsnprintf(buf, buflen, fmt, ap);
+
+    if (n < 0) {
+        mg_cry(conn, "vsnprintf error");
+        n = 0;
+    } else if (n >= (int) buflen) {
+        mg_cry(conn, "truncating vsnprintf buffer: [%.*s]",
+               n > 200 ? 200 : n, buf);
+        n = (int) buflen - 1;
+    }
+    buf[n] = '\0';
+
+    return n;
+}
+
+static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,
+                       PRINTF_FORMAT_STRING(const char *fmt), ...)
+PRINTF_ARGS(4, 5);
+
+static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,
+                       const char *fmt, ...)
+{
+    va_list ap;
+    int n;
+
+    va_start(ap, fmt);
+    n = mg_vsnprintf(conn, buf, buflen, fmt, ap);
+    va_end(ap);
+
+    return n;
+}
+
+/* Skip the characters until one of the delimiters characters found.
+   0-terminate resulting word. Skip the delimiter and following whitespaces.
+   Advance pointer to buffer to the next word. Return found 0-terminated word.
+   Delimiters can be quoted with quotechar. */
+static char *skip_quoted(char **buf, const char *delimiters,
+                         const char *whitespace, char quotechar)
+{
+    char *p, *begin_word, *end_word, *end_whitespace;
+
+    begin_word = *buf;
+    end_word = begin_word + strcspn(begin_word, delimiters);
+
+    /* Check for quotechar */
+    if (end_word > begin_word) {
+        p = end_word - 1;
+        while (*p == quotechar) {
+            /* If there is anything beyond end_word, copy it */
+            if (*end_word == '\0') {
+                *p = '\0';
+                break;
+            } else {
+                size_t end_off = strcspn(end_word + 1, delimiters);
+                memmove (p, end_word, end_off + 1);
+                p += end_off; /* p must correspond to end_word - 1 */
+                end_word += end_off + 1;
+            }
+        }
+        for (p++; p < end_word; p++) {
+            *p = '\0';
+        }
+    }
+
+    if (*end_word == '\0') {
+        *buf = end_word;
+    } else {
+        end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
+
+        for (p = end_word; p < end_whitespace; p++) {
+            *p = '\0';
+        }
+
+        *buf = end_whitespace;
+    }
+
+    return begin_word;
+}
+
+/* Simplified version of skip_quoted without quote char
+   and whitespace == delimiters */
+static char *skip(char **buf, const char *delimiters)
+{
+    return skip_quoted(buf, delimiters, delimiters, 0);
+}
+
+
+/* Return HTTP header value, or NULL if not found. */
+static const char *get_header(const struct mg_request_info *ri,
+                              const char *name)
+{
+    int i;
+
+    for (i = 0; i < ri->num_headers; i++)
+        if (!mg_strcasecmp(name, ri->http_headers[i].name))
+            return ri->http_headers[i].value;
+
+    return NULL;
+}
+
+const char *mg_get_header(const struct mg_connection *conn, const char *name)
+{
+    return get_header(&conn->request_info, name);
+}
+
+/* A helper function for traversing a comma separated list of values.
+   It returns a list pointer shifted to the next value, or NULL if the end
+   of the list found.
+   Value is stored in val vector. If value has form "x=y", then eq_val
+   vector is initialized to point to the "y" part, and val vector length
+   is adjusted to point only to "x". */
+static const char *next_option(const char *list, struct vec *val,
+                               struct vec *eq_val)
+{
+    if (list == NULL || *list == '\0') {
+        /* End of the list */
+        list = NULL;
+    } else {
+        val->ptr = list;
+        if ((list = strchr(val->ptr, ',')) != NULL) {
+            /* Comma found. Store length and shift the list ptr */
+            val->len = list - val->ptr;
+            list++;
+        } else {
+            /* This value is the last one */
+            list = val->ptr + strlen(val->ptr);
+            val->len = list - val->ptr;
+        }
+
+        if (eq_val != NULL) {
+            /* Value has form "x=y", adjust pointers and lengths
+               so that val points to "x", and eq_val points to "y". */
+            eq_val->len = 0;
+            eq_val->ptr = (const char *) memchr(val->ptr, '=', val->len);
+            if (eq_val->ptr != NULL) {
+                eq_val->ptr++;  /* Skip over '=' character */
+                eq_val->len = val->ptr + val->len - eq_val->ptr;
+                val->len = (eq_val->ptr - val->ptr) - 1;
+            }
+        }
+    }
+
+    return list;
+}
+
+/* Perform case-insensitive match of string against pattern */
+static int match_prefix(const char *pattern, int pattern_len, const char *str)
+{
+    const char *or_str;
+    int i, j, len, res;
+
+    if ((or_str = (const char *) memchr(pattern, '|', pattern_len)) != NULL) {
+        res = match_prefix(pattern, (int)(or_str - pattern), str);
+        return res > 0 ? res :
+               match_prefix(or_str + 1, (int)((pattern + pattern_len) - (or_str + 1)), str);
+    }
+
+    i = j = 0;
+    res = -1;
+    for (; i < pattern_len; i++, j++) {
+        if (pattern[i] == '?' && str[j] != '\0') {
+            continue;
+        } else if (pattern[i] == '$') {
+            return str[j] == '\0' ? j : -1;
+        } else if (pattern[i] == '*') {
+            i++;
+            if (pattern[i] == '*') {
+                i++;
+                len = (int) strlen(str + j);
+            } else {
+                len = (int) strcspn(str + j, "/");
+            }
+            if (i == pattern_len) {
+                return j + len;
+            }
+            do {
+                res = match_prefix(pattern + i, pattern_len - i, str + j + len);
+            } while (res == -1 && len-- > 0);
+            return res == -1 ? -1 : j + res + len;
+        } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
+            return -1;
+        }
+    }
+    return j;
+}
+
+/* HTTP 1.1 assumes keep alive if "Connection:" header is not set
+   This function must tolerate situations when connection info is not
+   set up, for example if request parsing failed. */
+static int should_keep_alive(const struct mg_connection *conn)
+{
+    const char *http_version = conn->request_info.http_version;
+    const char *header = mg_get_header(conn, "Connection");
+    if (conn->must_close ||
+        conn->status_code == 401 ||
+        mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0 ||
+        (header != NULL && mg_strcasecmp(header, "keep-alive") != 0) ||
+        (header == NULL && http_version && strcmp(http_version, "1.1"))) {
+        return 0;
+    }
+    return 1;
+}
+
+static const char *suggest_connection_header(const struct mg_connection *conn)
+{
+    return should_keep_alive(conn) ? "keep-alive" : "close";
+}
+
+static void send_http_error(struct mg_connection *, int, const char *,
+                            PRINTF_FORMAT_STRING(const char *fmt), ...)
+PRINTF_ARGS(4, 5);
+
+
+static void send_http_error(struct mg_connection *conn, int status,
+                            const char *reason, const char *fmt, ...)
+{
+    char buf[MG_BUF_LEN];
+    va_list ap;
+    int len = 0;
+    char date[64];
+    time_t curtime = time(NULL);
+
+    conn->status_code = status;
+    if (conn->ctx->callbacks.http_error == NULL ||
+        conn->ctx->callbacks.http_error(conn, status)) {
+        buf[0] = '\0';
+
+        gmt_time_string(date, sizeof(date), &curtime);
+
+        /* Errors 1xx, 204 and 304 MUST NOT send a body */
+        if (status > 199 && status != 204 && status != 304) {
+            len = mg_snprintf(conn, buf, sizeof(buf), "Error %d: %s", status, reason);
+            buf[len++] = '\n';
+
+            va_start(ap, fmt);
+            len += mg_vsnprintf(conn, buf + len, sizeof(buf) - len, fmt, ap);
+            va_end(ap);
+        }
+        DEBUG_TRACE(("[%s]", buf));
+
+        mg_printf(conn, "HTTP/1.1 %d %s\r\n"
+                        "Content-Length: %d\r\n"
+                        "Date: %s\r\n"
+                        "Connection: %s\r\n\r\n",
+                        status, reason, len, date,
+                        suggest_connection_header(conn));
+        conn->num_bytes_sent += mg_printf(conn, "%s", buf);
+    }
+}
+
+#if defined(_WIN32) && !defined(__SYMBIAN32__)
+static int pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
+{
+    (void) unused;
+    *mutex = CreateMutex(NULL, FALSE, NULL);
+    return *mutex == NULL ? -1 : 0;
+}
+
+static int pthread_mutex_destroy(pthread_mutex_t *mutex)
+{
+    return CloseHandle(*mutex) == 0 ? -1 : 0;
+}
+
+static int pthread_mutex_lock(pthread_mutex_t *mutex)
+{
+    return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1;
+}
+
+static int pthread_mutex_unlock(pthread_mutex_t *mutex)
+{
+    return ReleaseMutex(*mutex) == 0 ? -1 : 0;
+}
+
+static int clock_gettime(clockid_t clk_id, struct timespec *tp)
+{
+    FILETIME ft;
+    ULARGE_INTEGER li;
+    BOOL ok = FALSE;
+    double d;
+    static double perfcnt_per_sec = 0.0;
+
+    if (tp) {
+        if (clk_id == CLOCK_REALTIME) {
+            GetSystemTimeAsFileTime(&ft);
+            li.LowPart = ft.dwLowDateTime;
+            li.HighPart = ft.dwHighDateTime;
+            li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
+            tp->tv_sec = (time_t)(li.QuadPart / 10000000);
+            tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
+            ok = TRUE;
+        } else if (clk_id == CLOCK_MONOTONIC) {
+            if (perfcnt_per_sec==0) {
+                QueryPerformanceFrequency((LARGE_INTEGER *) &li);
+                perfcnt_per_sec = 1.0 / li.QuadPart;
+            }
+            if (perfcnt_per_sec!=0) {
+                QueryPerformanceCounter((LARGE_INTEGER *) &li);
+                d = li.QuadPart * perfcnt_per_sec;
+                tp->tv_sec = (time_t)d;
+                d -= tp->tv_sec;
+                tp->tv_nsec = (long)(d*1.0E9);
+                ok = TRUE;
+            }
+        }
+    }
+
+    return ok ? 0 : -1;
+}
+
+static int pthread_cond_init(pthread_cond_t *cv, const void *unused)
+{
+    (void) unused;
+    InitializeCriticalSection(&cv->threadIdSec);
+    cv->waitingthreadcount = 0;
+    cv->waitingthreadhdls = calloc(MAX_WORKER_THREADS, sizeof(pthread_t));
+    return (cv->waitingthreadhdls!=NULL) ? 0 : -1;
+}
+
+static int pthread_cond_timedwait(pthread_cond_t *cv, pthread_mutex_t *mutex, const struct timespec * abstime)
+{
+    struct mg_workerTLS * tls = (struct mg_workerTLS *)TlsGetValue(sTlsKey);
+    int ok;
+    struct timespec tsnow;
+    int64_t nsnow, nswaitabs, nswaitrel;
+    DWORD mswaitrel;
+
+    EnterCriticalSection(&cv->threadIdSec);
+    assert(cv->waitingthreadcount < MAX_WORKER_THREADS);
+    cv->waitingthreadhdls[cv->waitingthreadcount] = tls->pthread_cond_helper_mutex;
+    cv->waitingthreadcount++;
+    LeaveCriticalSection(&cv->threadIdSec);
+
+    if (abstime) {
+        clock_gettime(CLOCK_REALTIME, &tsnow);
+        nsnow = (((uint64_t)tsnow.tv_sec)<<32) + tsnow.tv_nsec;
+        nswaitabs = (((uint64_t)abstime->tv_sec)<<32) + abstime->tv_nsec;
+        nswaitrel = nswaitabs - nsnow;
+        if (nswaitrel<0) nswaitrel=0;
+        mswaitrel = (DWORD)(nswaitrel / 1000000);
+    } else {
+        mswaitrel = INFINITE;
+    }
+
+    pthread_mutex_unlock(mutex);
+    ok = (WAIT_OBJECT_0 == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
+    pthread_mutex_lock(mutex);
+
+    return ok ? 0 : -1;
+}
+
+static int pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
+{
+    return pthread_cond_timedwait(cv, mutex, NULL);
+}
+
+static int pthread_cond_signal(pthread_cond_t *cv)
+{
+    int i;
+    HANDLE wkup = NULL;
+    BOOL ok = FALSE;
+
+    EnterCriticalSection(&cv->threadIdSec);
+    if (cv->waitingthreadcount) {
+        wkup = cv->waitingthreadhdls[0];
+        ok = SetEvent(wkup);
+
+        for (i=1; i<cv->waitingthreadcount; i++) {
+            cv->waitingthreadhdls[i-1] = cv->waitingthreadhdls[i];
+        }
+        cv->waitingthreadcount--;
+
+        assert(ok);
+    }
+    LeaveCriticalSection(&cv->threadIdSec);
+
+    return ok ? 0 : 1;
+}
+
+static int pthread_cond_broadcast(pthread_cond_t *cv)
+{
+    EnterCriticalSection(&cv->threadIdSec);
+    while (cv->waitingthreadcount) {
+        pthread_cond_signal(cv);
+    }
+    LeaveCriticalSection(&cv->threadIdSec);
+
+    return 0;
+}
+
+static int pthread_cond_destroy(pthread_cond_t *cv)
+{
+    EnterCriticalSection(&cv->threadIdSec);
+    assert(cv->waitingthreadcount==0);
+    cv->waitingthreadhdls = 0;
+    free(cv->waitingthreadhdls);
+    LeaveCriticalSection(&cv->threadIdSec);
+    DeleteCriticalSection(&cv->threadIdSec);
+
+    return 0;
+}
+
+/* For Windows, change all slashes to backslashes in path names. */
+static void change_slashes_to_backslashes(char *path)
+{
+    int i;
+
+    for (i = 0; path[i] != '\0'; i++) {
+        if (path[i] == '/')
+            path[i] = '\\';
+        /* i > 0 check is to preserve UNC paths, like \\server\file.txt */
+        if (path[i] == '\\' && i > 0)
+            while (path[i + 1] == '\\' || path[i + 1] == '/')
+                (void) memmove(path + i + 1,
+                               path + i + 2, strlen(path + i + 1));
+    }
+}
+
+/* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
+   wbuf and wbuf_len is a target buffer and its length. */
+static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len)
+{
+    char buf[PATH_MAX], buf2[PATH_MAX];
+
+    mg_strlcpy(buf, path, sizeof(buf));
+    change_slashes_to_backslashes(buf);
+
+    /* Convert to Unicode and back. If doubly-converted string does not
+       match the original, something is fishy, reject. */
+    memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
+    MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
+    WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
+                        NULL, NULL);
+    if (strcmp(buf, buf2) != 0) {
+        wbuf[0] = L'\0';
+    }
+}
+
+#if defined(_WIN32_WCE)
+static time_t time(time_t *ptime)
+{
+    time_t t;
+    SYSTEMTIME st;
+    FILETIME ft;
+
+    GetSystemTime(&st);
+    SystemTimeToFileTime(&st, &ft);
+    t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
+
+    if (ptime != NULL) {
+        *ptime = t;
+    }
+
+    return t;
+}
+
+static struct tm *localtime(const time_t *ptime, struct tm *ptm)
+{
+    int64_t t = ((int64_t) *ptime) * RATE_DIFF + EPOCH_DIFF;
+    FILETIME ft, lft;
+    SYSTEMTIME st;
+    TIME_ZONE_INFORMATION tzinfo;
+
+    if (ptm == NULL) {
+        return NULL;
+    }
+
+    * (int64_t *) &ft = t;
+    FileTimeToLocalFileTime(&ft, &lft);
+    FileTimeToSystemTime(&lft, &st);
+    ptm->tm_year = st.wYear - 1900;
+    ptm->tm_mon = st.wMonth - 1;
+    ptm->tm_wday = st.wDayOfWeek;
+    ptm->tm_mday = st.wDay;
+    ptm->tm_hour = st.wHour;
+    ptm->tm_min = st.wMinute;
+    ptm->tm_sec = st.wSecond;
+    ptm->tm_yday = 0; /* hope nobody uses this */
+    ptm->tm_isdst =
+        GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;
+
+    return ptm;
+}
+
+static struct tm *gmtime(const time_t *ptime, struct tm *ptm)
+{
+    /* FIXME(lsm): fix this. */
+    return localtime(ptime, ptm);
+}
+
+static size_t strftime(char *dst, size_t dst_size, const char *fmt,
+                       const struct tm *tm)
+{
+    (void) snprintf(dst, dst_size, "implement strftime() for WinCE");
+    return 0;
+}
+#endif
+
+/* Windows happily opens files with some garbage at the end of file name.
+   For example, fopen("a.cgi    ", "r") on Windows successfully opens
+   "a.cgi", despite one would expect an error back.
+   This function returns non-0 if path ends with some garbage. */
+static int path_cannot_disclose_cgi(const char *path)
+{
+    static const char *allowed_last_characters = "_-";
+    int last = path[strlen(path) - 1];
+    return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
+}
+
+static int mg_stat(struct mg_connection *conn, const char *path,
+                   struct file *filep)
+{
+    wchar_t wbuf[PATH_MAX];
+    WIN32_FILE_ATTRIBUTE_DATA info;
+
+    if (!is_file_in_memory(conn, path, filep)) {
+        to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
+        if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
+            filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
+            filep->modification_time = SYS2UNIX_TIME(
+                                           info.ftLastWriteTime.dwLowDateTime,
+                                           info.ftLastWriteTime.dwHighDateTime);
+            filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
+            /* If file name is fishy, reset the file structure and return
+               error.
+               Note it is important to reset, not just return the error, cause
+               functions like is_file_opened() check the struct. */
+            if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
+                memset(filep, 0, sizeof(*filep));
+            }
+        }
+    }
+
+    return filep->membuf != NULL || filep->modification_time != 0;
+}
+
+static int mg_remove(const char *path)
+{
+    wchar_t wbuf[PATH_MAX];
+    to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
+    return DeleteFileW(wbuf) ? 0 : -1;
+}
+
+static int mg_mkdir(const char *path, int mode)
+{
+    char buf[PATH_MAX];
+    wchar_t wbuf[PATH_MAX];
+
+    (void) mode;
+    mg_strlcpy(buf, path, sizeof(buf));
+    change_slashes_to_backslashes(buf);
+
+    (void) MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, ARRAY_SIZE(wbuf));
+
+    return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
+}
+
+/* Implementation of POSIX opendir/closedir/readdir for Windows. */
+static DIR * opendir(const char *name)
+{
+    DIR *dir = NULL;
+    wchar_t wpath[PATH_MAX];
+    DWORD attrs;
+
+    if (name == NULL) {
+        SetLastError(ERROR_BAD_ARGUMENTS);
+    } else if ((dir = (DIR *) malloc(sizeof(*dir))) == NULL) {
+        SetLastError(ERROR_NOT_ENOUGH_MEMORY);
+    } else {
+        to_unicode(name, wpath, ARRAY_SIZE(wpath));
+        attrs = GetFileAttributesW(wpath);
+        if (attrs != 0xFFFFFFFF &&
+            ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {
+            (void) wcscat(wpath, L"\\*");
+            dir->handle = FindFirstFileW(wpath, &dir->info);
+            dir->result.d_name[0] = '\0';
+        } else {
+            free(dir);
+            dir = NULL;
+        }
+    }
+
+    return dir;
+}
+
+static int closedir(DIR *dir)
+{
+    int result = 0;
+
+    if (dir != NULL) {
+        if (dir->handle != INVALID_HANDLE_VALUE)
+            result = FindClose(dir->handle) ? 0 : -1;
+
+        free(dir);
+    } else {
+        result = -1;
+        SetLastError(ERROR_BAD_ARGUMENTS);
+    }
+
+    return result;
+}
+
+static struct dirent *readdir(DIR *dir)
+{
+    struct dirent *result = 0;
+
+    if (dir) {
+        if (dir->handle != INVALID_HANDLE_VALUE) {
+            result = &dir->result;
+            (void) WideCharToMultiByte(CP_UTF8, 0,
+                                       dir->info.cFileName, -1, result->d_name,
+                                       sizeof(result->d_name), NULL, NULL);
+
+            if (!FindNextFileW(dir->handle, &dir->info)) {
+                (void) FindClose(dir->handle);
+                dir->handle = INVALID_HANDLE_VALUE;
+            }
+
+        } else {
+            SetLastError(ERROR_FILE_NOT_FOUND);
+        }
+    } else {
+        SetLastError(ERROR_BAD_ARGUMENTS);
+    }
+
+    return result;
+}
+
+#ifndef HAVE_POLL
+static int poll(struct pollfd *pfd, int n, int milliseconds)
+{
+    struct timeval tv;
+    fd_set set;
+    int i, result;
+    SOCKET maxfd = 0;
+
+    tv.tv_sec = milliseconds / 1000;
+    tv.tv_usec = (milliseconds % 1000) * 1000;
+    FD_ZERO(&set);
+
+    for (i = 0; i < n; i++) {
+        FD_SET((SOCKET) pfd[i].fd, &set);
+        pfd[i].revents = 0;
+
+        if (pfd[i].fd > maxfd) {
+            maxfd = pfd[i].fd;
+        }
+    }
+
+    if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
+        for (i = 0; i < n; i++) {
+            if (FD_ISSET(pfd[i].fd, &set)) {
+                pfd[i].revents = POLLIN;
+            }
+        }
+    }
+
+    return result;
+}
+#endif /* HAVE_POLL */
+
+static void set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
+{
+    (void) conn; /* Unused. */
+    (void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0);
+}
+
+int mg_start_thread(mg_thread_func_t f, void *p)
+{
+#if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
+    /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384 */
+    return (long)_beginthread((void (__cdecl *)(void *)) f, USE_STACK_SIZE, p) == -1L ? -1 : 0;
+#else
+    return (long)_beginthread((void (__cdecl *)(void *)) f, 0, p) == -1L ? -1 : 0;
+#endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
+}
+
+/* Start a thread storing the thread context. */
+
+static int mg_start_thread_with_id(unsigned (__stdcall *f)(void *), void *p,
+                                   pthread_t *threadidptr)
+{
+    uintptr_t uip;
+    HANDLE threadhandle;
+    int result;
+
+    uip = _beginthreadex(NULL, 0, (unsigned (__stdcall *)(void *)) f, p, 0,
+                         NULL);
+    threadhandle = (HANDLE) uip;
+    if (threadidptr != NULL) {
+        *threadidptr = threadhandle;
+    }
+    result = (threadhandle == NULL) ? -1 : 0;
+
+    return result;
+}
+
+/* Wait for a thread to finish. */
+
+static int mg_join_thread(pthread_t threadid)
+{
+    int result;
+    DWORD dwevent;
+
+    result = -1;
+    dwevent = WaitForSingleObject(threadid, INFINITE);
+    if (dwevent == WAIT_FAILED) {
+        int err;
+
+        err = GetLastError();
+        DEBUG_TRACE(("WaitForSingleObject() failed, error %d", err));
+    } else {
+        if (dwevent == WAIT_OBJECT_0) {
+            CloseHandle(threadid);
+            result = 0;
+        }
+    }
+
+    return result;
+}
+
+static HANDLE dlopen(const char *dll_name, int flags)
+{
+    wchar_t wbuf[PATH_MAX];
+    (void) flags;
+    to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));
+    return LoadLibraryW(wbuf);
+}
+
+static int dlclose(void *handle)
+{
+    int result;
+
+    if (FreeLibrary(handle) != 0) {
+        result = 0;
+    } else {
+        result = -1;
+    }
+
+    return result;
+}
+
+#if !defined(NO_CGI)
+#define SIGKILL 0
+static int kill(pid_t pid, int sig_num)
+{
+    (void) TerminateProcess(pid, sig_num);
+    (void) CloseHandle(pid);
+    return 0;
+}
+
+static void trim_trailing_whitespaces(char *s)
+{
+    char *e = s + strlen(s) - 1;
+    while (e > s && isspace(* (unsigned char *) e)) {
+        *e-- = '\0';
+    }
+}
+
+static pid_t spawn_process(struct mg_connection *conn, const char *prog,
+                           char *envblk, char *envp[], int fdin,
+                           int fdout, const char *dir)
+{
+    HANDLE me;
+    char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
+         cmdline[PATH_MAX], buf[PATH_MAX];
+    struct file file = STRUCT_FILE_INITIALIZER;
+    STARTUPINFOA si;
+    PROCESS_INFORMATION pi = { 0 };
+
+    (void) envp;
+
+    memset(&si, 0, sizeof(si));
+    si.cb = sizeof(si);
+
+    /* TODO(lsm): redirect CGI errors to the error log file */
+    si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
+    si.wShowWindow = SW_HIDE;
+
+    me = GetCurrentProcess();
+    DuplicateHandle(me, (HANDLE) _get_osfhandle(fdin), me,
+                    &si.hStdInput, 0, TRUE, DUPLICATE_SAME_ACCESS);
+    DuplicateHandle(me, (HANDLE) _get_osfhandle(fdout), me,
+                    &si.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS);
+
+    /* If CGI file is a script, try to read the interpreter line */
+    interp = conn->ctx->config[CGI_INTERPRETER];
+    if (interp == NULL) {
+        buf[0] = buf[1] = '\0';
+
+        /* Read the first line of the script into the buffer */
+        snprintf(cmdline, sizeof(cmdline), "%s%c%s", dir, '/', prog);
+        if (mg_fopen(conn, cmdline, "r", &file)) {
+            p = (char *) file.membuf;
+            mg_fgets(buf, sizeof(buf), &file, &p);
+            mg_fclose(&file);
+            buf[sizeof(buf) - 1] = '\0';
+        }
+
+        if (buf[0] == '#' && buf[1] == '!') {
+            trim_trailing_whitespaces(buf + 2);
+        } else {
+            buf[2] = '\0';
+        }
+        interp = buf + 2;
+    }
+
+    if (interp[0] != '\0') {
+        GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
+        interp = full_interp;
+    }
+    GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
+
+    mg_snprintf(conn, cmdline, sizeof(cmdline), "%s%s\"%s\\%s\"",
+                interp, interp[0] == '\0' ? "" : " ", full_dir, prog);
+
+    DEBUG_TRACE(("Running [%s]", cmdline));
+    if (CreateProcessA(NULL, cmdline, NULL, NULL, TRUE,
+                       CREATE_NEW_PROCESS_GROUP, envblk, NULL, &si, &pi) == 0) {
+        mg_cry(conn, "%s: CreateProcess(%s): %ld",
+               __func__, cmdline, ERRNO);
+        pi.hProcess = (pid_t) -1;
+    }
+
+    (void) CloseHandle(si.hStdOutput);
+    (void) CloseHandle(si.hStdInput);
+    if (pi.hThread != NULL)
+        (void) CloseHandle(pi.hThread);
+
+    return (pid_t) pi.hProcess;
+}
+#endif /* !NO_CGI */
+
+static int set_non_blocking_mode(SOCKET sock)
+{
+    unsigned long on = 1;
+    return ioctlsocket(sock, FIONBIO, &on);
+}
+
+#else
+static int mg_stat(struct mg_connection *conn, const char *path,
+                   struct file *filep)
+{
+    struct stat st;
+
+    if (!is_file_in_memory(conn, path, filep) && !stat(path, &st)) {
+        filep->size = st.st_size;
+        filep->modification_time = st.st_mtime;
+        filep->is_directory = S_ISDIR(st.st_mode);
+    } else {
+        filep->modification_time = (time_t) 0;
+    }
+
+    return filep->membuf != NULL || filep->modification_time != (time_t) 0;
+}
+
+static void set_close_on_exec(int fd, struct mg_connection *conn /* may be null */)
+{
+    if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
+        if (conn)
+            mg_cry(conn, "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
+                   __func__, strerror(ERRNO));
+    }
+}
+
+int mg_start_thread(mg_thread_func_t func, void *param)
+{
+    pthread_t thread_id;
+    pthread_attr_t attr;
+    int result;
+
+    (void) pthread_attr_init(&attr);
+    (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
+
+#if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
+    /* Compile-time option to control stack size,
+       e.g. -DUSE_STACK_SIZE=16384 */
+    (void) pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
+#endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
+
+    result = pthread_create(&thread_id, &attr, func, param);
+    pthread_attr_destroy(&attr);
+
+    return result;
+}
+
+/* Start a thread storing the thread context. */
+
+static int mg_start_thread_with_id(mg_thread_func_t func, void *param,
+                                   pthread_t *threadidptr)
+{
+    pthread_t thread_id;
+    pthread_attr_t attr;
+    int result;
+
+    (void) pthread_attr_init(&attr);
+
+#if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
+    /* Compile-time option to control stack size,
+       e.g. -DUSE_STACK_SIZE=16384 */
+    (void) pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
+#endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
+
+    result = pthread_create(&thread_id, &attr, func, param);
+    pthread_attr_destroy(&attr);
+    if (threadidptr != NULL) {
+        *threadidptr = thread_id;
+    }
+    return result;
+}
+
+/* Wait for a thread to finish. */
+
+static int mg_join_thread(pthread_t threadid)
+{
+    int result;
+
+    result = pthread_join(threadid, NULL);
+    return result;
+}
+
+#ifndef NO_CGI
+static pid_t spawn_process(struct mg_connection *conn, const char *prog,
+                           char *envblk, char *envp[], int fdin,
+                           int fdout, const char *dir)
+{
+    pid_t pid;
+    const char *interp;
+
+    (void) envblk;
+
+    if ((pid = fork()) == -1) {
+        /* Parent */
+        send_http_error(conn, 500, http_500_error, "fork(): %s", strerror(ERRNO));
+    } else if (pid == 0) {
+        /* Child */
+        if (chdir(dir) != 0) {
+            mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
+        } else if (dup2(fdin, 0) == -1) {
+            mg_cry(conn, "%s: dup2(%d, 0): %s", __func__, fdin, strerror(ERRNO));
+        } else if (dup2(fdout, 1) == -1) {
+            mg_cry(conn, "%s: dup2(%d, 1): %s", __func__, fdout, strerror(ERRNO));
+        } else {
+            /* Not redirecting stderr to stdout, to avoid output being littered
+               with the error messages. */
+            (void) close(fdin);
+            (void) close(fdout);
+
+            /* After exec, all signal handlers are restored to their default
+               values, with one exception of SIGCHLD. According to
+               POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
+               leave unchanged after exec if it was set to be ignored. Restore
+               it to default action. */
+            signal(SIGCHLD, SIG_DFL);
+
+            interp = conn->ctx->config[CGI_INTERPRETER];
+            if (interp == NULL) {
+                (void) execle(prog, prog, NULL, envp);
+                mg_cry(conn, "%s: execle(%s): %s", __func__, prog, strerror(ERRNO));
+            } else {
+                (void) execle(interp, interp, prog, NULL, envp);
+                mg_cry(conn, "%s: execle(%s %s): %s", __func__, interp, prog,
+                       strerror(ERRNO));
+            }
+        }
+        exit(EXIT_FAILURE);
+    }
+
+    return pid;
+}
+#endif /* !NO_CGI */
+
+static int set_non_blocking_mode(SOCKET sock)
+{
+    int flags;
+
+    flags = fcntl(sock, F_GETFL, 0);
+    (void) fcntl(sock, F_SETFL, flags | O_NONBLOCK);
+
+    return 0;
+}
+#endif /* _WIN32 */
+
+/* Write data to the IO channel - opened file descriptor, socket or SSL
+   descriptor. Return number of bytes written. */
+static int64_t push(FILE *fp, SOCKET sock, SSL *ssl, const char *buf,
+                    int64_t len)
+{
+    int64_t sent;
+    int n, k;
+
+    (void) ssl;  /* Get rid of warning */
+    sent = 0;
+    while (sent < len) {
+
+        /* How many bytes we send in this iteration */
+        k = len - sent > INT_MAX ? INT_MAX : (int) (len - sent);
+
+#ifndef NO_SSL
+        if (ssl != NULL) {
+            n = SSL_write(ssl, buf + sent, k);
+        } else
+#endif
+            if (fp != NULL) {
+                n = (int) fwrite(buf + sent, 1, (size_t) k, fp);
+                if (ferror(fp))
+                    n = -1;
+            } else {
+                n = send(sock, buf + sent, (size_t) k, MSG_NOSIGNAL);
+            }
+
+        if (n <= 0)
+            break;
+
+        sent += n;
+    }
+
+    return sent;
+}
+
+/* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
+   Return negative value on error, or number of bytes read on success. */
+static int pull(FILE *fp, struct mg_connection *conn, char *buf, int len)
+{
+    int nread;
+
+    if (fp != NULL) {
+        /* Use read() instead of fread(), because if we're reading from the
+           CGI pipe, fread() may block until IO buffer is filled up. We cannot
+           afford to block and must pass all read bytes immediately to the
+           client. */
+        nread = read(fileno(fp), buf, (size_t) len);
+#ifndef NO_SSL
+    } else if (conn->ssl != NULL) {
+        nread = SSL_read(conn->ssl, buf, len);
+#endif
+    } else {
+        nread = recv(conn->client.sock, buf, (size_t) len, 0);
+    }
+
+    return conn->ctx->stop_flag ? -1 : nread;
+}
+
+static int pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
+{
+    int n, nread = 0;
+
+    while (len > 0 && conn->ctx->stop_flag == 0) {
+        n = pull(fp, conn, buf + nread, len);
+        if (n < 0) {
+            nread = n;  /* Propagate the error */
+            break;
+        } else if (n == 0) {
+            break;  /* No more data to read */
+        } else {
+            conn->consumed_content += n;
+            nread += n;
+            len -= n;
+        }
+    }
+
+    return nread;
+}
+
+int mg_read(struct mg_connection *conn, void *buf, size_t len)
+{
+    int n, buffered_len, nread;
+    const char *body;
+
+    /* If Content-Length is not set, read until socket is closed */
+    if (conn->consumed_content == 0 && conn->content_len == 0) {
+        conn->content_len = INT64_MAX;
+        conn->must_close = 1;
+    }
+
+    nread = 0;
+    if (conn->consumed_content < conn->content_len) {
+        /* Adjust number of bytes to read. */
+        int64_t to_read = conn->content_len - conn->consumed_content;
+        if (to_read < (int64_t) len) {
+            len = (size_t) to_read;
+        }
+
+        /* Return buffered data */
+        body = conn->buf + conn->request_len + conn->consumed_content;
+        buffered_len = (int)(&conn->buf[conn->data_len] - body);
+        if (buffered_len > 0) {
+            if (len < (size_t) buffered_len) {
+                buffered_len = (int) len;
+            }
+            memcpy(buf, body, (size_t) buffered_len);
+            len -= buffered_len;
+            conn->consumed_content += buffered_len;
+            nread += buffered_len;
+            buf = (char *) buf + buffered_len;
+        }
+
+        /* We have returned all buffered data. Read new data from the remote
+           socket. */
+        n = pull_all(NULL, conn, (char *) buf, (int) len);
+        nread = n >= 0 ? nread + n : n;
+    }
+    return nread;
+}
+
+int mg_write(struct mg_connection *conn, const void *buf, size_t len)
+{
+    time_t now;
+    int64_t n, total, allowed;
+
+    if (conn->throttle > 0) {
+        if ((now = time(NULL)) != conn->last_throttle_time) {
+            conn->last_throttle_time = now;
+            conn->last_throttle_bytes = 0;
+        }
+        allowed = conn->throttle - conn->last_throttle_bytes;
+        if (allowed > (int64_t) len) {
+            allowed = len;
+        }
+        if ((total = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
+                          (int64_t) allowed)) == allowed) {
+            buf = (char *) buf + total;
+            conn->last_throttle_bytes += total;
+            while (total < (int64_t) len && conn->ctx->stop_flag == 0) {
+                allowed = conn->throttle > (int64_t) len - total ?
+                          (int64_t) len - total : conn->throttle;
+                if ((n = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
+                              (int64_t) allowed)) != allowed) {
+                    break;
+                }
+                sleep(1);
+                conn->last_throttle_bytes = allowed;
+                conn->last_throttle_time = time(NULL);
+                buf = (char *) buf + n;
+                total += n;
+            }
+        }
+    } else {
+        total = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
+                     (int64_t) len);
+    }
+    return (int) total;
+}
+
+/* Alternative alloc_vprintf() for non-compliant C runtimes */
+static int alloc_vprintf2(char **buf, const char *fmt, va_list ap)
+{
+    va_list ap_copy;
+    int size = MG_BUF_LEN;
+    int len = -1;
+
+    *buf = NULL;
+    while (len == -1) {
+        if (*buf) free(*buf);
+        *buf = (char *)malloc(size *= 4);
+        if (!*buf) break;
+        va_copy(ap_copy, ap);
+        len = vsnprintf(*buf, size, fmt, ap_copy);
+        va_end(ap_copy);
+    }
+
+    return len;
+}
+
+/* Print message to buffer. If buffer is large enough to hold the message,
+   return buffer. If buffer is to small, allocate large enough buffer on heap,
+   and return allocated buffer. */
+static int alloc_vprintf(char **buf, size_t size, const char *fmt, va_list ap)
+{
+    va_list ap_copy;
+    int len;
+
+    /* Windows is not standard-compliant, and vsnprintf() returns -1 if
+       buffer is too small. Also, older versions of msvcrt.dll do not have
+       _vscprintf().  However, if size is 0, vsnprintf() behaves correctly.
+       Therefore, we make two passes: on first pass, get required message
+       length.
+       On second pass, actually print the message. */
+    va_copy(ap_copy, ap);
+    len = vsnprintf(NULL, 0, fmt, ap_copy);
+    va_end(ap_copy);
+
+    if (len < 0) {
+        /* C runtime is not standard compliant, vsnprintf() returned -1.
+           Switch to alternative code path that uses incremental allocations.
+        */
+        va_copy(ap_copy, ap);
+        len = alloc_vprintf2(buf, fmt, ap);
+        va_end(ap_copy);
+    } else if (len > (int) size &&
+               (size = len + 1) > 0 &&
+               (*buf = (char *) malloc(size)) == NULL) {
+        len = -1;  /* Allocation failed, mark failure */
+    } else {
+        va_copy(ap_copy, ap);
+        IGNORE_UNUSED_RESULT(vsnprintf(*buf, size, fmt, ap_copy));
+        va_end(ap_copy);
+    }
+
+    return len;
+}
+
+int mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap);
+
+int mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
+{
+    char mem[MG_BUF_LEN], *buf = mem;
+    int len;
+
+    if ((len = alloc_vprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
+        len = mg_write(conn, buf, (size_t) len);
+    }
+    if (buf != mem && buf != NULL) {
+        free(buf);
+    }
+
+    return len;
+}
+
+int mg_printf(struct mg_connection *conn, const char *fmt, ...)
+{
+    va_list ap;
+    int result;
+
+    va_start(ap, fmt);
+    result = mg_vprintf(conn, fmt, ap);
+    va_end(ap);
+
+    return result;
+}
+
+int mg_url_decode(const char *src, int src_len, char *dst,
+                  int dst_len, int is_form_url_encoded)
+{
+    int i, j, a, b;
+#define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
+
+    for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
+        if (src[i] == '%' && i < src_len - 2 &&
+            isxdigit(* (const unsigned char *) (src + i + 1)) &&
+            isxdigit(* (const unsigned char *) (src + i + 2))) {
+            a = tolower(* (const unsigned char *) (src + i + 1));
+            b = tolower(* (const unsigned char *) (src + i + 2));
+            dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
+            i += 2;
+        } else if (is_form_url_encoded && src[i] == '+') {
+            dst[j] = ' ';
+        } else {
+            dst[j] = src[i];
+        }
+    }
+
+    dst[j] = '\0'; /* Null-terminate the destination */
+
+    return i >= src_len ? j : -1;
+}
+
+int mg_get_var(const char *data, size_t data_len, const char *name,
+               char *dst, size_t dst_len)
+{
+    return mg_get_var2(data,data_len,name,dst,dst_len,0);
+}
+
+int mg_get_var2(const char *data, size_t data_len, const char *name,
+                char *dst, size_t dst_len, size_t occurrence)
+{
+    const char *p, *e, *s;
+    size_t name_len;
+    int len;
+
+    if (dst == NULL || dst_len == 0) {
+        len = -2;
+    } else if (data == NULL || name == NULL || data_len == 0) {
+        len = -1;
+        dst[0] = '\0';
+    } else {
+        name_len = strlen(name);
+        e = data + data_len;
+        len = -1;
+        dst[0] = '\0';
+
+        /* data is "var1=val1&var2=val2...". Find variable first */
+        for (p = data; p + name_len < e; p++) {
+            if ((p == data || p[-1] == '&') && p[name_len] == '=' &&
+                !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
+
+                /* Point p to variable value */
+                p += name_len + 1;
+
+                /* Point s to the end of the value */
+                s = (const char *) memchr(p, '&', (size_t)(e - p));
+                if (s == NULL) {
+                    s = e;
+                }
+                assert(s >= p);
+
+                /* Decode variable into destination buffer */
+                len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
+
+                /* Redirect error code from -1 to -2 (destination buffer too
+                   small). */
+                if (len == -1) {
+                    len = -2;
+                }
+                break;
+            }
+        }
+    }
+
+    return len;
+}
+
+int mg_get_cookie(const char *cookie_header, const char *var_name,
+                  char *dst, size_t dst_size)
+{
+    const char *s, *p, *end;
+    int name_len, len = -1;
+
+    if (dst == NULL || dst_size == 0) {
+        len = -2;
+    } else if (var_name == NULL || (s = cookie_header) == NULL) {
+        len = -1;
+        dst[0] = '\0';
+    } else {
+        name_len = (int) strlen(var_name);
+        end = s + strlen(s);
+        dst[0] = '\0';
+
+        for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
+            if (s[name_len] == '=') {
+                s += name_len + 1;
+                if ((p = strchr(s, ' ')) == NULL)
+                    p = end;
+                if (p[-1] == ';')
+                    p--;
+                if (*s == '"' && p[-1] == '"' && p > s + 1) {
+                    s++;
+                    p--;
+                }
+                if ((size_t) (p - s) < dst_size) {
+                    len = (int)(p - s);
+                    mg_strlcpy(dst, s, (size_t) len + 1);
+                } else {
+                    len = -3;
+                }
+                break;
+            }
+        }
+    }
+    return len;
+}
+
+#if defined(USE_WEBSOCKET) || defined(USE_LUA)
+static void base64_encode(const unsigned char *src, int src_len, char *dst)
+{
+    static const char *b64 =
+        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+    int i, j, a, b, c;
+
+    for (i = j = 0; i < src_len; i += 3) {
+        a = src[i];
+        b = i + 1 >= src_len ? 0 : src[i + 1];
+        c = i + 2 >= src_len ? 0 : src[i + 2];
+
+        dst[j++] = b64[a >> 2];
+        dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
+        if (i + 1 < src_len) {
+            dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
+        }
+        if (i + 2 < src_len) {
+            dst[j++] = b64[c & 63];
+        }
+    }
+    while (j % 4 != 0) {
+        dst[j++] = '=';
+    }
+    dst[j++] = '\0';
+}
+
+static unsigned char b64reverse(char letter) {
+    if (letter>='A' && letter<='Z') return letter-'A';
+    if (letter>='a' && letter<='z') return letter-'a'+26;
+    if (letter>='0' && letter<='9') return letter-'0'+52;
+    if (letter=='+') return 62;
+    if (letter=='/') return 63;
+    if (letter=='=') return 255; /* normal end */
+    return 254; /* error */
+}
+
+static int base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
+{
+    int i;
+    unsigned char a, b, c, d;
+
+    *dst_len = 0;
+
+    for (i = 0; i < src_len; i += 4) {
+        a = b64reverse(src[i]);
+        if (a>=254) return i;
+
+        b = b64reverse(i + 1 >= src_len ? 0 : src[i + 1]);
+        if (b>=254) return i+1;
+
+        c = b64reverse(i + 2 >= src_len ? 0 : src[i + 2]);
+        if (c==254) return i+2;
+
+        d = b64reverse(i + 3 >= src_len ? 0 : src[i + 3]);
+        if (c==254) return i+3;
+
+        dst[(*dst_len)++] = (a << 2) + (b >> 4);
+        if (c!=255) {
+            dst[(*dst_len)++] = (b << 4) + (c >> 2);
+            if (d!=255) {
+                dst[(*dst_len)++] = (c << 6) + d;
+            }
+        }
+    }
+    return -1;
+}
+#endif
+
+static void convert_uri_to_file_name(struct mg_connection *conn, char *buf,
+                                     size_t buf_len, struct file *filep,
+                                     int * is_script_ressource)
+{
+    struct vec a, b;
+    const char *rewrite, *uri = conn->request_info.uri,
+                          *root = conn->ctx->config[DOCUMENT_ROOT];
+    char *p;
+    int match_len;
+    char gz_path[PATH_MAX];
+    char const* accept_encoding;
+
+    *is_script_ressource = 0;
+
+#if defined(USE_WEBSOCKET)
+    if (is_websocket_request(conn) && conn->ctx->config[WEBSOCKET_ROOT]) {
+        root = conn->ctx->config[WEBSOCKET_ROOT];
+    }
+#endif
+
+    /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
+       of the path one byte on the right.
+       If document_root is NULL, leave the file empty. */
+    mg_snprintf(conn, buf, buf_len - 1, "%s%s",
+                root == NULL ? "" : root,
+                root == NULL ? "" : uri);
+
+    rewrite = conn->ctx->config[REWRITE];
+    while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
+        if ((match_len = match_prefix(a.ptr, (int) a.len, uri)) > 0) {
+            mg_snprintf(conn, buf, buf_len - 1, "%.*s%s", (int) b.len, b.ptr,
+                        uri + match_len);
+            break;
+        }
+    }
+
+    if (mg_stat(conn, buf, filep)) return;
+
+    /* if we can't find the actual file, look for the file
+       with the same name but a .gz extension. If we find it,
+       use that and set the gzipped flag in the file struct
+       to indicate that the response need to have the content-
+       encoding: gzip header
+       we can only do this if the browser declares support */
+    if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
+        if (strstr(accept_encoding,"gzip") != NULL) {
+            snprintf(gz_path, sizeof(gz_path), "%s.gz", buf);
+            if (mg_stat(conn, gz_path, filep)) {
+                filep->gzipped = 1;
+                return;
+            }
+        }
+    }
+
+    /* Support PATH_INFO for CGI scripts. */
+    for (p = buf + strlen(buf); p > buf + 1; p--) {
+        if (*p == '/') {
+            *p = '\0';
+            if ((match_prefix(conn->ctx->config[CGI_EXTENSIONS],
+                              (int)strlen(conn->ctx->config[CGI_EXTENSIONS]), buf) > 0
+#ifdef USE_LUA
+                 ||
+                 match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
+                              (int)strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]), buf) > 0
+#endif
+                ) && mg_stat(conn, buf, filep)) {
+                /* Shift PATH_INFO block one character right, e.g.
+                    "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
+                   conn->path_info is pointing to the local variable "path"
+                   declared in handle_request(), so PATH_INFO is not valid
+                   after handle_request returns. */
+                conn->path_info = p + 1;
+                memmove(p + 2, p + 1, strlen(p + 1) + 1);  /* +1 is for
+                                                              trailing \0 */
+                p[1] = '/';
+                *is_script_ressource = 1;
+                break;
+            } else {
+                *p = '/';
+            }
+        }
+    }
+}
+
+/* Check whether full request is buffered. Return:
+     -1  if request is malformed
+      0  if request is not yet fully buffered
+     >0  actual request length, including last \r\n\r\n */
+static int get_request_len(const char *buf, int buflen)
+{
+    const char *s, *e;
+    int len = 0;
+
+    for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
+        /* Control characters are not allowed but >=128 is. */
+        if (!isprint(* (const unsigned char *) s) && *s != '\r' &&
+            *s != '\n' && * (const unsigned char *) s < 128) {
+            len = -1;
+            break;  /* [i_a] abort scan as soon as one malformed character is
+                       found; */
+            /* don't let subsequent \r\n\r\n win us over anyhow */
+        } else if (s[0] == '\n' && s[1] == '\n') {
+            len = (int) (s - buf) + 2;
+        } else if (s[0] == '\n' && &s[1] < e &&
+                   s[1] == '\r' && s[2] == '\n') {
+            len = (int) (s - buf) + 3;
+        }
+
+    return len;
+}
+
+/* Convert month to the month number. Return -1 on error, or month number */
+static int get_month_index(const char *s)
+{
+    size_t i;
+
+    for (i = 0; i < ARRAY_SIZE(month_names); i++)
+        if (!strcmp(s, month_names[i]))
+            return (int) i;
+
+    return -1;
+}
+
+static int num_leap_years(int year)
+{
+    return year / 4 - year / 100 + year / 400;
+}
+
+/* Parse UTC date-time string, and return the corresponding time_t value. */
+static time_t parse_date_string(const char *datetime)
+{
+    static const unsigned short days_before_month[] = {
+        0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
+    };
+    char month_str[32];
+    int second, minute, hour, day, month, year, leap_days, days;
+    time_t result = (time_t) 0;
+
+    if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d",
+                 &day, month_str, &year, &hour, &minute, &second) == 6) ||
+         (sscanf(datetime, "%d %3s %d %d:%d:%d",
+                 &day, month_str, &year, &hour, &minute, &second) == 6) ||
+         (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d",
+                 &day, month_str, &year, &hour, &minute, &second) == 6) ||
+         (sscanf(datetime, "%d-%3s-%d %d:%d:%d",
+                 &day, month_str, &year, &hour, &minute, &second) == 6)) &&
+        year > 1970 &&
+        (month = get_month_index(month_str)) != -1) {
+        leap_days = num_leap_years(year) - num_leap_years(1970);
+        year -= 1970;
+        days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
+        result = (time_t) days * 24 * 3600 + (time_t) hour * 3600 +
+                 minute * 60 + second;
+    }
+
+    return result;
+}
+
+/* Protect against directory disclosure attack by removing '..',
+   excessive '/' and '\' characters */
+static void remove_double_dots_and_double_slashes(char *s)
+{
+    char *p = s;
+
+    while (*s != '\0') {
+        *p++ = *s++;
+        if (s[-1] == '/' || s[-1] == '\\') {
+            /* Skip all following slashes, backslashes and double-dots */
+            while (s[0] != '\0') {
+                if (s[0] == '/' || s[0] == '\\') {
+                    s++;
+                } else if (s[0] == '.' && s[1] == '.') {
+                    s += 2;
+                } else {
+                    break;
+                }
+            }
+        }
+    }
+    *p = '\0';
+}
+
+static const struct {
+    const char *extension;
+    size_t ext_len;
+    const char *mime_type;
+} builtin_mime_types[] = {
+    /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
+       application types */
+    {".doc",     4, "application/msword"},
+    {".eps",     4, "application/postscript"},
+    {".exe",     4, "application/octet-stream"},
+    {".js",      3, "application/javascript"},
+    {".json",    5, "application/json"},
+    {".pdf",     4, "application/pdf"},
+    {".ps",      3, "application/postscript"},
+    {".rtf",     4, "application/rtf"},
+    {".xhtml",   6, "application/xhtml+xml"},
+    {".xsl",     4, "application/xml"},
+    {".xslt",    5, "application/xml"},
+
+    /* audio */
+    {".mp3",     4, "audio/mpeg"},
+    {".oga",     4, "audio/ogg"},
+    {".ogg",     4, "audio/ogg"},
+
+    /* image */
+    {".gif",     4, "image/gif"},
+    {".ief",     4, "image/ief"},
+    {".jpeg",    5, "image/jpeg"},
+    {".jpg",     4, "image/jpeg"},
+    {".jpm",     4, "image/jpm"},
+    {".jpx",     4, "image/jpx"},
+    {".png",     4, "image/png"},
+    {".svg",     4, "image/svg+xml"},
+    {".tif",     4, "image/tiff"},
+    {".tiff",    5, "image/tiff"},
+
+    /* model */
+    {".wrl",     4, "model/vrml"},
+
+    /* text */
+    {".css",     4, "text/css"},
+    {".csv",     4, "text/csv"},
+    {".htm",     4, "text/html"},
+    {".html",    5, "text/html"},
+    {".sgm",     4, "text/sgml"},
+    {".shtm",    5, "text/html"},
+    {".shtml",   6, "text/html"},
+    {".txt",     4, "text/plain"},
+    {".xml",     4, "text/xml"},
+
+    /* video */
+    {".mov",     4, "video/quicktime"},
+    {".mp4",     4, "video/mp4"},
+    {".mpeg",    5, "video/mpeg"},
+    {".mpg",     4, "video/mpeg"},
+    {".ogv",     4, "video/ogg"},
+    {".qt",      3, "video/quicktime"},
+
+    /* not registered types
+       (http://reference.sitepoint.com/html/mime-types-full,
+        http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
+    {".arj",     4, "application/x-arj-compressed"},
+    {".gz",      3, "application/x-gunzip"},
+    {".rar",     4, "application/x-arj-compressed"},
+    {".swf",     4, "application/x-shockwave-flash"},
+    {".tar",     4, "application/x-tar"},
+    {".tgz",     4, "application/x-tar-gz"},
+    {".torrent", 8, "application/x-bittorrent"},
+    {".ppt",     4, "application/x-mspowerpoint"},
+    {".xls",     4, "application/x-msexcel"},
+    {".zip",     4, "application/x-zip-compressed"},
+    {".aac",     4, "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
+    {".aif",     4, "audio/x-aif"},
+    {".m3u",     4, "audio/x-mpegurl"},
+    {".mid",     4, "audio/x-midi"},
+    {".ra",      3, "audio/x-pn-realaudio"},
+    {".ram",     4, "audio/x-pn-realaudio"},
+    {".wav",     4, "audio/x-wav"},
+    {".bmp",     4, "image/bmp"},
+    {".ico",     4, "image/x-icon"},
+    {".pct",     4, "image/x-pct"},
+    {".pict",    5, "image/pict"},
+    {".rgb",     4, "image/x-rgb"},
+    {".webm",    5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
+    {".asf",     4, "video/x-ms-asf"},
+    {".avi",     4, "video/x-msvideo"},
+    {".m4v",     4, "video/x-m4v"},
+    {NULL, 0, NULL}
+};
+
+const char *mg_get_builtin_mime_type(const char *path)
+{
+    const char *ext;
+    size_t i, path_len;
+
+    path_len = strlen(path);
+
+    for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
+        ext = path + (path_len - builtin_mime_types[i].ext_len);
+        if (path_len > builtin_mime_types[i].ext_len &&
+            mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
+            return builtin_mime_types[i].mime_type;
+        }
+    }
+
+    return "text/plain";
+}
+
+/* Look at the "path" extension and figure what mime type it has.
+   Store mime type in the vector. */
+static void get_mime_type(struct mg_context *ctx, const char *path,
+                          struct vec *vec)
+{
+    struct vec ext_vec, mime_vec;
+    const char *list, *ext;
+    size_t path_len;
+
+    path_len = strlen(path);
+
+    /* Scan user-defined mime types first, in case user wants to
+       override default mime types. */
+    list = ctx->config[EXTRA_MIME_TYPES];
+    while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
+        /* ext now points to the path suffix */
+        ext = path + path_len - ext_vec.len;
+        if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
+            *vec = mime_vec;
+            return;
+        }
+    }
+
+    vec->ptr = mg_get_builtin_mime_type(path);
+    vec->len = strlen(vec->ptr);
+}
+
+/* Stringify binary data. Output buffer must be twice as big as input,
+   because each byte takes 2 bytes in string representation */
+static void bin2str(char *to, const unsigned char *p, size_t len)
+{
+    static const char *hex = "0123456789abcdef";
+
+    for (; len--; p++) {
+        *to++ = hex[p[0] >> 4];
+        *to++ = hex[p[0] & 0x0f];
+    }
+    *to = '\0';
+}
+
+/* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
+char *mg_md5(char buf[33], ...)
+{
+    md5_byte_t hash[16];
+    const char *p;
+    va_list ap;
+    md5_state_t ctx;
+
+    md5_init(&ctx);
+
+    va_start(ap, buf);
+    while ((p = va_arg(ap, const char *)) != NULL) {
+        md5_append(&ctx, (const md5_byte_t *) p, (int) strlen(p));
+    }
+    va_end(ap);
+
+    md5_finish(&ctx, hash);
+    bin2str(buf, hash, sizeof(hash));
+    return buf;
+}
+
+/* Check the user's password, return 1 if OK */
+static int check_password(const char *method, const char *ha1, const char *uri,
+                          const char *nonce, const char *nc, const char *cnonce,
+                          const char *qop, const char *response)
+{
+    char ha2[32 + 1], expected_response[32 + 1];
+
+    /* Some of the parameters may be NULL */
+    if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL ||
+        qop == NULL || response == NULL) {
+        return 0;
+    }
+
+    /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
+    /* TODO(lsm): check for authentication timeout */
+    if (/* strcmp(dig->uri, c->ouri) != 0 || */
+        strlen(response) != 32
+        /* || now - strtoul(dig->nonce, NULL, 10) > 3600 */
+    ) {
+        return 0;
+    }
+
+    mg_md5(ha2, method, ":", uri, NULL);
+    mg_md5(expected_response, ha1, ":", nonce, ":", nc,
+           ":", cnonce, ":", qop, ":", ha2, NULL);
+
+    return mg_strcasecmp(response, expected_response) == 0;
+}
+
+/* Use the global passwords file, if specified by auth_gpass option,
+   or search for .htpasswd in the requested directory. */
+static void open_auth_file(struct mg_connection *conn, const char *path,
+                           struct file *filep)
+{
+    char name[PATH_MAX];
+    const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
+    struct file file = STRUCT_FILE_INITIALIZER;
+
+    if (gpass != NULL) {
+        /* Use global passwords file */
+        if (!mg_fopen(conn, gpass, "r", filep)) {
+#ifdef DEBUG
+            mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
+#endif
+        }
+        /* Important: using local struct file to test path for is_directory
+           flag.
+           If filep is used, mg_stat() makes it appear as if auth file was
+           opened. */
+    } else if (mg_stat(conn, path, &file) && file.is_directory) {
+        mg_snprintf(conn, name, sizeof(name), "%s%c%s",
+                    path, '/', PASSWORDS_FILE_NAME);
+        if (!mg_fopen(conn, name, "r", filep)) {
+#ifdef DEBUG
+            mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
+#endif
+        }
+    } else {
+        /* Try to find .htpasswd in requested directory. */
+        for (p = path, e = p + strlen(p) - 1; e > p; e--)
+            if (e[0] == '/')
+                break;
+        mg_snprintf(conn, name, sizeof(name), "%.*s%c%s",
+                    (int) (e - p), p, '/', PASSWORDS_FILE_NAME);
+        if (!mg_fopen(conn, name, "r", filep)) {
+#ifdef DEBUG
+            mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
+#endif
+        }
+    }
+}
+
+/* Parsed Authorization header */
+struct ah {
+    char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
+};
+
+/* Return 1 on success. Always initializes the ah structure. */
+static int parse_auth_header(struct mg_connection *conn, char *buf,
+                             size_t buf_size, struct ah *ah)
+{
+    char *name, *value, *s;
+    const char *auth_header;
+    unsigned long nonce;
+
+    (void) memset(ah, 0, sizeof(*ah));
+    if ((auth_header = mg_get_header(conn, "Authorization")) == NULL ||
+        mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
+        return 0;
+    }
+
+    /* Make modifiable copy of the auth header */
+    (void) mg_strlcpy(buf, auth_header + 7, buf_size);
+    s = buf;
+
+    /* Parse authorization header */
+    for (;;) {
+        /* Gobble initial spaces */
+        while (isspace(* (unsigned char *) s)) {
+            s++;
+        }
+        name = skip_quoted(&s, "=", " ", 0);
+        /* Value is either quote-delimited, or ends at first comma or space. */
+        if (s[0] == '\"') {
+            s++;
+            value = skip_quoted(&s, "\"", " ", '\\');
+            if (s[0] == ',') {
+                s++;
+            }
+        } else {
+            value = skip_quoted(&s, ", ", " ", 0);  /* IE uses commas, FF uses
+                                                       spaces */
+        }
+        if (*name == '\0') {
+            break;
+        }
+
+        if (!strcmp(name, "username")) {
+            ah->user = value;
+        } else if (!strcmp(name, "cnonce")) {
+            ah->cnonce = value;
+        } else if (!strcmp(name, "response")) {
+            ah->response = value;
+        } else if (!strcmp(name, "uri")) {
+            ah->uri = value;
+        } else if (!strcmp(name, "qop")) {
+            ah->qop = value;
+        } else if (!strcmp(name, "nc")) {
+            ah->nc = value;
+        } else if (!strcmp(name, "nonce")) {
+            ah->nonce = value;
+        }
+    }
+
+#ifndef NO_NONCE_CHECK
+    /* Convert the nonce from the client to a number and check it. */
+    /* Server side nonce check is valuable in all situations but one: if the server restarts frequently,
+       but the client should not see that, so the server should accept nonces from previous starts. */
+    nonce = strtoul(ah->nonce, &s, 10);
+    if ((s == NULL) || (*s != 0)) {
+        return 0;
+    }
+    nonce ^= (unsigned long)(conn->ctx);
+    if (nonce<conn->ctx->start_time) {
+        /* nonce is from a previous start of the server and no longer valid (replay attack?) */
+        return 0;
+    }
+    if (nonce>=conn->ctx->start_time+conn->ctx->nonce_count) {
+        return 0;
+    }
+#endif
+
+    /* CGI needs it as REMOTE_USER */
+    if (ah->user != NULL) {
+        conn->request_info.remote_user = mg_strdup(ah->user);
+    } else {
+        return 0;
+    }
+
+    return 1;
+}
+
+static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p)
+{
+    char *eof;
+    size_t len;
+    char *memend;
+
+    if (filep->membuf != NULL && *p != NULL) {
+        memend = (char *) &filep->membuf[filep->size];
+        eof = (char *) memchr(*p, '\n', memend - *p); /* Search for \n from p
+                                                         till the end of
+                                                         stream */
+        if (eof != NULL) {
+            eof += 1; /* Include \n */
+        } else {
+            eof = memend; /* Copy remaining data */
+        }
+        len = (size_t) (eof - *p) > size - 1 ? size - 1 : (size_t) (eof - *p);
+        memcpy(buf, *p, len);
+        buf[len] = '\0';
+        *p += len;
+        return len ? eof : NULL;
+    } else if (filep->fp != NULL) {
+        return fgets(buf, (int)size, filep->fp);
+    } else {
+        return NULL;
+    }
+}
+
+/* Authorize against the opened passwords file. Return 1 if authorized. */
+static int authorize(struct mg_connection *conn, struct file *filep)
+{
+    struct ah ah;
+    char line[256], f_user[256] = "", ha1[256] = "", f_domain[256] = "", buf[MG_BUF_LEN], *p;
+
+    if (!parse_auth_header(conn, buf, sizeof(buf), &ah)) {
+        return 0;
+    }
+
+    /* Loop over passwords file */
+    p = (char *) filep->membuf;
+    while (mg_fgets(line, sizeof(line), filep, &p) != NULL) {
+        if (sscanf(line, "%[^:]:%[^:]:%s", f_user, f_domain, ha1) != 3) {
+            continue;
+        }
+
+        if (!strcmp(ah.user, f_user) &&
+            !strcmp(conn->ctx->config[AUTHENTICATION_DOMAIN], f_domain))
+            return check_password(conn->request_info.request_method, ha1, ah.uri,
+                                  ah.nonce, ah.nc, ah.cnonce, ah.qop, ah.response);
+    }
+
+    return 0;
+}
+
+/* Return 1 if request is authorised, 0 otherwise. */
+static int check_authorization(struct mg_connection *conn, const char *path)
+{
+    char fname[PATH_MAX];
+    struct vec uri_vec, filename_vec;
+    const char *list;
+    struct file file = STRUCT_FILE_INITIALIZER;
+    int authorized = 1;
+
+    list = conn->ctx->config[PROTECT_URI];
+    while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
+        if (!memcmp(conn->request_info.uri, uri_vec.ptr, uri_vec.len)) {
+            mg_snprintf(conn, fname, sizeof(fname), "%.*s",
+                        (int) filename_vec.len, filename_vec.ptr);
+            if (!mg_fopen(conn, fname, "r", &file)) {
+                mg_cry(conn, "%s: cannot open %s: %s", __func__, fname, strerror(errno));
+            }
+            break;
+        }
+    }
+
+    if (!is_file_opened(&file)) {
+        open_auth_file(conn, path, &file);
+    }
+
+    if (is_file_opened(&file)) {
+        authorized = authorize(conn, &file);
+        mg_fclose(&file);
+    }
+
+    return authorized;
+}
+
+static void send_authorization_request(struct mg_connection *conn)
+{
+    char date[64];

+    time_t curtime = time(NULL);

+    unsigned long nonce = (unsigned long)(conn->ctx->start_time);

+

+    (void)pthread_mutex_lock(&conn->ctx->mutex);
+    nonce += conn->ctx->nonce_count;
+    ++conn->ctx->nonce_count;
+    (void)pthread_mutex_unlock(&conn->ctx->mutex);

+

+    nonce ^= (unsigned long)(conn->ctx);

+    conn->status_code = 401;
+    conn->must_close = 1;
+
+    gmt_time_string(date, sizeof(date), &curtime);
+
+    mg_printf(conn,
+              "HTTP/1.1 401 Unauthorized\r\n"
+              "Date: %s\r\n"
+              "Connection: %s\r\n"
+              "Content-Length: 0\r\n"
+              "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", nonce=\"%lu\"\r\n\r\n",
+              date, suggest_connection_header(conn),
+              conn->ctx->config[AUTHENTICATION_DOMAIN],
+              nonce);
+}
+
+static int is_authorized_for_put(struct mg_connection *conn)
+{
+    struct file file = STRUCT_FILE_INITIALIZER;
+    const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
+    int ret = 0;
+
+    if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
+        ret = authorize(conn, &file);
+        mg_fclose(&file);
+    }
+
+    return ret;
+}
+
+int mg_modify_passwords_file(const char *fname, const char *domain,
+                             const char *user, const char *pass)
+{
+    int found;
+    char line[512], u[512] = "", d[512] ="", ha1[33], tmp[PATH_MAX+1];
+    FILE *fp, *fp2;
+
+    found = 0;
+    fp = fp2 = NULL;
+
+    /* Regard empty password as no password - remove user record. */
+    if (pass != NULL && pass[0] == '\0') {
+        pass = NULL;
+    }
+
+    (void) snprintf(tmp, sizeof(tmp) - 1, "%s.tmp", fname);
+    tmp[sizeof(tmp) - 1] = 0;
+
+    /* Create the file if does not exist */
+    if ((fp = fopen(fname, "a+")) != NULL) {
+        (void) fclose(fp);
+    }
+
+    /* Open the given file and temporary file */
+    if ((fp = fopen(fname, "r")) == NULL) {
+        return 0;
+    } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
+        fclose(fp);
+        return 0;
+    }
+
+    /* Copy the stuff to temporary file */
+    while (fgets(line, sizeof(line), fp) != NULL) {
+        if (sscanf(line, "%[^:]:%[^:]:%*s", u, d) != 2) {
+            continue;
+        }
+
+        if (!strcmp(u, user) && !strcmp(d, domain)) {
+            found++;
+            if (pass != NULL) {
+                mg_md5(ha1, user, ":", domain, ":", pass, NULL);
+                fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
+            }
+        } else {
+            fprintf(fp2, "%s", line);
+        }
+    }
+
+    /* If new user, just add it */
+    if (!found && pass != NULL) {
+        mg_md5(ha1, user, ":", domain, ":", pass, NULL);
+        fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
+    }
+
+    /* Close files */
+    fclose(fp);
+    fclose(fp2);
+
+    /* Put the temp file in place of real file */
+    IGNORE_UNUSED_RESULT(remove(fname));
+    IGNORE_UNUSED_RESULT(rename(tmp, fname));
+
+    return 1;
+}
+
+static SOCKET conn2(struct mg_context *ctx  /* may be null */, const char *host, int port,
+                    int use_ssl, char *ebuf, size_t ebuf_len)
+{
+    struct sockaddr_in sain;
+    struct hostent *he;
+    SOCKET sock = INVALID_SOCKET;
+
+    if (host == NULL) {
+        snprintf(ebuf, ebuf_len, "%s", "NULL host");
+    } else if (use_ssl && SSLv23_client_method == NULL) {
+        snprintf(ebuf, ebuf_len, "%s", "SSL is not initialized");
+        /* TODO(lsm): use something threadsafe instead of gethostbyname() */
+    } else if ((he = gethostbyname(host)) == NULL) {
+        snprintf(ebuf, ebuf_len, "gethostbyname(%s): %s", host, strerror(ERRNO));
+    } else if ((sock = socket(PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
+        snprintf(ebuf, ebuf_len, "socket(): %s", strerror(ERRNO));
+    } else {
+        set_close_on_exec(sock, fc(ctx));
+        memset(&sain, '\0', sizeof(sain));
+        sain.sin_family = AF_INET;
+        sain.sin_port = htons((uint16_t) port);
+        sain.sin_addr = * (struct in_addr *) he->h_addr_list[0];
+        if (connect(sock, (struct sockaddr *) &sain, sizeof(sain)) != 0) {
+            snprintf(ebuf, ebuf_len, "connect(%s:%d): %s",
+                     host, port, strerror(ERRNO));
+            closesocket(sock);
+            sock = INVALID_SOCKET;
+        }
+    }
+    return sock;
+}
+
+int mg_url_encode(const char *src, char *dst, size_t dst_len)
+{
+    static const char *dont_escape = "._-$,;~()";
+    static const char *hex = "0123456789abcdef";
+    char *pos = dst;
+    const char *end = dst + dst_len - 1;
+
+    for (; *src != '\0' && pos < end; src++, pos++) {
+        if (isalnum(*(const unsigned char *) src) ||
+            strchr(dont_escape, * (const unsigned char *) src) != NULL) {
+            *pos = *src;
+        } else if (pos + 2 < end) {
+            pos[0] = '%';
+            pos[1] = hex[(* (const unsigned char *) src) >> 4];
+            pos[2] = hex[(* (const unsigned char *) src) & 0xf];
+            pos += 2;
+        } else {
+            return -1;
+        }
+    }
+
+    *pos = '\0';
+    return (*src == '\0') ? (int)(pos - dst) : -1;
+}
+
+static void print_dir_entry(struct de *de)
+{
+    char size[64], mod[64], href[PATH_MAX];
+    struct tm *tm;
+
+    if (de->file.is_directory) {
+        mg_snprintf(de->conn, size, sizeof(size), "%s", "[DIRECTORY]");
+    } else {
+        /* We use (signed) cast below because MSVC 6 compiler cannot
+           convert unsigned __int64 to double. Sigh. */
+        if (de->file.size < 1024) {
+            mg_snprintf(de->conn, size, sizeof(size), "%d", (int) de->file.size);
+        } else if (de->file.size < 0x100000) {
+            mg_snprintf(de->conn, size, sizeof(size),
+                        "%.1fk", (double) de->file.size / 1024.0);
+        } else if (de->file.size < 0x40000000) {
+            mg_snprintf(de->conn, size, sizeof(size),
+                        "%.1fM", (double) de->file.size / 1048576);
+        } else {
+            mg_snprintf(de->conn, size, sizeof(size),
+                        "%.1fG", (double) de->file.size / 1073741824);
+        }
+    }
+    tm = localtime(&de->file.modification_time);
+    if (tm != NULL) {
+        strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
+    } else {
+        strncpy(mod, "01-Jan-1970 00:00", sizeof(mod));
+        mod[sizeof(mod) - 1] = '\0';
+    }
+    mg_url_encode(de->file_name, href, sizeof(href));
+    de->conn->num_bytes_sent += mg_printf(de->conn,
+                                          "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
+                                          "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
+                                          de->conn->request_info.uri, href, de->file.is_directory ? "/" : "",
+                                          de->file_name, de->file.is_directory ? "/" : "", mod, size);
+}
+
+/* This function is called from send_directory() and used for
+   sorting directory entries by size, or name, or modification time.
+   On windows, __cdecl specification is needed in case if project is built
+   with __stdcall convention. qsort always requires __cdels callback. */
+static int WINCDECL compare_dir_entries(const void *p1, const void *p2)
+{
+    const struct de *a = (const struct de *) p1, *b = (const struct de *) p2;
+    const char *query_string = a->conn->request_info.query_string;
+    int cmp_result = 0;
+
+    if (query_string == NULL) {
+        query_string = "na";
+    }
+
+    if (a->file.is_directory && !b->file.is_directory) {
+        return -1;  /* Always put directories on top */
+    } else if (!a->file.is_directory && b->file.is_directory) {
+        return 1;   /* Always put directories on top */
+    } else if (*query_string == 'n') {
+        cmp_result = strcmp(a->file_name, b->file_name);
+    } else if (*query_string == 's') {
+        cmp_result = a->file.size == b->file.size ? 0 :
+                     a->file.size > b->file.size ? 1 : -1;
+    } else if (*query_string == 'd') {
+        cmp_result = a->file.modification_time == b->file.modification_time ? 0 :
+                     a->file.modification_time > b->file.modification_time ? 1 : -1;
+    }
+
+    return query_string[1] == 'd' ? -cmp_result : cmp_result;
+}
+
+static int must_hide_file(struct mg_connection *conn, const char *path)
+{
+    const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
+    const char *pattern = conn->ctx->config[HIDE_FILES];
+    return match_prefix(pw_pattern, (int)strlen(pw_pattern), path) > 0 ||
+           (pattern != NULL && match_prefix(pattern, (int)strlen(pattern), path) > 0);
+}
+
+static int scan_directory(struct mg_connection *conn, const char *dir,
+                          void *data, void (*cb)(struct de *, void *))
+{
+    char path[PATH_MAX];
+    struct dirent *dp;
+    DIR *dirp;
+    struct de de;
+
+    if ((dirp = opendir(dir)) == NULL) {
+        return 0;
+    } else {
+        de.conn = conn;
+
+        while ((dp = readdir(dirp)) != NULL) {
+            /* Do not show current dir and hidden files */
+            if (!strcmp(dp->d_name, ".") ||
+                !strcmp(dp->d_name, "..") ||
+                must_hide_file(conn, dp->d_name)) {
+                continue;
+            }
+
+            mg_snprintf(conn, path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
+
+            /* If we don't memset stat structure to zero, mtime will have
+               garbage and strftime() will segfault later on in
+               print_dir_entry(). memset is required only if mg_stat()
+               fails. For more details, see
+               http://code.google.com/p/mongoose/issues/detail?id=79 */
+            memset(&de.file, 0, sizeof(de.file));
+            if (!mg_stat(conn, path, &de.file)) {
+                mg_cry(conn, "%s: mg_stat(%s) failed: %s",
+                       __func__, path, strerror(ERRNO));
+            }
+
+            de.file_name = dp->d_name;
+            cb(&de, data);
+        }
+        (void) closedir(dirp);
+    }
+    return 1;
+}
+
+static int remove_directory(struct mg_connection *conn, const char *dir)
+{
+    char path[PATH_MAX];
+    struct dirent *dp;
+    DIR *dirp;
+    struct de de;
+
+    if ((dirp = opendir(dir)) == NULL) {
+        return 0;
+    } else {
+        de.conn = conn;
+
+        while ((dp = readdir(dirp)) != NULL) {
+            /* Do not show current dir (but show hidden files as they will
+               also be removed) */
+            if (!strcmp(dp->d_name, ".") ||
+                !strcmp(dp->d_name, "..")) {
+                continue;
+            }
+
+            mg_snprintf(conn, path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
+
+            /* If we don't memset stat structure to zero, mtime will have
+               garbage and strftime() will segfault later on in
+               print_dir_entry(). memset is required only if mg_stat()
+               fails. For more details, see
+               http://code.google.com/p/mongoose/issues/detail?id=79 */
+            memset(&de.file, 0, sizeof(de.file));
+            if (!mg_stat(conn, path, &de.file)) {
+                mg_cry(conn, "%s: mg_stat(%s) failed: %s",
+                       __func__, path, strerror(ERRNO));
+            }
+            if(de.file.modification_time) {
+                if(de.file.is_directory) {
+                    remove_directory(conn, path);
+                } else {
+                    mg_remove(path);
+                }
+            }
+
+        }
+        (void) closedir(dirp);
+
+        IGNORE_UNUSED_RESULT(rmdir(dir));
+    }
+
+    return 1;
+}
+
+struct dir_scan_data {
+    struct de *entries;
+    int num_entries;
+    int arr_size;
+};
+
+/* Behaves like realloc(), but frees original pointer on failure */
+static void *realloc2(void *ptr, size_t size)
+{
+    void *new_ptr = realloc(ptr, size);
+    if (new_ptr == NULL) {
+        free(ptr);
+    }
+    return new_ptr;
+}
+
+static void dir_scan_callback(struct de *de, void *data)
+{
+    struct dir_scan_data *dsd = (struct dir_scan_data *) data;
+
+    if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
+        dsd->arr_size *= 2;
+        dsd->entries = (struct de *) realloc2(dsd->entries, dsd->arr_size *
+                                              sizeof(dsd->entries[0]));
+    }
+    if (dsd->entries == NULL) {
+        /* TODO(lsm): propagate an error to the caller */
+        dsd->num_entries = 0;
+    } else {
+        dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
+        dsd->entries[dsd->num_entries].file = de->file;
+        dsd->entries[dsd->num_entries].conn = de->conn;
+        dsd->num_entries++;
+    }
+}
+
+static void handle_directory_request(struct mg_connection *conn,
+                                     const char *dir)
+{
+    int i, sort_direction;
+    struct dir_scan_data data = { NULL, 0, 128 };
+    char date[64];
+    time_t curtime = time(NULL);
+
+    if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
+        send_http_error(conn, 500, "Cannot open directory",
+                        "Error: opendir(%s): %s", dir, strerror(ERRNO));
+        return;
+    }
+
+    gmt_time_string(date, sizeof(date), &curtime);
+
+    sort_direction = conn->request_info.query_string != NULL &&
+                     conn->request_info.query_string[1] == 'd' ? 'a' : 'd';
+
+    conn->must_close = 1;
+    mg_printf(conn, "HTTP/1.1 200 OK\r\n"
+                    "Date: %s\r\n"
+                    "Connection: close\r\n"
+                    "Content-Type: text/html; charset=utf-8\r\n\r\n",
+                    date);
+
+    conn->num_bytes_sent += mg_printf(conn,
+                                      "<html><head><title>Index of %s</title>"
+                                      "<style>th {text-align: left;}</style></head>"
+                                      "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
+                                      "<tr><th><a href=\"?n%c\">Name</a></th>"
+                                      "<th><a href=\"?d%c\">Modified</a></th>"
+                                      "<th><a href=\"?s%c\">Size</a></th></tr>"
+                                      "<tr><td colspan=\"3\"><hr></td></tr>",
+                                      conn->request_info.uri, conn->request_info.uri,
+                                      sort_direction, sort_direction, sort_direction);
+
+    /* Print first entry - link to a parent directory */
+    conn->num_bytes_sent += mg_printf(conn,
+                                      "<tr><td><a href=\"%s%s\">%s</a></td>"
+                                      "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
+                                      conn->request_info.uri, "..", "Parent directory", "-", "-");
+
+    /* Sort and print directory entries */
+    if (data.entries != NULL) {
+        qsort(data.entries, (size_t) data.num_entries,
+              sizeof(data.entries[0]), compare_dir_entries);
+        for (i = 0; i < data.num_entries; i++) {
+            print_dir_entry(&data.entries[i]);
+            free(data.entries[i].file_name);
+        }
+        free(data.entries);
+    }
+
+    conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
+    conn->status_code = 200;
+}
+
+/* Send len bytes from the opened file to the client. */
+static void send_file_data(struct mg_connection *conn, struct file *filep,
+                           int64_t offset, int64_t len)
+{
+    char buf[MG_BUF_LEN];
+    int to_read, num_read, num_written;
+
+    /* Sanity check the offset */
+    offset = offset < 0 ? 0 : offset > filep->size ? filep->size : offset;
+
+    if (len > 0 && filep->membuf != NULL && filep->size > 0) {
+        if (len > filep->size - offset) {
+            len = filep->size - offset;
+        }
+        mg_write(conn, filep->membuf + offset, (size_t) len);
+    } else if (len > 0 && filep->fp != NULL) {
+        if (offset > 0 && fseeko(filep->fp, offset, SEEK_SET) != 0) {
+            mg_cry(conn, "%s: fseeko() failed: %s",
+                   __func__, strerror(ERRNO));
+        }
+        while (len > 0) {
+            /* Calculate how much to read from the file in the buffer */
+            to_read = sizeof(buf);
+            if ((int64_t) to_read > len) {
+                to_read = (int) len;
+            }
+
+            /* Read from file, exit the loop on error */
+            if ((num_read = (int) fread(buf, 1, (size_t) to_read, filep->fp)) <= 0) {
+                break;
+            }
+
+            /* Send read bytes to the client, exit the loop on error */
+            if ((num_written = mg_write(conn, buf, (size_t) num_read)) != num_read) {
+                break;
+            }
+
+            /* Both read and were successful, adjust counters */
+            conn->num_bytes_sent += num_written;
+            len -= num_written;
+        }
+    }
+}
+
+static int parse_range_header(const char *header, int64_t *a, int64_t *b)
+{
+    return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
+}
+
+static void construct_etag(char *buf, size_t buf_len,
+                           const struct file *filep)
+{
+    snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"",
+             (unsigned long) filep->modification_time, filep->size);
+}
+
+static void fclose_on_exec(struct file *filep, struct mg_connection *conn)
+{
+    if (filep != NULL && filep->fp != NULL) {
+#ifdef _WIN32
+        (void) conn; /* Unused. */
+#else
+        if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
+            mg_cry(conn, "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
+                   __func__, strerror(ERRNO));
+        }
+#endif
+    }
+}
+
+static void handle_file_request(struct mg_connection *conn, const char *path,
+                                struct file *filep)
+{
+    char date[64], lm[64], etag[64], range[64];
+    const char *msg = "OK", *hdr;
+    time_t curtime = time(NULL);
+    int64_t cl, r1, r2;
+    struct vec mime_vec;
+    int n;
+    char gz_path[PATH_MAX];
+    char const* encoding = "";
+
+    get_mime_type(conn->ctx, path, &mime_vec);
+    cl = filep->size;
+    conn->status_code = 200;
+    range[0] = '\0';
+
+    /* if this file is in fact a pre-gzipped file, rewrite its filename
+       it's important to rewrite the filename after resolving
+       the mime type from it, to preserve the actual file's type */
+    if (filep->gzipped) {
+        snprintf(gz_path, sizeof(gz_path), "%s.gz", path);
+        path = gz_path;
+        encoding = "Content-Encoding: gzip\r\n";
+    }
+
+    if (!mg_fopen(conn, path, "rb", filep)) {
+        send_http_error(conn, 500, http_500_error,
+                        "fopen(%s): %s", path, strerror(ERRNO));
+        return;
+    }
+
+    fclose_on_exec(filep, conn);
+
+    /* If Range: header specified, act accordingly */
+    r1 = r2 = 0;
+    hdr = mg_get_header(conn, "Range");
+    if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 &&
+        r1 >= 0 && r2 >= 0) {
+        /* actually, range requests don't play well with a pre-gzipped
+           file (since the range is specified in the uncompressed space) */
+        if (filep->gzipped) {
+            send_http_error(conn, 501, "Not Implemented", "range requests in gzipped files are not supported");
+            mg_fclose(filep);
+            return;
+        }
+        conn->status_code = 206;
+cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1: cl - r1;
+        mg_snprintf(conn, range, sizeof(range),
+                    "Content-Range: bytes "
+                    "%" INT64_FMT "-%"
+                    INT64_FMT "/%" INT64_FMT "\r\n",
+                    r1, r1 + cl - 1, filep->size);
+        msg = "Partial Content";
+    }
+
+    /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
+       http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
+    gmt_time_string(date, sizeof(date), &curtime);
+    gmt_time_string(lm, sizeof(lm), &filep->modification_time);
+    construct_etag(etag, sizeof(etag), filep);
+
+    (void) mg_printf(conn,
+                     "HTTP/1.1 %d %s\r\n"
+                     "Date: %s\r\n"
+                     "Last-Modified: %s\r\n"
+                     "Etag: %s\r\n"
+                     "Content-Type: %.*s\r\n"
+                     "Content-Length: %" INT64_FMT "\r\n"
+                     "Connection: %s\r\n"
+                     "Accept-Ranges: bytes\r\n"
+                     "%s%s\r\n",
+                     conn->status_code, msg, date, lm, etag, (int) mime_vec.len,
+                     mime_vec.ptr, cl, suggest_connection_header(conn), range, encoding);
+
+    if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
+        send_file_data(conn, filep, r1, cl);
+    }
+    mg_fclose(filep);
+}
+
+void mg_send_file(struct mg_connection *conn, const char *path)
+{
+    struct file file = STRUCT_FILE_INITIALIZER;
+    if (mg_stat(conn, path, &file)) {
+        handle_file_request(conn, path, &file);
+    } else {
+        send_http_error(conn, 404, "Not Found", "%s", "File not found");
+    }
+}
+
+
+/* Parse HTTP headers from the given buffer, advance buffer to the point
+   where parsing stopped. */
+static void parse_http_headers(char **buf, struct mg_request_info *ri)
+{
+    int i;
+
+    for (i = 0; i < (int) ARRAY_SIZE(ri->http_headers); i++) {
+        ri->http_headers[i].name = skip_quoted(buf, ":", " ", 0);
+        ri->http_headers[i].value = skip(buf, "\r\n");
+        if (ri->http_headers[i].name[0] == '\0')
+            break;
+        ri->num_headers = i + 1;
+    }
+}
+
+static int is_valid_http_method(const char *method)
+{
+    return !strcmp(method, "GET") || !strcmp(method, "POST") ||
+           !strcmp(method, "HEAD") || !strcmp(method, "CONNECT") ||
+           !strcmp(method, "PUT") || !strcmp(method, "DELETE") ||
+           !strcmp(method, "OPTIONS") || !strcmp(method, "PROPFIND")
+           || !strcmp(method, "MKCOL")
+           ;
+}
+
+/* Parse HTTP request, fill in mg_request_info structure.
+   This function modifies the buffer by NUL-terminating
+   HTTP request components, header names and header values. */
+static int parse_http_message(char *buf, int len, struct mg_request_info *ri)
+{
+    int is_request, request_length = get_request_len(buf, len);
+    if (request_length > 0) {
+        /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_port */
+        ri->remote_user = ri->request_method = ri->uri = ri->http_version = NULL;
+        ri->num_headers = 0;
+
+        buf[request_length - 1] = '\0';
+
+        /* RFC says that all initial whitespaces should be ingored */
+        while (*buf != '\0' && isspace(* (unsigned char *) buf)) {
+            buf++;
+        }
+        ri->request_method = skip(&buf, " ");
+        ri->uri = skip(&buf, " ");
+        ri->http_version = skip(&buf, "\r\n");
+
+        /* HTTP message could be either HTTP request or HTTP response, e.g.
+           "GET / HTTP/1.0 ...." or  "HTTP/1.0 200 OK ..." */
+        is_request = is_valid_http_method(ri->request_method);
+        if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0) ||
+            (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
+            request_length = -1;
+        } else {
+            if (is_request) {
+                ri->http_version += 5;
+            }
+            parse_http_headers(&buf, ri);
+        }
+    }
+    return request_length;
+}
+
+/* Keep reading the input (either opened file descriptor fd, or socket sock,
+   or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
+   buffer (which marks the end of HTTP request). Buffer buf may already
+   have some data. The length of the data is stored in nread.
+   Upon every read operation, increase nread by the number of bytes read. */
+static int read_request(FILE *fp, struct mg_connection *conn,
+                        char *buf, int bufsiz, int *nread)
+{
+    int request_len, n = 0;
+
+    request_len = get_request_len(buf, *nread);
+    while (conn->ctx->stop_flag == 0 &&
+           *nread < bufsiz && request_len == 0 &&
+           (n = pull(fp, conn, buf + *nread, bufsiz - *nread)) > 0) {
+        *nread += n;
+        assert(*nread <= bufsiz);
+        request_len = get_request_len(buf, *nread);
+    }
+
+    return request_len <= 0 && n <= 0 ? -1 : request_len;
+}
+
+/* For given directory path, substitute it to valid index file.
+   Return 1 if index file has been found, 0 if not found.
+   If the file is found, it's stats is returned in stp. */
+static int substitute_index_file(struct mg_connection *conn, char *path,
+                                 size_t path_len, struct file *filep)
+{
+    const char *list = conn->ctx->config[INDEX_FILES];
+    struct file file = STRUCT_FILE_INITIALIZER;
+    struct vec filename_vec;
+    size_t n = strlen(path);
+    int found = 0;
+
+    /* The 'path' given to us points to the directory. Remove all trailing
+       directory separator characters from the end of the path, and
+       then append single directory separator character. */
+    while (n > 0 && path[n - 1] == '/') {
+        n--;
+    }
+    path[n] = '/';
+
+    /* Traverse index files list. For each entry, append it to the given
+       path and see if the file exists. If it exists, break the loop */
+    while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
+
+        /* Ignore too long entries that may overflow path buffer */
+        if (filename_vec.len > path_len - (n + 2))
+            continue;
+
+        /* Prepare full path to the index file */
+        mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
+
+        /* Does it exist? */
+        if (mg_stat(conn, path, &file)) {
+            /* Yes it does, break the loop */
+            *filep = file;
+            found = 1;
+            break;
+        }
+    }
+
+    /* If no index file exists, restore directory path */
+    if (!found) {
+        path[n] = '\0';
+    }
+
+    return found;
+}
+
+/* Return True if we should reply 304 Not Modified. */
+static int is_not_modified(const struct mg_connection *conn,
+                           const struct file *filep)
+{
+    char etag[64];
+    const char *ims = mg_get_header(conn, "If-Modified-Since");
+    const char *inm = mg_get_header(conn, "If-None-Match");
+    construct_etag(etag, sizeof(etag), filep);
+    return (inm != NULL && !mg_strcasecmp(etag, inm)) ||
+           (ims != NULL && filep->modification_time <= parse_date_string(ims));
+}
+
+static int forward_body_data(struct mg_connection *conn, FILE *fp,
+                             SOCKET sock, SSL *ssl)
+{
+    const char *expect, *body;
+    char buf[MG_BUF_LEN];
+    int to_read, nread, buffered_len, success = 0;
+
+    expect = mg_get_header(conn, "Expect");
+    assert(fp != NULL);
+
+    if (conn->content_len == -1) {
+        send_http_error(conn, 411, "Length Required", "%s", "");
+    } else if (expect != NULL && mg_strcasecmp(expect, "100-continue")) {
+        send_http_error(conn, 417, "Expectation Failed", "%s", "");
+    } else {
+        if (expect != NULL) {
+            (void) mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
+        }
+
+        body = conn->buf + conn->request_len + conn->consumed_content;
+        buffered_len = (int)(&conn->buf[conn->data_len] - body);
+        assert(buffered_len >= 0);
+        assert(conn->consumed_content == 0);
+
+        if (buffered_len > 0) {
+            if ((int64_t) buffered_len > conn->content_len) {
+                buffered_len = (int) conn->content_len;
+            }
+            push(fp, sock, ssl, body, (int64_t) buffered_len);
+            conn->consumed_content += buffered_len;
+        }
+
+        nread = 0;
+        while (conn->consumed_content < conn->content_len) {
+            to_read = sizeof(buf);
+            if ((int64_t) to_read > conn->content_len - conn->consumed_content) {
+                to_read = (int) (conn->content_len - conn->consumed_content);
+            }
+            nread = pull(NULL, conn, buf, to_read);
+            if (nread <= 0 || push(fp, sock, ssl, buf, nread) != nread) {
+                break;
+            }
+            conn->consumed_content += nread;
+        }
+
+        if (conn->consumed_content == conn->content_len) {
+            success = nread >= 0;
+        }
+
+        /* Each error code path in this function must send an error */
+        if (!success) {
+            send_http_error(conn, 577, http_500_error, "%s", "");
+        }
+    }
+
+    return success;
+}
+
+#if !defined(NO_CGI)
+/* This structure helps to create an environment for the spawned CGI program.
+   Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
+   last element must be NULL.
+   However, on Windows there is a requirement that all these VARIABLE=VALUE\0
+   strings must reside in a contiguous buffer. The end of the buffer is
+   marked by two '\0' characters.
+   We satisfy both worlds: we create an envp array (which is vars), all
+   entries are actually pointers inside buf. */
+struct cgi_env_block {
+    struct mg_connection *conn;
+    char buf[CGI_ENVIRONMENT_SIZE]; /* Environment buffer */
+    int len; /* Space taken */
+    char *vars[MAX_CGI_ENVIR_VARS]; /* char **envp */
+    int nvars; /* Number of variables */
+};
+
+static char *addenv(struct cgi_env_block *block,
+                    PRINTF_FORMAT_STRING(const char *fmt), ...)
+PRINTF_ARGS(2, 3);
+
+/* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
+   pointer into the vars array. */
+static char *addenv(struct cgi_env_block *block, const char *fmt, ...)
+{
+    int n, space;
+    char *added;
+    va_list ap;
+
+    /* Calculate how much space is left in the buffer */
+    space = sizeof(block->buf) - block->len - 2;
+    assert(space >= 0);
+
+    /* Make a pointer to the free space int the buffer */
+    added = block->buf + block->len;
+
+    /* Copy VARIABLE=VALUE\0 string into the free space */
+    va_start(ap, fmt);
+    n = mg_vsnprintf(block->conn, added, (size_t) space, fmt, ap);
+    va_end(ap);
+
+    /* Make sure we do not overflow buffer and the envp array */
+    if (n > 0 && n + 1 < space &&
+        block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
+        /* Append a pointer to the added string into the envp array */
+        block->vars[block->nvars++] = added;
+        /* Bump up used length counter. Include \0 terminator */
+        block->len += n + 1;
+    } else {
+        mg_cry(block->conn, "%s: CGI env buffer truncated for [%s]", __func__, fmt);
+    }
+
+    return added;
+}
+
+static void prepare_cgi_environment(struct mg_connection *conn,
+                                    const char *prog,
+                                    struct cgi_env_block *blk)
+{
+    const char *s, *slash;
+    struct vec var_vec;
+    char *p, src_addr[IP_ADDR_STR_LEN];
+    int  i;
+
+    blk->len = blk->nvars = 0;
+    blk->conn = conn;
+    sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
+
+    addenv(blk, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
+    addenv(blk, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
+    addenv(blk, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
+    addenv(blk, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
+
+    /* Prepare the environment block */
+    addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
+    addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
+    addenv(blk, "%s", "REDIRECT_STATUS=200"); /* For PHP */
+
+    /* TODO(lsm): fix this for IPv6 case */
+    addenv(blk, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
+
+    addenv(blk, "REQUEST_METHOD=%s", conn->request_info.request_method);
+    addenv(blk, "REMOTE_ADDR=%s", src_addr);
+    addenv(blk, "REMOTE_PORT=%d", conn->request_info.remote_port);
+    addenv(blk, "REQUEST_URI=%s", conn->request_info.uri);
+
+    /* SCRIPT_NAME */
+    assert(conn->request_info.uri[0] == '/');
+    slash = strrchr(conn->request_info.uri, '/');
+    if ((s = strrchr(prog, '/')) == NULL)
+        s = prog;
+    addenv(blk, "SCRIPT_NAME=%.*s%s", (int) (slash - conn->request_info.uri),
+           conn->request_info.uri, s);
+
+    addenv(blk, "SCRIPT_FILENAME=%s", prog);
+    addenv(blk, "PATH_TRANSLATED=%s", prog);
+    addenv(blk, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
+
+    if ((s = mg_get_header(conn, "Content-Type")) != NULL)
+        addenv(blk, "CONTENT_TYPE=%s", s);
+
+    if (conn->request_info.query_string != NULL)
+        addenv(blk, "QUERY_STRING=%s", conn->request_info.query_string);
+
+    if ((s = mg_get_header(conn, "Content-Length")) != NULL)
+        addenv(blk, "CONTENT_LENGTH=%s", s);
+
+    if ((s = getenv("PATH")) != NULL)
+        addenv(blk, "PATH=%s", s);
+
+    if (conn->path_info != NULL) {
+        addenv(blk, "PATH_INFO=%s", conn->path_info);
+    }
+
+#if defined(_WIN32)
+    if ((s = getenv("COMSPEC")) != NULL) {
+        addenv(blk, "COMSPEC=%s", s);
+    }
+    if ((s = getenv("SYSTEMROOT")) != NULL) {
+        addenv(blk, "SYSTEMROOT=%s", s);
+    }
+    if ((s = getenv("SystemDrive")) != NULL) {
+        addenv(blk, "SystemDrive=%s", s);
+    }
+    if ((s = getenv("ProgramFiles")) != NULL) {
+        addenv(blk, "ProgramFiles=%s", s);
+    }
+    if ((s = getenv("ProgramFiles(x86)")) != NULL) {
+        addenv(blk, "ProgramFiles(x86)=%s", s);
+    }
+#else
+    if ((s = getenv("LD_LIBRARY_PATH")) != NULL)
+        addenv(blk, "LD_LIBRARY_PATH=%s", s);
+#endif /* _WIN32 */
+
+    if ((s = getenv("PERLLIB")) != NULL)
+        addenv(blk, "PERLLIB=%s", s);
+
+    if (conn->request_info.remote_user != NULL) {
+        addenv(blk, "REMOTE_USER=%s", conn->request_info.remote_user);
+        addenv(blk, "%s", "AUTH_TYPE=Digest");
+    }
+
+    /* Add all headers as HTTP_* variables */
+    for (i = 0; i < conn->request_info.num_headers; i++) {
+        p = addenv(blk, "HTTP_%s=%s",
+                   conn->request_info.http_headers[i].name,
+                   conn->request_info.http_headers[i].value);
+
+        /* Convert variable name into uppercase, and change - to _ */
+        for (; *p != '=' && *p != '\0'; p++) {
+            if (*p == '-')
+                *p = '_';
+            *p = (char) toupper(* (unsigned char *) p);
+        }
+    }
+
+    /* Add user-specified variables */
+    s = conn->ctx->config[CGI_ENVIRONMENT];
+    while ((s = next_option(s, &var_vec, NULL)) != NULL) {
+        addenv(blk, "%.*s", (int) var_vec.len, var_vec.ptr);
+    }
+
+    blk->vars[blk->nvars++] = NULL;
+    blk->buf[blk->len++] = '\0';
+
+    assert(blk->nvars < (int) ARRAY_SIZE(blk->vars));
+    assert(blk->len > 0);
+    assert(blk->len < (int) sizeof(blk->buf));
+}
+
+static void handle_cgi_request(struct mg_connection *conn, const char *prog)
+{
+    char *buf;
+    size_t buflen;
+    int headers_len, data_len, i, fdin[2] = { 0, 0 }, fdout[2] = { 0, 0 };
+    const char *status, *status_text, *connection_state;
+    char *pbuf, dir[PATH_MAX], *p;
+    struct mg_request_info ri;
+    struct cgi_env_block blk;
+    FILE *in = NULL, *out = NULL;
+    struct file fout = STRUCT_FILE_INITIALIZER;
+    pid_t pid = (pid_t) -1;
+
+    buf = NULL;
+    buflen = 16384;
+    prepare_cgi_environment(conn, prog, &blk);
+
+    /* CGI must be executed in its own directory. 'dir' must point to the
+       directory containing executable program, 'p' must point to the
+       executable program name relative to 'dir'. */
+    (void) mg_snprintf(conn, dir, sizeof(dir), "%s", prog);
+    if ((p = strrchr(dir, '/')) != NULL) {
+        *p++ = '\0';
+    } else {
+        dir[0] = '.', dir[1] = '\0';
+        p = (char *) prog;
+    }
+
+    if (pipe(fdin) != 0 || pipe(fdout) != 0) {
+        send_http_error(conn, 500, http_500_error,
+                        "Cannot create CGI pipe: %s", strerror(ERRNO));
+        goto done;
+    }
+
+    pid = spawn_process(conn, p, blk.buf, blk.vars, fdin[0], fdout[1], dir);
+    if (pid == (pid_t) -1) {
+        send_http_error(conn, 500, http_500_error,
+                        "Cannot spawn CGI process [%s]: %s", prog, strerror(ERRNO));
+        goto done;
+    }
+
+    /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
+    set_close_on_exec(fdin[0], conn);
+    set_close_on_exec(fdin[1], conn);
+    set_close_on_exec(fdout[0], conn);
+    set_close_on_exec(fdout[1], conn);
+
+    /* Parent closes only one side of the pipes.
+       If we don't mark them as closed, close() attempt before
+       return from this function throws an exception on Windows.
+       Windows does not like when closed descriptor is closed again. */
+    (void) close(fdin[0]);
+    (void) close(fdout[1]);
+    fdin[0] = fdout[1] = -1;
+
+
+    if ((in = fdopen(fdin[1], "wb")) == NULL ||
+        (out = fdopen(fdout[0], "rb")) == NULL) {
+        send_http_error(conn, 500, http_500_error,
+                        "fopen: %s", strerror(ERRNO));
+        goto done;
+    }
+
+    setbuf(in, NULL);
+    setbuf(out, NULL);
+    fout.fp = out;
+
+    /* Send POST data to the CGI process if needed */
+    if (!strcmp(conn->request_info.request_method, "POST") &&
+        !forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
+        goto done;
+    }
+
+    /* Close so child gets an EOF. */
+    fclose(in);
+    in = NULL;
+    fdin[1] = -1;
+
+    /* Now read CGI reply into a buffer. We need to set correct
+       status code, thus we need to see all HTTP headers first.
+       Do not send anything back to client, until we buffer in all
+       HTTP headers. */
+    data_len = 0;
+    buf = malloc(buflen);
+    if (buf == NULL) {
+        send_http_error(conn, 500, http_500_error,
+                        "Not enough memory for buffer (%u bytes)",
+                        (unsigned int) buflen);
+        goto done;
+    }
+    headers_len = read_request(out, conn, buf, (int) buflen, &data_len);
+    if (headers_len <= 0) {
+        send_http_error(conn, 500, http_500_error,
+                        "CGI program sent malformed or too big (>%u bytes) "
+                        "HTTP headers: [%.*s]",
+                        (unsigned) buflen, data_len, buf);
+        goto done;
+    }
+    pbuf = buf;
+    buf[headers_len - 1] = '\0';
+    parse_http_headers(&pbuf, &ri);
+
+    /* Make up and send the status line */
+    status_text = "OK";
+    if ((status = get_header(&ri, "Status")) != NULL) {
+        conn->status_code = atoi(status);
+        status_text = status;
+        while (isdigit(* (unsigned char *) status_text) || *status_text == ' ') {
+            status_text++;
+        }
+    } else if (get_header(&ri, "Location") != NULL) {
+        conn->status_code = 302;
+    } else {
+        conn->status_code = 200;
+    }
+    connection_state = get_header(&ri, "Connection");
+    if (connection_state == NULL ||
+        mg_strcasecmp(connection_state, "keep-alive")) {
+        conn->must_close = 1;
+    }
+    (void) mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code,
+                     status_text);
+
+    /* Send headers */
+    for (i = 0; i < ri.num_headers; i++) {
+        mg_printf(conn, "%s: %s\r\n",
+                  ri.http_headers[i].name, ri.http_headers[i].value);
+    }
+    mg_write(conn, "\r\n", 2);
+
+    /* Send chunk of data that may have been read after the headers */
+    conn->num_bytes_sent += mg_write(conn, buf + headers_len,
+                                     (size_t)(data_len - headers_len));
+
+    /* Read the rest of CGI output and send to the client */
+    send_file_data(conn, &fout, 0, INT64_MAX);
+
+done:
+    if (pid != (pid_t) -1) {
+        kill(pid, SIGKILL);
+#if !defined(_WIN32)
+        {
+            int st;
+            while (waitpid(pid, &st, 0) != -1);  /* clean zombies */
+        }
+#endif
+    }
+    if (fdin[0] != -1) {
+        close(fdin[0]);
+    }
+    if (fdout[1] != -1) {
+        close(fdout[1]);
+    }
+
+    if (in != NULL) {
+        fclose(in);
+    } else if (fdin[1] != -1) {
+        close(fdin[1]);
+    }
+
+    if (out != NULL) {
+        fclose(out);
+    } else if (fdout[0] != -1) {
+        close(fdout[0]);
+    }
+    if (buf != NULL) {
+        free(buf);
+    }
+}
+#endif /* !NO_CGI */
+
+/* For a given PUT path, create all intermediate subdirectories
+   for given path. Return 0 if the path itself is a directory,
+   or -1 on error, 1 if OK. */
+static int put_dir(struct mg_connection *conn, const char *path)
+{
+    char buf[PATH_MAX];
+    const char *s, *p;
+    struct file file = STRUCT_FILE_INITIALIZER;
+    int len, res = 1;
+
+    for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
+        len = (int)(p - path);
+        if (len >= (int) sizeof(buf)) {
+            res = -1;
+            break;
+        }
+        memcpy(buf, path, len);
+        buf[len] = '\0';
+
+        /* Try to create intermediate directory */
+        DEBUG_TRACE(("mkdir(%s)", buf));
+        if (!mg_stat(conn, buf, &file) && mg_mkdir(buf, 0755) != 0) {
+            res = -1;
+            break;
+        }
+
+        /* Is path itself a directory? */
+        if (p[1] == '\0') {
+            res = 0;
+        }
+    }
+
+    return res;
+}
+
+static void mkcol(struct mg_connection *conn, const char *path)
+{
+    int rc, body_len;
+    struct de de;
+    char date[64];

+    time_t curtime = time(NULL);
+
+    memset(&de.file, 0, sizeof(de.file));
+    if (!mg_stat(conn, path, &de.file)) {
+        mg_cry(conn, "%s: mg_stat(%s) failed: %s",
+               __func__, path, strerror(ERRNO));
+    }
+
+    if(de.file.modification_time) {
+        send_http_error(conn, 405, "Method Not Allowed",
+                        "mkcol(%s): %s", path, strerror(ERRNO));
+        return;
+    }
+
+    body_len = conn->data_len - conn->request_len;
+    if(body_len > 0) {
+        send_http_error(conn, 415, "Unsupported media type",
+                        "mkcol(%s): %s", path, strerror(ERRNO));
+        return;
+    }
+
+    rc = mg_mkdir(path, 0755);
+
+    if (rc == 0) {
+        conn->status_code = 201;
+        gmt_time_string(date, sizeof(date), &curtime);
+        mg_printf(conn, "HTTP/1.1 %d Created\r\nDate: %s\r\nContent-Length: 0\r\nConnection: %s\r\n\r\n",
+                  conn->status_code, date, suggest_connection_header(conn));
+    } else if (rc == -1) {
+        if(errno == EEXIST)
+            send_http_error(conn, 405, "Method Not Allowed",
+                            "mkcol(%s): %s", path, strerror(ERRNO));
+        else if(errno == EACCES)
+            send_http_error(conn, 403, "Forbidden",
+                            "mkcol(%s): %s", path, strerror(ERRNO));
+        else if(errno == ENOENT)
+            send_http_error(conn, 409, "Conflict",
+                            "mkcol(%s): %s", path, strerror(ERRNO));
+        else
+            send_http_error(conn, 500, http_500_error,
+                            "fopen(%s): %s", path, strerror(ERRNO));
+    }
+}
+
+static void put_file(struct mg_connection *conn, const char *path)
+{
+    struct file file = STRUCT_FILE_INITIALIZER;
+    const char *range;
+    int64_t r1, r2;
+    int rc;
+    char date[64];

+    time_t curtime = time(NULL);
+
+    conn->status_code = mg_stat(conn, path, &file) ? 200 : 201;
+
+    if ((rc = put_dir(conn, path)) == 0) {
+        gmt_time_string(date, sizeof(date), &curtime);
+        mg_printf(conn, "HTTP/1.1 %d OK\r\nDate: %s\r\nContent-Length: 0\r\nConnection: %s\r\n\r\n",
+                  conn->status_code, date, suggest_connection_header(conn));
+    } else if (rc == -1) {
+        send_http_error(conn, 500, http_500_error,
+                        "put_dir(%s): %s", path, strerror(ERRNO));
+    } else if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
+        mg_fclose(&file);
+        send_http_error(conn, 500, http_500_error,
+                        "fopen(%s): %s", path, strerror(ERRNO));
+    } else {
+        fclose_on_exec(&file, conn);
+        range = mg_get_header(conn, "Content-Range");
+        r1 = r2 = 0;
+        if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
+            conn->status_code = 206;
+            fseeko(file.fp, r1, SEEK_SET);
+        }
+        if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
+            conn->status_code = 500;
+        }
+        gmt_time_string(date, sizeof(date), &curtime);
+        mg_printf(conn, "HTTP/1.1 %d OK\r\nDate: %s\r\nContent-Length: 0\r\nConnection: %s\r\n\r\n",
+                  conn->status_code, date, suggest_connection_header(conn));
+        mg_fclose(&file);
+    }
+}
+
+static void send_ssi_file(struct mg_connection *, const char *,
+                          struct file *, int);
+
+static void do_ssi_include(struct mg_connection *conn, const char *ssi,
+                           char *tag, int include_level)
+{
+    char file_name[MG_BUF_LEN], path[PATH_MAX], *p;
+    struct file file = STRUCT_FILE_INITIALIZER;
+
+    /* sscanf() is safe here, since send_ssi_file() also uses buffer
+       of size MG_BUF_LEN to get the tag. So strlen(tag) is
+       always < MG_BUF_LEN. */
+    if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
+        /* File name is relative to the webserver root */
+        (void) mg_snprintf(conn, path, sizeof(path), "%s%c%s",
+                           conn->ctx->config[DOCUMENT_ROOT], '/', file_name);
+    } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) {
+        /* File name is relative to the webserver working directory
+           or it is absolute system path */
+        (void) mg_snprintf(conn, path, sizeof(path), "%s", file_name);
+    } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 ||
+               sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
+        /* File name is relative to the currect document */
+        (void) mg_snprintf(conn, path, sizeof(path), "%s", ssi);
+        if ((p = strrchr(path, '/')) != NULL) {
+            p[1] = '\0';
+        }
+        (void) mg_snprintf(conn, path + strlen(path),
+                           sizeof(path) - strlen(path), "%s", file_name);
+    } else {
+        mg_cry(conn, "Bad SSI #include: [%s]", tag);
+        return;
+    }
+
+    if (!mg_fopen(conn, path, "rb", &file)) {
+        mg_cry(conn, "Cannot open SSI #include: [%s]: fopen(%s): %s",
+               tag, path, strerror(ERRNO));
+    } else {
+        fclose_on_exec(&file, conn);
+        if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
+                         (int)strlen(conn->ctx->config[SSI_EXTENSIONS]), path) > 0) {
+            send_ssi_file(conn, path, &file, include_level + 1);
+        } else {
+            send_file_data(conn, &file, 0, INT64_MAX);
+        }
+        mg_fclose(&file);
+    }
+}
+
+#if !defined(NO_POPEN)
+static void do_ssi_exec(struct mg_connection *conn, char *tag)
+{
+    char cmd[MG_BUF_LEN] = "";
+    struct file file = STRUCT_FILE_INITIALIZER;
+
+    if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
+        mg_cry(conn, "Bad SSI #exec: [%s]", tag);
+    } else if ((file.fp = popen(cmd, "r")) == NULL) {
+        mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
+    } else {
+        send_file_data(conn, &file, 0, INT64_MAX);
+        pclose(file.fp);
+    }
+}
+#endif /* !NO_POPEN */
+
+static int mg_fgetc(struct file *filep, int offset)
+{
+    if (filep->membuf != NULL && offset >=0 && offset < filep->size) {
+        return ((unsigned char *) filep->membuf)[offset];
+    } else if (filep->fp != NULL) {
+        return fgetc(filep->fp);
+    } else {
+        return EOF;
+    }
+}
+
+static void send_ssi_file(struct mg_connection *conn, const char *path,
+                          struct file *filep, int include_level)
+{
+    char buf[MG_BUF_LEN];
+    int ch, offset, len, in_ssi_tag;
+
+    if (include_level > 10) {
+        mg_cry(conn, "SSI #include level is too deep (%s)", path);
+        return;
+    }
+
+    in_ssi_tag = len = offset = 0;
+    while ((ch = mg_fgetc(filep, offset)) != EOF) {
+        if (in_ssi_tag && ch == '>') {
+            in_ssi_tag = 0;
+            buf[len++] = (char) ch;
+            buf[len] = '\0';
+            assert(len <= (int) sizeof(buf));
+            if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
+                /* Not an SSI tag, pass it */
+                (void) mg_write(conn, buf, (size_t) len);
+            } else {
+                if (!memcmp(buf + 5, "include", 7)) {
+                    do_ssi_include(conn, path, buf + 12, include_level);
+#if !defined(NO_POPEN)
+                } else if (!memcmp(buf + 5, "exec", 4)) {
+                    do_ssi_exec(conn, buf + 9);
+#endif /* !NO_POPEN */
+                } else {
+                    mg_cry(conn, "%s: unknown SSI " "command: \"%s\"", path, buf);
+                }
+            }
+            len = 0;
+        } else if (in_ssi_tag) {
+            if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
+                /* Not an SSI tag */
+                in_ssi_tag = 0;
+            } else if (len == (int) sizeof(buf) - 2) {
+                mg_cry(conn, "%s: SSI tag is too large", path);
+                len = 0;
+            }
+            buf[len++] = ch & 0xff;
+        } else if (ch == '<') {
+            in_ssi_tag = 1;
+            if (len > 0) {
+                mg_write(conn, buf, (size_t) len);
+            }
+            len = 0;
+            buf[len++] = ch & 0xff;
+        } else {
+            buf[len++] = ch & 0xff;
+            if (len == (int) sizeof(buf)) {
+                mg_write(conn, buf, (size_t) len);
+                len = 0;
+            }
+        }
+    }
+
+    /* Send the rest of buffered data */
+    if (len > 0) {
+        mg_write(conn, buf, (size_t) len);
+    }
+}
+
+static void handle_ssi_file_request(struct mg_connection *conn,
+                                    const char *path)
+{
+    struct file file = STRUCT_FILE_INITIALIZER;
+    char date[64];
+    time_t curtime = time(NULL);
+
+    if (!mg_fopen(conn, path, "rb", &file)) {
+        send_http_error(conn, 500, http_500_error, "fopen(%s): %s", path,
+                        strerror(ERRNO));
+    } else {
+        conn->must_close = 1;
+        gmt_time_string(date, sizeof(date), &curtime);
+        fclose_on_exec(&file, conn);
+        mg_printf(conn, "HTTP/1.1 200 OK\r\n"
+                        "Date: %s\r\n"
+                        "Content-Type: text/html\r\n"
+                        "Connection: %s\r\n\r\n",
+                  date, suggest_connection_header(conn));
+        send_ssi_file(conn, path, &file, 0);
+        mg_fclose(&file);
+    }
+}
+
+static void send_options(struct mg_connection *conn)
+{
+    char date[64];
+    time_t curtime = time(NULL);
+
+    conn->status_code = 200;
+    conn->must_close = 1;
+    gmt_time_string(date, sizeof(date), &curtime);
+
+    mg_printf(conn, "HTTP/1.1 200 OK\r\n"
+                    "Date: %s\r\n"
+                    "Connection: %s\r\n"
+                    "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, PROPFIND, MKCOL\r\n"
+                    "DAV: 1\r\n\r\n",
+                    date, suggest_connection_header(conn));
+}
+
+/* Writes PROPFIND properties for a collection element */
+static void print_props(struct mg_connection *conn, const char* uri,
+                        struct file *filep)
+{
+    char mtime[64];
+    gmt_time_string(mtime, sizeof(mtime), &filep->modification_time);
+    conn->num_bytes_sent += mg_printf(conn,
+                                      "<d:response>"
+                                      "<d:href>%s</d:href>"
+                                      "<d:propstat>"
+                                      "<d:prop>"
+                                      "<d:resourcetype>%s</d:resourcetype>"
+                                      "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
+                                      "<d:getlastmodified>%s</d:getlastmodified>"
+                                      "</d:prop>"
+                                      "<d:status>HTTP/1.1 200 OK</d:status>"
+                                      "</d:propstat>"
+                                      "</d:response>\n",
+                                      uri,
+                                      filep->is_directory ? "<d:collection/>" : "",
+                                      filep->size,
+                                      mtime);
+}
+
+static void print_dav_dir_entry(struct de *de, void *data)
+{
+    char href[PATH_MAX];
+    char href_encoded[PATH_MAX];
+    struct mg_connection *conn = (struct mg_connection *) data;
+    mg_snprintf(conn, href, sizeof(href), "%s%s",
+                conn->request_info.uri, de->file_name);
+    mg_url_encode(href, href_encoded, PATH_MAX-1);
+    print_props(conn, href_encoded, &de->file);
+}
+
+static void handle_propfind(struct mg_connection *conn, const char *path,
+                            struct file *filep)
+{
+    const char *depth = mg_get_header(conn, "Depth");
+    char date[64];

+    time_t curtime = time(NULL);
+
+    gmt_time_string(date, sizeof(date), &curtime);
+
+    conn->must_close = 1;
+    conn->status_code = 207;
+    mg_printf(conn, "HTTP/1.1 207 Multi-Status\r\n"
+                    "Date: %s\r\n"
+                    "Connection: %s\r\n"
+                    "Content-Type: text/xml; charset=utf-8\r\n\r\n",
+                    date, suggest_connection_header(conn));
+
+    conn->num_bytes_sent += mg_printf(conn,
+                                      "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+                                      "<d:multistatus xmlns:d='DAV:'>\n");
+
+    /* Print properties for the requested resource itself */
+    print_props(conn, conn->request_info.uri, filep);
+
+    /* If it is a directory, print directory entries too if Depth is not 0 */
+    if (filep->is_directory &&
+        !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes") &&
+        (depth == NULL || strcmp(depth, "0") != 0)) {
+        scan_directory(conn, path, conn, &print_dav_dir_entry);
+    }
+
+    conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
+}
+
+void mg_lock(struct mg_connection* conn)
+{
+    (void) pthread_mutex_lock(&conn->mutex);
+}
+
+void mg_unlock(struct mg_connection* conn)
+{
+    (void) pthread_mutex_unlock(&conn->mutex);
+}
+
+#ifdef USE_LUA
+#include "mod_lua.inl"
+#endif /* USE_LUA */
+
+#if defined(USE_WEBSOCKET)
+
+/* START OF SHA-1 code
+   Copyright(c) By Steve Reid <steve@edmweb.com> */
+#define SHA1HANDSOFF
+#if defined(__sun)
+#include "solarisfixes.h"
+#endif
+
+static int is_big_endian(void)
+{
+    static const int n = 1;
+    return ((char *) &n)[0] == 0;
+}
+
+union char64long16 {
+    unsigned char c[64];
+    uint32_t l[16];
+};
+
+#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
+
+static uint32_t blk0(union char64long16 *block, int i)
+{
+    /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
+    if (!is_big_endian()) {
+        block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
+                      (rol(block->l[i], 8) & 0x00FF00FF);
+    }
+    return block->l[i];
+}
+
+#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
+    ^block->l[(i+2)&15]^block->l[i&15],1))
+#define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(block, i)+0x5A827999+rol(v,5);w=rol(w,30);
+#define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
+#define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
+#define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
+#define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
+
+typedef struct {
+    uint32_t state[5];
+    uint32_t count[2];
+    unsigned char buffer[64];
+} SHA1_CTX;
+
+static void SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
+{
+    uint32_t a, b, c, d, e;
+    union char64long16 block[1];
+
+    memcpy(block, buffer, 64);
+    a = state[0];
+    b = state[1];
+    c = state[2];
+    d = state[3];
+    e = state[4];
+    R0(a,b,c,d,e, 0);
+    R0(e,a,b,c,d, 1);
+    R0(d,e,a,b,c, 2);
+    R0(c,d,e,a,b, 3);
+    R0(b,c,d,e,a, 4);
+    R0(a,b,c,d,e, 5);
+    R0(e,a,b,c,d, 6);
+    R0(d,e,a,b,c, 7);
+    R0(c,d,e,a,b, 8);
+    R0(b,c,d,e,a, 9);
+    R0(a,b,c,d,e,10);
+    R0(e,a,b,c,d,11);
+    R0(d,e,a,b,c,12);
+    R0(c,d,e,a,b,13);
+    R0(b,c,d,e,a,14);
+    R0(a,b,c,d,e,15);
+    R1(e,a,b,c,d,16);
+    R1(d,e,a,b,c,17);
+    R1(c,d,e,a,b,18);
+    R1(b,c,d,e,a,19);
+    R2(a,b,c,d,e,20);
+    R2(e,a,b,c,d,21);
+    R2(d,e,a,b,c,22);
+    R2(c,d,e,a,b,23);
+    R2(b,c,d,e,a,24);
+    R2(a,b,c,d,e,25);
+    R2(e,a,b,c,d,26);
+    R2(d,e,a,b,c,27);
+    R2(c,d,e,a,b,28);
+    R2(b,c,d,e,a,29);
+    R2(a,b,c,d,e,30);
+    R2(e,a,b,c,d,31);
+    R2(d,e,a,b,c,32);
+    R2(c,d,e,a,b,33);
+    R2(b,c,d,e,a,34);
+    R2(a,b,c,d,e,35);
+    R2(e,a,b,c,d,36);
+    R2(d,e,a,b,c,37);
+    R2(c,d,e,a,b,38);
+    R2(b,c,d,e,a,39);
+    R3(a,b,c,d,e,40);
+    R3(e,a,b,c,d,41);
+    R3(d,e,a,b,c,42);
+    R3(c,d,e,a,b,43);
+    R3(b,c,d,e,a,44);
+    R3(a,b,c,d,e,45);
+    R3(e,a,b,c,d,46);
+    R3(d,e,a,b,c,47);
+    R3(c,d,e,a,b,48);
+    R3(b,c,d,e,a,49);
+    R3(a,b,c,d,e,50);
+    R3(e,a,b,c,d,51);
+    R3(d,e,a,b,c,52);
+    R3(c,d,e,a,b,53);
+    R3(b,c,d,e,a,54);
+    R3(a,b,c,d,e,55);
+    R3(e,a,b,c,d,56);
+    R3(d,e,a,b,c,57);
+    R3(c,d,e,a,b,58);
+    R3(b,c,d,e,a,59);
+    R4(a,b,c,d,e,60);
+    R4(e,a,b,c,d,61);
+    R4(d,e,a,b,c,62);
+    R4(c,d,e,a,b,63);
+    R4(b,c,d,e,a,64);
+    R4(a,b,c,d,e,65);
+    R4(e,a,b,c,d,66);
+    R4(d,e,a,b,c,67);
+    R4(c,d,e,a,b,68);
+    R4(b,c,d,e,a,69);
+    R4(a,b,c,d,e,70);
+    R4(e,a,b,c,d,71);
+    R4(d,e,a,b,c,72);
+    R4(c,d,e,a,b,73);
+    R4(b,c,d,e,a,74);
+    R4(a,b,c,d,e,75);
+    R4(e,a,b,c,d,76);
+    R4(d,e,a,b,c,77);
+    R4(c,d,e,a,b,78);
+    R4(b,c,d,e,a,79);
+    state[0] += a;
+    state[1] += b;
+    state[2] += c;
+    state[3] += d;
+    state[4] += e;
+    a = b = c = d = e = 0;
+    memset(block, '\0', sizeof(block));
+}
+
+static void SHA1Init(SHA1_CTX* context)
+{
+    context->state[0] = 0x67452301;
+    context->state[1] = 0xEFCDAB89;
+    context->state[2] = 0x98BADCFE;
+    context->state[3] = 0x10325476;
+    context->state[4] = 0xC3D2E1F0;
+    context->count[0] = context->count[1] = 0;
+}
+
+static void SHA1Update(SHA1_CTX* context, const unsigned char* data,
+                       uint32_t len)
+{
+    uint32_t i, j;
+
+    j = context->count[0];
+    if ((context->count[0] += len << 3) < j)
+        context->count[1]++;
+    context->count[1] += (len>>29);
+    j = (j >> 3) & 63;
+    if ((j + len) > 63) {
+        memcpy(&context->buffer[j], data, (i = 64-j));
+        SHA1Transform(context->state, context->buffer);
+        for ( ; i + 63 < len; i += 64) {
+            SHA1Transform(context->state, &data[i]);
+        }
+        j = 0;
+    } else i = 0;
+    memcpy(&context->buffer[j], &data[i], len - i);
+}
+
+static void SHA1Final(unsigned char digest[20], SHA1_CTX* context)
+{
+    unsigned i;
+    unsigned char finalcount[8], c;
+
+    for (i = 0; i < 8; i++) {
+        finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
+                                         >> ((3-(i & 3)) * 8) ) & 255);
+    }
+    c = 0200;
+    SHA1Update(context, &c, 1);
+    while ((context->count[0] & 504) != 448) {
+        c = 0000;
+        SHA1Update(context, &c, 1);
+    }
+    SHA1Update(context, finalcount, 8);
+    for (i = 0; i < 20; i++) {
+        digest[i] = (unsigned char)
+                    ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
+    }
+    memset(context, '\0', sizeof(*context));
+    memset(&finalcount, '\0', sizeof(finalcount));
+}
+/* END OF SHA1 CODE */
+
+static void send_websocket_handshake(struct mg_connection *conn)
+{
+    static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
+    char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
+    SHA1_CTX sha_ctx;
+
+    mg_snprintf(conn, buf, sizeof(buf), "%s%s",
+                mg_get_header(conn, "Sec-WebSocket-Key"), magic);
+    SHA1Init(&sha_ctx);
+    SHA1Update(&sha_ctx, (unsigned char *) buf, (uint32_t)strlen(buf));
+    SHA1Final((unsigned char *) sha, &sha_ctx);
+    base64_encode((unsigned char *) sha, sizeof(sha), b64_sha);
+    mg_printf(conn, "%s%s%s",
+              "HTTP/1.1 101 Switching Protocols\r\n"
+              "Upgrade: websocket\r\n"
+              "Connection: Upgrade\r\n"
+              "Sec-WebSocket-Accept: ", b64_sha, "\r\n\r\n");
+}
+
+static void read_websocket(struct mg_connection *conn)
+{
+    /* Pointer to the beginning of the portion of the incoming websocket
+       message queue.
+       The original websocket upgrade request is never removed, so the queue
+       begins after it. */
+    unsigned char *buf = (unsigned char *) conn->buf + conn->request_len;
+    int n, error;
+
+    /* body_len is the length of the entire queue in bytes
+       len is the length of the current message
+       data_len is the length of the current message's data payload
+       header_len is the length of the current message's header */
+    size_t i, len, mask_len, data_len, header_len, body_len;
+
+    /* "The masking key is a 32-bit value chosen at random by the client."
+       http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5 */
+    unsigned char mask[4];
+
+    /* data points to the place where the message is stored when passed to the
+       websocket_data callback.  This is either mem on the stack, or a
+       dynamically allocated buffer if it is too large. */
+    char mem[4096];
+    char *data = mem;
+    unsigned char mop;  /* mask flag and opcode */
+
+    /* Loop continuously, reading messages from the socket, invoking the
+       callback, and waiting repeatedly until an error occurs. */
+    assert(conn->content_len == 0);
+    for (;;) {
+        header_len = 0;
+        assert(conn->data_len >= conn->request_len);
+        if ((body_len = conn->data_len - conn->request_len) >= 2) {
+            len = buf[1] & 127;
+            mask_len = buf[1] & 128 ? 4 : 0;
+            if (len < 126 && body_len >= mask_len) {
+                data_len = len;
+                header_len = 2 + mask_len;
+            } else if (len == 126 && body_len >= 4 + mask_len) {
+                header_len = 4 + mask_len;
+                data_len = ((((int) buf[2]) << 8) + buf[3]);
+            } else if (body_len >= 10 + mask_len) {
+                header_len = 10 + mask_len;
+                data_len = (((uint64_t) ntohl(* (uint32_t *) &buf[2])) << 32) +
+                           ntohl(* (uint32_t *) &buf[6]);
+            }
+        }
+
+        if (header_len > 0) {
+            /* Allocate space to hold websocket payload */
+            data = mem;
+            if (data_len > sizeof(mem)) {
+                data = (char *)malloc(data_len);
+                if (data == NULL) {
+                    /* Allocation failed, exit the loop and then close the
+                       connection */
+                    mg_cry(conn, "websocket malloc() failed; closing connection");
+                    break;
+                }
+            }
+
+            /* Copy the mask before we shift the queue and destroy it */
+            if (mask_len > 0) {
+                *(uint32_t*)mask = *(uint32_t*)(buf + header_len - mask_len);
+            } else {
+                *(uint32_t*)mask = 0;
+            }
+
+            /* Read frame payload from the first message in the queue into
+               data and advance the queue by moving the memory in place. */
+            assert(body_len >= header_len);
+            if (data_len + header_len > body_len) {
+                mop = buf[0];   /* current mask and opcode */
+                /* Overflow case */
+                len = body_len - header_len;
+                memcpy(data, buf + header_len, len);
+                error = 0;
+                while (len < data_len) {
+                    int n = pull(NULL, conn, data + len, (int)(data_len - len));
+                    if (n < 0) {
+                        error = 1;
+                        break;
+                    }
+                    len += n;
+                }
+                if (error) {
+                    mg_cry(conn, "Websocket pull failed; closing connection");
+                    break;
+                }
+                conn->data_len = conn->request_len;
+            } else {
+                mop = buf[0];   /* current mask and opcode, overwritten by memmove() */
+                /* Length of the message being read at the front of the
+                   queue */
+                len = data_len + header_len;
+
+                /* Copy the data payload into the data pointer for the
+                   callback */
+                memcpy(data, buf + header_len, data_len);
+
+                /* Move the queue forward len bytes */
+                memmove(buf, buf + len, body_len - len);
+
+                /* Mark the queue as advanced */
+                conn->data_len -= (int)len;
+            }
+
+            /* Apply mask if necessary */
+            if (mask_len > 0) {
+                for (i = 0; i < data_len; ++i) {
+                    data[i] ^= mask[i & 3];
+                }
+            }
+
+            /* Exit the loop if callback signalled to exit,
+               or "connection close" opcode received. */
+            if ((conn->ctx->callbacks.websocket_data != NULL &&
+#ifdef USE_LUA
+                 (conn->lua_websocket_state == NULL) &&
+#endif
+                 !conn->ctx->callbacks.websocket_data(conn, mop, data, data_len)) ||
+#ifdef USE_LUA
+                (conn->lua_websocket_state &&
+                 !lua_websocket_data(conn, mop, data, data_len)) ||
+#endif
+                (buf[0] & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE) {  /* Opcode == 8, connection close */
+                break;
+            }
+
+            if (data != mem) {
+                free(data);
+            }
+            /* Not breaking the loop, process next websocket frame. */
+        } else {
+            /* Read from the socket into the next available location in the
+               message queue. */
+            if ((n = pull(NULL, conn, conn->buf + conn->data_len,
+                          conn->buf_size - conn->data_len)) <= 0) {
+                /* Error, no bytes read */
+                break;
+            }
+            conn->data_len += n;
+        }
+    }
+}
+
+int mg_websocket_write(struct mg_connection* conn, int opcode, const char* data, size_t dataLen)
+{
+    unsigned char header[10];
+    size_t headerLen = 1;
+
+    int retval = -1;
+
+    header[0] = 0x80 + (opcode & 0xF);
+
+    /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
+    if (dataLen < 126) {
+        /* inline 7-bit length field */
+        header[1] = (unsigned char)dataLen;
+        headerLen = 2;
+    } else if (dataLen <= 0xFFFF) {
+        /* 16-bit length field */
+        header[1] = 126;
+        *(uint16_t*)(header + 2) = htons((uint16_t)dataLen);
+        headerLen = 4;
+    } else {
+        /* 64-bit length field */
+        header[1] = 127;
+        *(uint32_t*)(header + 2) = htonl((uint64_t)dataLen >> 32);
+        *(uint32_t*)(header + 6) = htonl(dataLen & 0xFFFFFFFF);
+        headerLen = 10;
+    }
+
+    /* Note that POSIX/Winsock's send() is threadsafe
+       http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
+       but mongoose's mg_printf/mg_write is not (because of the loop in
+       push(), although that is only a problem if the packet is large or
+       outgoing buffer is full). */
+    (void) mg_lock(conn);
+    retval = mg_write(conn, header, headerLen);
+    retval = mg_write(conn, data, dataLen);
+    mg_unlock(conn);
+
+    return retval;
+}
+
+static void handle_websocket_request(struct mg_connection *conn, const char *path, int is_script_resource)
+{
+    const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
+#ifdef USE_LUA
+    int lua_websock, shared_lua_websock = 0;
+    /* TODO: A websocket script may be shared between several clients, allowing them to communicate
+             directly instead of writing to a data base and polling the data base. */
+#endif
+
+    if (version == NULL || strcmp(version, "13") != 0) {
+        send_http_error(conn, 426, "Upgrade Required", "%s", "Upgrade Required");
+    } else if (conn->ctx->callbacks.websocket_connect != NULL &&
+               conn->ctx->callbacks.websocket_connect(conn) != 0) {
+        /* C callback has returned non-zero, do not proceed with handshake. */
+        /* The C callback is called before Lua and may prevent Lua from handling the websocket. */
+    } else {
+#ifdef USE_LUA
+        lua_websock = conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS] ?
+                          match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
+                                       (int)strlen(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
+                                       path) : 0;
+
+        if (lua_websock || shared_lua_websock) {
+            conn->lua_websocket_state = lua_websocket_new(path, conn, !!shared_lua_websock);
+            if (conn->lua_websocket_state) {
+                send_websocket_handshake(conn);
+                if (lua_websocket_ready(conn)) {
+                    read_websocket(conn);
+                }
+            }
+        } else
+#endif
+        {
+            /* No Lua websock script specified. */
+            send_websocket_handshake(conn);
+            if (conn->ctx->callbacks.websocket_ready != NULL) {
+                conn->ctx->callbacks.websocket_ready(conn);
+            }
+            read_websocket(conn);
+        }
+    }
+}
+
+static int is_websocket_request(const struct mg_connection *conn)
+{
+    const char *host, *upgrade, *connection, *version, *key;
+
+    host = mg_get_header(conn, "Host");
+    upgrade = mg_get_header(conn, "Upgrade");
+    connection = mg_get_header(conn, "Connection");
+    key = mg_get_header(conn, "Sec-WebSocket-Key");
+    version = mg_get_header(conn, "Sec-WebSocket-Version");
+
+    return host != NULL && upgrade != NULL && connection != NULL &&
+           key != NULL && version != NULL &&
+           mg_strcasestr(upgrade, "websocket") != NULL &&
+           mg_strcasestr(connection, "Upgrade") != NULL;
+}
+#endif /* !USE_WEBSOCKET */
+
+static int isbyte(int n)
+{
+    return n >= 0 && n <= 255;
+}
+
+static int parse_net(const char *spec, uint32_t *net, uint32_t *mask)
+{
+    int n, a, b, c, d, slash = 32, len = 0;
+
+    if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
+         sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
+        isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) &&
+        slash >= 0 && slash < 33) {
+        len = n;
+        *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | d;
+        *mask = slash ? 0xffffffffU << (32 - slash) : 0;
+    }
+
+    return len;
+}
+
+static int set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
+{
+    int throttle = 0;
+    struct vec vec, val;
+    uint32_t net, mask;
+    char mult;
+    double v;
+
+    while ((spec = next_option(spec, &vec, &val)) != NULL) {
+        mult = ',';
+        if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0 ||
+            (lowercase(&mult) != 'k' && lowercase(&mult) != 'm' && mult != ',')) {
+            continue;
+        }
+        v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576 : 1;
+        if (vec.len == 1 && vec.ptr[0] == '*') {
+            throttle = (int) v;
+        } else if (parse_net(vec.ptr, &net, &mask) > 0) {
+            if ((remote_ip & mask) == net) {
+                throttle = (int) v;
+            }
+        } else if (match_prefix(vec.ptr, (int)vec.len, uri) > 0) {
+            throttle = (int) v;
+        }
+    }
+
+    return throttle;
+}
+
+static uint32_t get_remote_ip(const struct mg_connection *conn)
+{
+    return ntohl(* (uint32_t *) &conn->client.rsa.sin.sin_addr);
+}
+
+int mg_upload(struct mg_connection *conn, const char *destination_dir)
+{
+    const char *content_type_header, *boundary_start;
+    char buf[MG_BUF_LEN], path[PATH_MAX], fname[1024], boundary[100], *s;
+    FILE *fp;
+    int bl, n, i, j, headers_len, boundary_len, eof,
+        len = 0, num_uploaded_files = 0;
+
+    /* Request looks like this:
+
+       POST /upload HTTP/1.1
+       Host: 127.0.0.1:8080
+       Content-Length: 244894
+       Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryRVr
+
+       ------WebKitFormBoundaryRVr
+       Content-Disposition: form-data; name="file"; filename="accum.png"
+       Content-Type: image/png
+
+        <89>PNG
+        <PNG DATA>
+       ------WebKitFormBoundaryRVr */
+
+    /* Extract boundary string from the Content-Type header */
+    if ((content_type_header = mg_get_header(conn, "Content-Type")) == NULL ||
+        (boundary_start = mg_strcasestr(content_type_header,
+                                        "boundary=")) == NULL ||
+        (sscanf(boundary_start, "boundary=\"%99[^\"]\"", boundary) == 0 &&
+         sscanf(boundary_start, "boundary=%99s", boundary) == 0) ||
+        boundary[0] == '\0') {
+        return num_uploaded_files;
+    }
+
+    boundary_len = (int)strlen(boundary);
+    bl = boundary_len + 4;  /* \r\n--<boundary> */
+    for (;;) {
+        /* Pull in headers */
+        assert(len >= 0 && len <= (int) sizeof(buf));
+        while ((n = mg_read(conn, buf + len, sizeof(buf) - len)) > 0) {
+            len += n;
+        }
+        if ((headers_len = get_request_len(buf, len)) <= 0) {
+            break;
+        }
+
+        /* Fetch file name. */
+        fname[0] = '\0';
+        for (i = j = 0; i < headers_len; i++) {
+            if (buf[i] == '\r' && buf[i + 1] == '\n') {
+                buf[i] = buf[i + 1] = '\0';
+                /* TODO(lsm): don't expect filename to be the 3rd field,
+                   parse the header properly instead. */
+                IGNORE_UNUSED_RESULT(sscanf(&buf[j], "Content-Disposition: %*s %*s filename=\"%1023[^\"]",
+                                            fname));
+                j = i + 2;
+            }
+        }
+
+        /* Give up if the headers are not what we expect */
+        if (fname[0] == '\0') {
+            break;
+        }
+
+        /* Move data to the beginning of the buffer */
+        assert(len >= headers_len);
+        memmove(buf, &buf[headers_len], len - headers_len);
+        len -= headers_len;
+
+        /* We open the file with exclusive lock held. This guarantee us
+           there is no other thread can save into the same file
+           simultaneously. */
+        fp = NULL;
+        /* Construct destination file name. Do not allow paths to have
+           slashes. */
+        if ((s = strrchr(fname, '/')) == NULL &&
+            (s = strrchr(fname, '\\')) == NULL) {
+            s = fname;
+        }
+
+        /* Open file in binary mode. TODO: set an exclusive lock. */
+        snprintf(path, sizeof(path), "%s/%s", destination_dir, s);
+        if ((fp = fopen(path, "wb")) == NULL) {
+            break;
+        }
+
+        /* Read POST data, write into file until boundary is found. */
+        eof = n = 0;
+        do {
+            len += n;
+            for (i = 0; i < len - bl; i++) {
+                if (!memcmp(&buf[i], "\r\n--", 4) &&
+                    !memcmp(&buf[i + 4], boundary, boundary_len)) {
+                    /* Found boundary, that's the end of file data. */
+                    fwrite(buf, 1, i, fp);
+                    eof = 1;
+                    memmove(buf, &buf[i + bl], len - (i + bl));
+                    len -= i + bl;
+                    break;
+                }
+            }
+            if (!eof && len > bl) {
+                fwrite(buf, 1, len - bl, fp);
+                memmove(buf, &buf[len - bl], bl);
+                len = bl;
+            }
+        } while (!eof && (n = mg_read(conn, buf + len, sizeof(buf) - len)) > 0);
+        fclose(fp);
+        if (eof) {
+            num_uploaded_files++;
+            if (conn->ctx->callbacks.upload != NULL) {
+                conn->ctx->callbacks.upload(conn, path);
+            }
+        }
+    }
+
+    return num_uploaded_files;
+}
+
+static int is_put_or_delete_request(const struct mg_connection *conn)
+{
+    const char *s = conn->request_info.request_method;
+    return s != NULL && (!strcmp(s, "PUT") ||
+                         !strcmp(s, "DELETE") ||
+                         !strcmp(s, "MKCOL"));
+}
+
+static int get_first_ssl_listener_index(const struct mg_context *ctx)
+{
+    int i, idx = -1;
+    for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
+        idx = ctx->listening_sockets[i].is_ssl ? i : -1;
+    }
+    return idx;
+}
+
+static void redirect_to_https_port(struct mg_connection *conn, int ssl_index)
+{
+    char host[1025];
+    const char *host_header;
+    size_t hostlen;
+
+    host_header = mg_get_header(conn, "Host");
+    hostlen = sizeof(host);
+    if (host_header != NULL) {
+        char *pos;
+
+        strncpy(host, host_header, hostlen);
+        host[hostlen - 1] = '\0';
+        pos = strchr(host, ':');
+        if (pos != NULL) {
+            *pos = '\0';
+        }
+    } else {
+        /* Cannot get host from the Host: header.
+           Fallback to our IP address. */
+        sockaddr_to_string(host, hostlen, &conn->client.lsa);
+    }
+
+    mg_printf(conn, "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s\r\n\r\n",
+              host, (int) ntohs(conn->ctx->listening_sockets[ssl_index].
+                                lsa.sin.sin_port), conn->request_info.uri);
+}
+
+
+void mg_set_request_handler(struct mg_context *ctx, const char *uri, mg_request_handler handler, void *cbdata)
+{
+    struct mg_request_handler_info *tmp_rh, *lastref = 0;
+    size_t urilen = strlen(uri);
+
+    /* first see it the uri exists */
+    for (tmp_rh = ctx->request_handlers;
+         tmp_rh != NULL && strcmp(uri, tmp_rh->uri);
+         lastref = tmp_rh, tmp_rh = tmp_rh->next) {
+        /* first try for an exact match */
+        if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri,uri)) {
+            /* already there... */
+
+            if (handler != NULL) {
+                /* change this entry */
+                tmp_rh->handler = handler;
+                tmp_rh->cbdata = cbdata;
+            } else {
+                /* remove this entry */
+                if (lastref != NULL)
+                    lastref->next = tmp_rh->next;
+                else
+                    ctx->request_handlers = tmp_rh->next;
+                free(tmp_rh->uri);
+                free(tmp_rh);
+            }
+            return;
+        }
+
+        /* next try for a partial match, we will accept uri/something */
+        if (tmp_rh->uri_len < urilen
+            && uri[tmp_rh->uri_len] == '/'
+            && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
+            /* if there is a partical match this new entry MUST go BEFORE
+               the current position otherwise it will never be matched. */
+            break;
+        }
+
+    }
+
+    if (handler == NULL) {
+        /* no handler to set, this was a remove request */
+        return;
+    }
+
+    tmp_rh = (struct mg_request_handler_info *)malloc(sizeof(struct mg_request_handler_info));
+    if (tmp_rh == NULL) {
+        mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
+        return;
+    }
+    tmp_rh->uri = mg_strdup(uri);
+    tmp_rh->uri_len = strlen(uri);
+    tmp_rh->handler = handler;
+    tmp_rh->cbdata = cbdata;
+
+    if (lastref == NULL) {
+        tmp_rh->next = ctx->request_handlers;
+        ctx->request_handlers = tmp_rh;
+    } else {
+        tmp_rh->next = lastref->next;
+        lastref->next = tmp_rh;
+    }
+
+}
+
+static int use_request_handler(struct mg_connection *conn)
+{
+    struct mg_request_info *request_info = mg_get_request_info(conn);
+    const char *uri = request_info->uri;
+    size_t urilen = strlen(uri);
+    struct mg_request_handler_info *tmp_rh = conn->ctx->request_handlers;
+
+    for (; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
+
+        /* first try for an exact match */
+        if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri,uri)) {
+            return tmp_rh->handler(conn, tmp_rh->cbdata);
+        }
+
+        /* next try for a partial match */
+        /* we will accept uri/something */
+        if (tmp_rh->uri_len < urilen
+            && uri[tmp_rh->uri_len] == '/'
+            && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
+
+            return tmp_rh->handler(conn, tmp_rh->cbdata);
+        }
+

+        /* try for pattern match */

+        if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {

+           return tmp_rh->handler(conn, tmp_rh->cbdata);

+        }
+
+    }
+
+    return 0; /* none found */
+}
+
+/* This is the heart of the Civetweb's logic.
+   This function is called when the request is read, parsed and validated,
+   and Civetweb must decide what action to take: serve a file, or
+   a directory, or call embedded function, etcetera. */
+static void handle_request(struct mg_connection *conn)
+{
+    struct mg_request_info *ri = &conn->request_info;
+    char path[PATH_MAX];
+    int uri_len, ssl_index, is_script_resource;
+    struct file file = STRUCT_FILE_INITIALIZER;
+    char date[64];

+    time_t curtime = time(NULL);
+
+    if ((conn->request_info.query_string = strchr(ri->uri, '?')) != NULL) {
+        * ((char *) conn->request_info.query_string++) = '\0';
+    }
+    uri_len = (int) strlen(ri->uri);
+    mg_url_decode(ri->uri, uri_len, (char *) ri->uri, uri_len + 1, 0);
+    remove_double_dots_and_double_slashes((char *) ri->uri);
+    path[0] = '\0';
+    convert_uri_to_file_name(conn, path, sizeof(path), &file, &is_script_resource);
+    conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
+                                  get_remote_ip(conn), ri->uri);
+
+    DEBUG_TRACE(("%s", ri->uri));
+    /* Perform redirect and auth checks before calling begin_request() handler.
+       Otherwise, begin_request() would need to perform auth checks and
+       redirects. */
+    if (!conn->client.is_ssl && conn->client.ssl_redir &&
+        (ssl_index = get_first_ssl_listener_index(conn->ctx)) > -1) {
+        redirect_to_https_port(conn, ssl_index);
+    } else if (!is_script_resource && !is_put_or_delete_request(conn) &&
+               !check_authorization(conn, path)) {
+        send_authorization_request(conn);
+    } else if (conn->ctx->callbacks.begin_request != NULL &&
+               conn->ctx->callbacks.begin_request(conn)) {
+        /* Do nothing, callback has served the request */
+#if defined(USE_WEBSOCKET)
+    } else if (is_websocket_request(conn)) {
+        handle_websocket_request(conn, path, is_script_resource);
+#endif
+    } else if (conn->ctx->request_handlers != NULL &&
+               use_request_handler(conn)) {
+        /* Do nothing, callback has served the request */
+    } else if (!is_script_resource && !strcmp(ri->request_method, "OPTIONS")) {
+        send_options(conn);
+    } else if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
+        send_http_error(conn, 404, "Not Found", "Not Found");
+    } else if (!is_script_resource && is_put_or_delete_request(conn) &&
+               (is_authorized_for_put(conn) != 1)) {
+        send_authorization_request(conn);
+    } else if (!is_script_resource && !strcmp(ri->request_method, "PUT")) {
+        put_file(conn, path);
+    } else if (!is_script_resource && !strcmp(ri->request_method, "MKCOL")) {
+        mkcol(conn, path);
+    } else if (!is_script_resource && !strcmp(ri->request_method, "DELETE")) {
+        struct de de;
+        memset(&de.file, 0, sizeof(de.file));
+        if(!mg_stat(conn, path, &de.file)) {
+            send_http_error(conn, 404, "Not Found", "%s", "File not found");
+        } else {
+            if(de.file.modification_time) {
+                if(de.file.is_directory) {
+                    remove_directory(conn, path);
+                    send_http_error(conn, 204, "No Content", "%s", "");
+                } else if (mg_remove(path) == 0) {
+                    send_http_error(conn, 204, "No Content", "%s", "");
+                } else {
+                    send_http_error(conn, 423, "Locked", "remove(%s): %s", path,
+                                    strerror(ERRNO));
+                }
+            } else {
+                send_http_error(conn, 500, http_500_error, "remove(%s): %s", path,
+                                strerror(ERRNO));
+            }
+        }
+    } else if ((file.membuf == NULL && file.modification_time == (time_t) 0) ||
+               must_hide_file(conn, path)) {
+        send_http_error(conn, 404, "Not Found", "%s", "File not found");
+    } else if (file.is_directory && ri->uri[uri_len - 1] != '/') {
+        gmt_time_string(date, sizeof(date), &curtime);
+        mg_printf(conn, "HTTP/1.1 301 Moved Permanently\r\n"
+                        "Location: %s/\r\n"
+                        "Date: %s\r\n"
+                        "Content-Length: 0\r\n"
+                        "Connection: %s\r\n\r\n",
+                        ri->uri, date, suggest_connection_header(conn));
+    } else if (!is_script_resource && !strcmp(ri->request_method, "PROPFIND")) {
+        handle_propfind(conn, path, &file);
+    } else if (file.is_directory &&
+               !substitute_index_file(conn, path, sizeof(path), &file)) {
+        if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")) {
+            handle_directory_request(conn, path);
+        } else {
+            send_http_error(conn, 403, "Directory Listing Denied",
+                            "Directory listing denied");
+        }
+#ifdef USE_LUA
+    } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
+                            (int)strlen(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
+                            path) > 0) {
+        /* Lua server page: an SSI like page containing mostly plain html code plus some tags with server generated contents. */
+        handle_lsp_request(conn, path, &file, NULL);
+    } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
+                            (int)strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
+                            path) > 0) {
+        /* Lua in-server module script: a CGI like script used to generate the entire reply. */
+        mg_exec_lua_script(conn, path, NULL);
+#endif
+#if !defined(NO_CGI)
+    } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
+                            (int)strlen(conn->ctx->config[CGI_EXTENSIONS]),
+                            path) > 0) {
+        /* TODO: check unsupported methods -> 501
+        if (strcmp(ri->request_method, "POST") &&
+            strcmp(ri->request_method, "HEAD") &&
+            strcmp(ri->request_method, "GET")) {
+            send_http_error(conn, 501, "Not Implemented",
+                            "Method %s is not implemented", ri->request_method);
+        } else {
+            handle_cgi_request(conn, path);
+        } */
+        handle_cgi_request(conn, path);
+#endif /* !NO_CGI */
+    } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
+                            (int)strlen(conn->ctx->config[SSI_EXTENSIONS]),
+                            path) > 0) {
+        handle_ssi_file_request(conn, path);
+    } else if (is_not_modified(conn, &file)) {
+        send_http_error(conn, 304, "Not Modified", "%s", "");
+    } else {
+        handle_file_request(conn, path, &file);
+    }
+}
+
+static void close_all_listening_sockets(struct mg_context *ctx)
+{
+    int i;
+    for (i = 0; i < ctx->num_listening_sockets; i++) {
+        closesocket(ctx->listening_sockets[i].sock);
+    }
+    free(ctx->listening_sockets);
+}
+
+static int is_valid_port(unsigned int port)
+{
+    return port < 0xffff;
+}
+
+/* Valid listening port specification is: [ip_address:]port[s]
+   Examples: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
+   TODO(lsm): add parsing of the IPv6 address */
+static int parse_port_string(const struct vec *vec, struct socket *so)
+{
+    unsigned int a, b, c, d, ch, len, port;
+#if defined(USE_IPV6)
+    char buf[100];
+#endif
+
+    /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
+       Also, all-zeroes in the socket address means binding to all addresses
+       for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
+    memset(so, 0, sizeof(*so));
+    so->lsa.sin.sin_family = AF_INET;
+
+    if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) {
+        /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
+        so->lsa.sin.sin_addr.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
+        so->lsa.sin.sin_port = htons((uint16_t) port);
+#if defined(USE_IPV6)
+
+    } else if (sscanf(vec->ptr, "[%49[^]]]:%d%n", buf, &port, &len) == 2 &&
+               inet_pton(AF_INET6, buf, &so->lsa.sin6.sin6_addr)) {
+        /* IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080 */
+        so->lsa.sin6.sin6_family = AF_INET6;
+        so->lsa.sin6.sin6_port = htons((uint16_t) port);
+#endif
+    } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
+        /* If only port is specified, bind to IPv4, INADDR_ANY */
+        so->lsa.sin.sin_port = htons((uint16_t) port);
+    } else {
+        port = len = 0;   /* Parsing failure. Make port invalid. */
+    }
+
+    ch = vec->ptr[len];  /* Next character after the port number */
+    so->is_ssl = ch == 's';
+    so->ssl_redir = ch == 'r';
+
+    /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
+    return is_valid_port(port) &&
+           (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
+}
+
+static int set_ports_option(struct mg_context *ctx)
+{
+    const char *list = ctx->config[LISTENING_PORTS];
+    int on = 1, success = 1;
+#if defined(USE_IPV6)
+    int off = 0;
+#endif
+    struct vec vec;
+    struct socket so, *ptr;
+
+    in_port_t *portPtr;
+    struct sockaddr_in sin;
+    socklen_t len;
+
+    memset(&sin, 0, sizeof(sin));
+    len = sizeof(sin);
+
+    while (success && (list = next_option(list, &vec, NULL)) != NULL) {
+        if (!parse_port_string(&vec, &so)) {
+            mg_cry(fc(ctx), "%s: %.*s: invalid port spec. Expecting list of: %s",
+                   __func__, (int) vec.len, vec.ptr, "[IP_ADDRESS:]PORT[s|r]");
+            success = 0;
+        } else if (so.is_ssl && ctx->ssl_ctx == NULL) {
+            mg_cry(fc(ctx), "Cannot add SSL socket, is -ssl_certificate option set?");
+            success = 0;
+        } else if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6)) ==
+                   INVALID_SOCKET ||
+                   /* On Windows, SO_REUSEADDR is recommended only for
+                      broadcast UDP sockets */
+                   setsockopt(so.sock, SOL_SOCKET, SO_REUSEADDR,
+                              (void *) &on, sizeof(on)) != 0 ||
+#if defined(USE_IPV6)
+                   (so.lsa.sa.sa_family == AF_INET6 &&
+                    setsockopt(so.sock, IPPROTO_IPV6, IPV6_V6ONLY, (void *) &off,
+                               sizeof(off)) != 0) ||
+#endif
+                   bind(so.sock, &so.lsa.sa, so.lsa.sa.sa_family == AF_INET ?
+                        sizeof(so.lsa.sin) : sizeof(so.lsa)) != 0 ||
+                   listen(so.sock, SOMAXCONN) != 0 ||
+                   getsockname(so.sock, (struct sockaddr *)&sin, &len) != 0) {
+            mg_cry(fc(ctx), "%s: cannot bind to %.*s: %d (%s)", __func__,
+                   (int) vec.len, vec.ptr, ERRNO, strerror(errno));
+            if (so.sock != INVALID_SOCKET) {
+                closesocket(so.sock);
+            }
+            success = 0;
+        } else if ((ptr = (struct socket *) realloc(ctx->listening_sockets,
+                          (ctx->num_listening_sockets + 1) *
+                          sizeof(ctx->listening_sockets[0]))) == NULL) {
+            closesocket(so.sock);
+            success = 0;
+        } else if ((portPtr = (in_port_t*) realloc(ctx->listening_ports,
+                          (ctx->num_listening_sockets + 1) *
+                          sizeof(ctx->listening_ports[0]))) == NULL) {
+            closesocket(so.sock);
+            success = 0;
+        }
+        else {
+            set_close_on_exec(so.sock, fc(ctx));
+            ctx->listening_sockets = ptr;
+            ctx->listening_sockets[ctx->num_listening_sockets] = so;
+            ctx->listening_ports = portPtr;
+            ctx->listening_ports[ctx->num_listening_sockets] = ntohs(sin.sin_port);
+            ctx->num_listening_sockets++;
+        }
+    }
+
+    if (!success) {
+        close_all_listening_sockets(ctx);
+    }
+
+    return success;
+}
+
+static void log_header(const struct mg_connection *conn, const char *header,
+                       FILE *fp)
+{
+    const char *header_value;
+
+    if ((header_value = mg_get_header(conn, header)) == NULL) {
+        (void) fprintf(fp, "%s", " -");
+    } else {
+        (void) fprintf(fp, " \"%s\"", header_value);
+    }
+}
+
+static void log_access(const struct mg_connection *conn)
+{
+    const struct mg_request_info *ri;
+    FILE *fp;
+    char date[64], src_addr[IP_ADDR_STR_LEN];
+    struct tm *tm;
+
+    fp = conn->ctx->config[ACCESS_LOG_FILE] == NULL ?  NULL :
+         fopen(conn->ctx->config[ACCESS_LOG_FILE], "a+");
+
+    if (fp == NULL)
+        return;
+
+    tm = localtime(&conn->birth_time);
+    if (tm != NULL) {
+        strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
+    } else {
+        strncpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
+        date[sizeof(date) - 1] = '\0';
+    }
+
+    ri = &conn->request_info;
+    flockfile(fp);
+
+    sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
+    fprintf(fp, "%s - %s [%s] \"%s %s HTTP/%s\" %d %" INT64_FMT,
+            src_addr, ri->remote_user == NULL ? "-" : ri->remote_user, date,
+            ri->request_method ? ri->request_method : "-",
+            ri->uri ? ri->uri : "-", ri->http_version,
+            conn->status_code, conn->num_bytes_sent);
+    log_header(conn, "Referer", fp);
+    log_header(conn, "User-Agent", fp);
+    fputc('\n', fp);
+    fflush(fp);
+
+    funlockfile(fp);
+    fclose(fp);
+}
+
+/* Verify given socket address against the ACL.
+   Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed. */
+static int check_acl(struct mg_context *ctx, uint32_t remote_ip)
+{
+    int allowed, flag;
+    uint32_t net, mask;
+    struct vec vec;
+    const char *list = ctx->config[ACCESS_CONTROL_LIST];
+
+    /* If any ACL is set, deny by default */
+    allowed = list == NULL ? '+' : '-';
+
+    while ((list = next_option(list, &vec, NULL)) != NULL) {
+        flag = vec.ptr[0];
+        if ((flag != '+' && flag != '-') ||
+            parse_net(&vec.ptr[1], &net, &mask) == 0) {
+            mg_cry(fc(ctx), "%s: subnet must be [+|-]x.x.x.x[/x]", __func__);
+            return -1;
+        }
+
+        if (net == (remote_ip & mask)) {
+            allowed = flag;
+        }
+    }
+
+    return allowed == '+';
+}
+
+#if !defined(_WIN32)
+static int set_uid_option(struct mg_context *ctx)
+{
+    struct passwd *pw;
+    const char *uid = ctx->config[RUN_AS_USER];
+    int success = 0;
+
+    if (uid == NULL) {
+        success = 1;
+    } else {
+        if ((pw = getpwnam(uid)) == NULL) {
+            mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
+        } else if (setgid(pw->pw_gid) == -1) {
+            mg_cry(fc(ctx), "%s: setgid(%s): %s", __func__, uid, strerror(errno));
+        } else if (setuid(pw->pw_uid) == -1) {
+            mg_cry(fc(ctx), "%s: setuid(%s): %s", __func__, uid, strerror(errno));
+        } else {
+            success = 1;
+        }
+    }
+
+    return success;
+}
+#endif /* !_WIN32 */
+
+#if !defined(NO_SSL)
+static pthread_mutex_t *ssl_mutexes;
+
+static int sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *))
+{
+    return (conn->ssl = SSL_new(s)) != NULL &&
+           SSL_set_fd(conn->ssl, conn->client.sock) == 1 &&
+           func(conn->ssl) == 1;
+}
+
+/* Return OpenSSL error message */
+static const char *ssl_error(void)
+{
+    unsigned long err;
+    err = ERR_get_error();
+    return err == 0 ? "" : ERR_error_string(err, NULL);
+}
+
+static void ssl_locking_callback(int mode, int mutex_num, const char *file,
+                                 int line)
+{
+    (void) line;
+    (void) file;
+
+    if (mode & 1) {  /* 1 is CRYPTO_LOCK */
+        (void) pthread_mutex_lock(&ssl_mutexes[mutex_num]);
+    } else {
+        (void) pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
+    }
+}
+
+static unsigned long ssl_id_callback(void)
+{
+    return (unsigned long) pthread_self();
+}
+
+#if !defined(NO_SSL_DL)
+static void *load_dll(struct mg_context *ctx, const char *dll_name,
+                      struct ssl_func *sw)
+{
+    union {
+        void *p;
+        void (*fp)(void);
+    } u;
+    void  *dll_handle;
+    struct ssl_func *fp;
+
+    if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
+        mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
+        return NULL;
+    }
+
+    for (fp = sw; fp->name != NULL; fp++) {
+#ifdef _WIN32
+        /* GetProcAddress() returns pointer to function */
+        u.fp = (void (*)(void)) dlsym(dll_handle, fp->name);
+#else
+        /* dlsym() on UNIX returns void *. ISO C forbids casts of data
+           pointers to function pointers. We need to use a union to make a
+           cast. */
+        u.p = dlsym(dll_handle, fp->name);
+#endif /* _WIN32 */
+        if (u.fp == NULL) {
+            mg_cry(fc(ctx), "%s: %s: cannot find %s", __func__, dll_name, fp->name);
+            dlclose(dll_handle);
+            return NULL;
+        } else {
+            fp->ptr = u.fp;
+        }
+    }
+
+    return dll_handle;
+}
+#endif /* NO_SSL_DL */
+
+/* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
+static int set_ssl_option(struct mg_context *ctx)
+{
+    int i, size;
+    const char *pem;
+
+    /* If PEM file is not specified and the init_ssl callback
+       is not specified, skip SSL initialization. */
+    if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL &&
+        ctx->callbacks.init_ssl == NULL) {
+        return 1;
+    }
+
+#if !defined(NO_SSL_DL)
+    ctx->ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
+    ctx->cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
+    if (!ctx->ssllib_dll_handle || !ctx->cryptolib_dll_handle) {
+        return 0;
+    }
+#endif /* NO_SSL_DL */
+
+    /* Initialize SSL library */
+    SSL_library_init();
+    SSL_load_error_strings();
+
+    if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
+        mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
+        return 0;
+    }
+
+    /* If user callback returned non-NULL, that means that user callback has
+       set up certificate itself. In this case, skip sertificate setting. */
+    if ((ctx->callbacks.init_ssl == NULL ||
+         !ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data)) &&
+        (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0 ||
+         SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0)) {
+        mg_cry(fc(ctx), "%s: cannot open %s: %s", __func__, pem, ssl_error());
+        return 0;
+    }
+
+    if (pem != NULL) {
+        (void) SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
+    }
+
+    /* Initialize locking callbacks, needed for thread safety.
+       http://www.openssl.org/support/faq.html#PROG1 */
+    size = sizeof(pthread_mutex_t) * CRYPTO_num_locks();
+    if ((ssl_mutexes = (pthread_mutex_t *) malloc((size_t)size)) == NULL) {
+        mg_cry(fc(ctx), "%s: cannot allocate mutexes: %s", __func__, ssl_error());
+        return 0;
+    }
+
+    for (i = 0; i < CRYPTO_num_locks(); i++) {
+        pthread_mutex_init(&ssl_mutexes[i], NULL);
+    }
+
+    CRYPTO_set_locking_callback(&ssl_locking_callback);
+    CRYPTO_set_id_callback(&ssl_id_callback);
+
+    return 1;
+}
+
+static void uninitialize_ssl(struct mg_context *ctx)
+{
+    int i;
+    if (ctx->ssl_ctx != NULL) {
+        CRYPTO_set_locking_callback(NULL);
+        for (i = 0; i < CRYPTO_num_locks(); i++) {
+            pthread_mutex_destroy(&ssl_mutexes[i]);
+        }
+        CRYPTO_set_locking_callback(NULL);
+        CRYPTO_set_id_callback(NULL);
+    }
+}
+#endif /* !NO_SSL */
+
+static int set_gpass_option(struct mg_context *ctx)
+{
+    struct file file = STRUCT_FILE_INITIALIZER;
+    const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
+    if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
+        mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
+        return 0;
+    }
+    return 1;
+}
+
+static int set_acl_option(struct mg_context *ctx)
+{
+    return check_acl(ctx, (uint32_t) 0x7f000001UL) != -1;
+}
+
+static void reset_per_request_attributes(struct mg_connection *conn)
+{
+    conn->path_info = NULL;
+    conn->num_bytes_sent = conn->consumed_content = 0;
+    conn->status_code = -1;
+    conn->must_close = conn->request_len = conn->throttle = 0;
+}
+
+static void close_socket_gracefully(struct mg_connection *conn)
+{
+#if defined(_WIN32)
+    char buf[MG_BUF_LEN];
+    int n;
+#endif
+    struct linger linger;
+
+    /* Set linger option to avoid socket hanging out after close. This prevent
+       ephemeral port exhaust problem under high QPS. */
+    linger.l_onoff = 1;
+    linger.l_linger = 1;
+    if (setsockopt(conn->client.sock, SOL_SOCKET, SO_LINGER,
+                   (char *) &linger, sizeof(linger)) != 0) {
+        mg_cry(conn, "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
+               __func__, strerror(ERRNO));
+    }
+
+    /* Send FIN to the client */
+    shutdown(conn->client.sock, SHUT_WR);
+    set_non_blocking_mode(conn->client.sock);
+
+#if defined(_WIN32)
+    /* Read and discard pending incoming data. If we do not do that and close
+       the socket, the data in the send buffer may be discarded. This
+       behaviour is seen on Windows, when client keeps sending data
+       when server decides to close the connection; then when client
+       does recv() it gets no data back. */
+    do {
+        n = pull(NULL, conn, buf, sizeof(buf));
+    } while (n > 0);
+#endif
+
+    /* Now we know that our FIN is ACK-ed, safe to close */
+    closesocket(conn->client.sock);
+}
+
+static void close_connection(struct mg_connection *conn)
+{
+#if defined(USE_LUA) && defined(USE_WEBSOCKET)
+    if (conn->lua_websocket_state) {
+        lua_websocket_close(conn);
+    }
+#endif
+
+    /* call the connection_close callback if assigned */
+    if (conn->ctx->callbacks.connection_close != NULL)
+        conn->ctx->callbacks.connection_close(conn);
+
+    mg_lock(conn);
+
+    conn->must_close = 1;
+
+#ifndef NO_SSL
+    if (conn->ssl != NULL) {
+        /* Run SSL_shutdown twice to ensure completly close SSL connection */
+        SSL_shutdown(conn->ssl);
+        SSL_free(conn->ssl);
+        conn->ssl = NULL;
+    }
+#endif
+    if (conn->client.sock != INVALID_SOCKET) {
+        close_socket_gracefully(conn);
+        conn->client.sock = INVALID_SOCKET;
+    }
+
+    mg_unlock(conn);
+}
+
+void mg_close_connection(struct mg_connection *conn)
+{
+#ifndef NO_SSL
+    if (conn->client_ssl_ctx != NULL) {
+        SSL_CTX_free((SSL_CTX *) conn->client_ssl_ctx);
+    }
+#endif
+    close_connection(conn);
+    (void) pthread_mutex_destroy(&conn->mutex);
+    free(conn);
+}
+
+struct mg_connection *mg_connect(const char *host, int port, int use_ssl,
+                                 char *ebuf, size_t ebuf_len);
+
+struct mg_connection *mg_connect(const char *host, int port, int use_ssl,
+                                 char *ebuf, size_t ebuf_len)
+{
+    static struct mg_context fake_ctx;
+    struct mg_connection *conn = NULL;
+    SOCKET sock;
+
+    if ((sock = conn2(&fake_ctx, host, port, use_ssl, ebuf,
+                      ebuf_len)) == INVALID_SOCKET) {
+    } else if ((conn = (struct mg_connection *)
+                       calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
+        snprintf(ebuf, ebuf_len, "calloc(): %s", strerror(ERRNO));
+        closesocket(sock);
+#ifndef NO_SSL
+    } else if (use_ssl && (conn->client_ssl_ctx =
+                               SSL_CTX_new(SSLv23_client_method())) == NULL) {
+        snprintf(ebuf, ebuf_len, "SSL_CTX_new error");
+        closesocket(sock);
+        free(conn);
+        conn = NULL;
+#endif /* NO_SSL */
+    } else {
+        socklen_t len = sizeof(struct sockaddr);
+        conn->buf_size = MAX_REQUEST_SIZE;
+        conn->buf = (char *) (conn + 1);
+        conn->ctx = &fake_ctx;
+        conn->client.sock = sock;
+        if (getsockname(sock, &conn->client.rsa.sa, &len) != 0) {
+            mg_cry(conn, "%s: getsockname() failed: %s",
+                   __func__, strerror(ERRNO));
+        }
+        conn->client.is_ssl = use_ssl;
+        (void) pthread_mutex_init(&conn->mutex, NULL);
+#ifndef NO_SSL
+        if (use_ssl) {
+            /* SSL_CTX_set_verify call is needed to switch off server
+               certificate checking, which is off by default in OpenSSL and on
+               in yaSSL. */
+            SSL_CTX_set_verify(conn->client_ssl_ctx, 0, 0);
+            sslize(conn, conn->client_ssl_ctx, SSL_connect);
+        }
+#endif
+    }
+
+    return conn;
+}
+
+static int is_valid_uri(const char *uri)
+{
+    /* Conform to
+       http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
+       URI can be an asterisk (*) or should start with slash. */
+    return uri[0] == '/' || (uri[0] == '*' && uri[1] == '\0');
+}
+
+static int getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len)
+{
+    const char *cl;
+
+    ebuf[0] = '\0';
+    reset_per_request_attributes(conn);
+    conn->request_len = read_request(NULL, conn, conn->buf, conn->buf_size,
+                                     &conn->data_len);
+    assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
+
+    if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
+        snprintf(ebuf, ebuf_len, "%s", "Request Too Large");
+    } else if (conn->request_len <= 0) {
+        snprintf(ebuf, ebuf_len, "%s", "Client closed connection");
+    } else if (parse_http_message(conn->buf, conn->buf_size,
+                                  &conn->request_info) <= 0) {
+        snprintf(ebuf, ebuf_len, "Bad request: [%.*s]", conn->data_len, conn->buf);
+    } else {
+        /* Request is valid */
+        if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
+            conn->content_len = strtoll(cl, NULL, 10);
+        } else if (!mg_strcasecmp(conn->request_info.request_method, "POST") ||
+                   !mg_strcasecmp(conn->request_info.request_method, "PUT")) {
+            conn->content_len = -1;
+        } else {
+            conn->content_len = 0;
+        }
+        conn->birth_time = time(NULL);
+    }
+    return ebuf[0] == '\0';
+}
+
+struct mg_connection *mg_download(const char *host, int port, int use_ssl,
+                                  char *ebuf, size_t ebuf_len,
+                                  const char *fmt, ...)
+{
+    struct mg_connection *conn;
+    va_list ap;
+
+    va_start(ap, fmt);
+    ebuf[0] = '\0';
+    if ((conn = mg_connect(host, port, use_ssl, ebuf, ebuf_len)) == NULL) {
+    } else if (mg_vprintf(conn, fmt, ap) <= 0) {
+        snprintf(ebuf, ebuf_len, "%s", "Error sending request");
+    } else {
+        getreq(conn, ebuf, ebuf_len);
+    }
+    if (ebuf[0] != '\0' && conn != NULL) {
+        mg_close_connection(conn);
+        conn = NULL;
+    }
+    va_end(ap);
+
+    return conn;
+}
+
+static void process_new_connection(struct mg_connection *conn)
+{
+    struct mg_request_info *ri = &conn->request_info;
+    int keep_alive_enabled, keep_alive, discard_len;
+    char ebuf[100];
+
+    keep_alive_enabled = !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
+    keep_alive = 0;
+
+    /* Important: on new connection, reset the receiving buffer. Credit goes
+       to crule42. */
+    conn->data_len = 0;
+    do {
+        if (!getreq(conn, ebuf, sizeof(ebuf))) {
+            send_http_error(conn, 500, "Server Error", "%s", ebuf);
+            conn->must_close = 1;
+        } else if (!is_valid_uri(conn->request_info.uri)) {
+            snprintf(ebuf, sizeof(ebuf), "Invalid URI: [%s]", ri->uri);
+            send_http_error(conn, 400, "Bad Request", "%s", ebuf);
+        } else if (strcmp(ri->http_version, "1.0") &&
+                   strcmp(ri->http_version, "1.1")) {
+            snprintf(ebuf, sizeof(ebuf), "Bad HTTP version: [%s]", ri->http_version);
+            send_http_error(conn, 505, "Bad HTTP version", "%s", ebuf);
+        }
+
+        if (ebuf[0] == '\0') {
+            handle_request(conn);
+            if (conn->ctx->callbacks.end_request != NULL) {
+                conn->ctx->callbacks.end_request(conn, conn->status_code);
+            }
+            log_access(conn);
+        }
+        if (ri->remote_user != NULL) {
+            free((void *) ri->remote_user);
+            /* Important! When having connections with and without auth
+               would cause double free and then crash */
+            ri->remote_user = NULL;
+        }
+
+        /* NOTE(lsm): order is important here. should_keep_alive() call is
+           using parsed request, which will be invalid after memmove's below.
+           Therefore, memorize should_keep_alive() result now for later use
+           in loop exit condition. */
+        keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled &&
+                     conn->content_len >= 0 && should_keep_alive(conn);
+
+        /* Discard all buffered data for this request */
+        discard_len = conn->content_len >= 0 && conn->request_len > 0 &&
+                      conn->request_len + conn->content_len < (int64_t) conn->data_len ?
+                      (int) (conn->request_len + conn->content_len) : conn->data_len;
+        assert(discard_len >= 0);
+        memmove(conn->buf, conn->buf + discard_len, conn->data_len - discard_len);
+        conn->data_len -= discard_len;
+        assert(conn->data_len >= 0);
+        assert(conn->data_len <= conn->buf_size);
+    } while (keep_alive);
+}
+
+/* Worker threads take accepted socket from the queue */
+static int consume_socket(struct mg_context *ctx, struct socket *sp)
+{
+    (void) pthread_mutex_lock(&ctx->mutex);
+    DEBUG_TRACE(("going idle"));
+
+    /* If the queue is empty, wait. We're idle at this point. */
+    while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
+        pthread_cond_wait(&ctx->sq_full, &ctx->mutex);
+    }
+
+    /* If we're stopping, sq_head may be equal to sq_tail. */
+    if (ctx->sq_head > ctx->sq_tail) {
+        /* Copy socket from the queue and increment tail */
+        *sp = ctx->queue[ctx->sq_tail % ARRAY_SIZE(ctx->queue)];
+        ctx->sq_tail++;
+        DEBUG_TRACE(("grabbed socket %d, going busy", sp->sock));
+
+        /* Wrap pointers if needed */
+        while (ctx->sq_tail > (int) ARRAY_SIZE(ctx->queue)) {
+            ctx->sq_tail -= ARRAY_SIZE(ctx->queue);
+            ctx->sq_head -= ARRAY_SIZE(ctx->queue);
+        }
+    }
+
+    (void) pthread_cond_signal(&ctx->sq_empty);
+    (void) pthread_mutex_unlock(&ctx->mutex);
+
+    return !ctx->stop_flag;
+}
+
+static void *worker_thread_run(void *thread_func_param)
+{
+    struct mg_context *ctx = (struct mg_context *) thread_func_param;
+    struct mg_connection *conn;
+    struct mg_workerTLS tls;
+
+    tls.is_master = 0;
+#if defined(_WIN32) && !defined(__SYMBIAN32__)
+    tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
+#endif
+
+    conn = (struct mg_connection *) calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
+    if (conn == NULL) {
+        mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
+    } else {
+        pthread_setspecific(sTlsKey, &tls);
+        conn->buf_size = MAX_REQUEST_SIZE;
+        conn->buf = (char *) (conn + 1);
+        conn->ctx = ctx;
+        conn->request_info.user_data = ctx->user_data;
+        /* Allocate a mutex for this connection to allow communication both
+           within the request handler and from elsewhere in the application */
+        (void) pthread_mutex_init(&conn->mutex, NULL);
+
+        /* Call consume_socket() even when ctx->stop_flag > 0, to let it
+           signal sq_empty condvar to wake up the master waiting in
+           produce_socket() */
+        while (consume_socket(ctx, &conn->client)) {
+            conn->birth_time = time(NULL);
+
+            /* Fill in IP, port info early so even if SSL setup below fails,
+               error handler would have the corresponding info.
+               Thanks to Johannes Winkelmann for the patch.
+               TODO(lsm): Fix IPv6 case */
+            conn->request_info.remote_port = ntohs(conn->client.rsa.sin.sin_port);
+            memcpy(&conn->request_info.remote_ip,
+                   &conn->client.rsa.sin.sin_addr.s_addr, 4);
+            conn->request_info.remote_ip = ntohl(conn->request_info.remote_ip);
+            conn->request_info.is_ssl = conn->client.is_ssl;
+
+            if (!conn->client.is_ssl
+#ifndef NO_SSL
+                || sslize(conn, conn->ctx->ssl_ctx, SSL_accept)
+#endif
+               ) {
+                process_new_connection(conn);
+            }
+
+            close_connection(conn);
+        }
+    }
+
+    /* Signal master that we're done with connection and exiting */
+    (void) pthread_mutex_lock(&ctx->mutex);
+    ctx->num_threads--;
+    (void) pthread_cond_signal(&ctx->cond);
+    assert(ctx->num_threads >= 0);
+    (void) pthread_mutex_unlock(&ctx->mutex);
+
+    pthread_setspecific(sTlsKey, 0);
+#if defined(_WIN32) && !defined(__SYMBIAN32__)
+    CloseHandle(tls.pthread_cond_helper_mutex);
+#endif
+    free(conn);
+
+    DEBUG_TRACE(("exiting"));
+    return NULL;
+}
+
+/* Threads have different return types on Windows and Unix. */
+
+#ifdef _WIN32
+static unsigned __stdcall worker_thread(void *thread_func_param)
+{
+    worker_thread_run(thread_func_param);
+    return 0;
+}
+#else
+static void *worker_thread(void *thread_func_param)
+{
+    worker_thread_run(thread_func_param);
+    return NULL;
+}
+#endif /* _WIN32 */
+
+/* Master thread adds accepted socket to a queue */
+static void produce_socket(struct mg_context *ctx, const struct socket *sp)
+{
+    (void) pthread_mutex_lock(&ctx->mutex);
+
+    /* If the queue is full, wait */
+    while (ctx->stop_flag == 0 &&
+           ctx->sq_head - ctx->sq_tail >= (int) ARRAY_SIZE(ctx->queue)) {
+        (void) pthread_cond_wait(&ctx->sq_empty, &ctx->mutex);
+    }
+
+    if (ctx->sq_head - ctx->sq_tail < (int) ARRAY_SIZE(ctx->queue)) {
+        /* Copy socket to the queue and increment head */
+        ctx->queue[ctx->sq_head % ARRAY_SIZE(ctx->queue)] = *sp;
+        ctx->sq_head++;
+        DEBUG_TRACE(("queued socket %d", sp->sock));
+    }
+
+    (void) pthread_cond_signal(&ctx->sq_full);
+    (void) pthread_mutex_unlock(&ctx->mutex);
+}
+
+static int set_sock_timeout(SOCKET sock, int milliseconds)
+{
+#ifdef _WIN32
+    DWORD t = milliseconds;
+#else
+    struct timeval t;
+    t.tv_sec = milliseconds / 1000;
+    t.tv_usec = (milliseconds * 1000) % 1000000;
+#endif
+    return setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (void *) &t, sizeof(t)) ||
+           setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (void *) &t, sizeof(t));
+}
+
+static void accept_new_connection(const struct socket *listener,
+                                  struct mg_context *ctx)
+{
+    struct socket so;
+    char src_addr[IP_ADDR_STR_LEN];
+    socklen_t len = sizeof(so.rsa);
+    int on = 1;
+
+    if ((so.sock = accept(listener->sock, &so.rsa.sa, &len)) == INVALID_SOCKET) {
+    } else if (!check_acl(ctx, ntohl(* (uint32_t *) &so.rsa.sin.sin_addr))) {
+        sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
+        mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
+        closesocket(so.sock);
+    } else {
+        /* Put so socket structure into the queue */
+        DEBUG_TRACE(("Accepted socket %d", (int) so.sock));
+        set_close_on_exec(so.sock, fc(ctx));
+        so.is_ssl = listener->is_ssl;
+        so.ssl_redir = listener->ssl_redir;
+        if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
+            mg_cry(fc(ctx), "%s: getsockname() failed: %s",
+                   __func__, strerror(ERRNO));
+        }
+        /* Set TCP keep-alive. This is needed because if HTTP-level keep-alive
+           is enabled, and client resets the connection, server won't get
+           TCP FIN or RST and will keep the connection open forever. With TCP
+           keep-alive, next keep-alive handshake will figure out that the
+           client is down and will close the server end.
+           Thanks to Igor Klopov who suggested the patch. */
+        if (setsockopt(so.sock, SOL_SOCKET, SO_KEEPALIVE, (void *) &on,
+                       sizeof(on)) != 0) {
+            mg_cry(fc(ctx),
+                   "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
+                   __func__, strerror(ERRNO));
+        }
+        set_sock_timeout(so.sock, atoi(ctx->config[REQUEST_TIMEOUT]));
+        produce_socket(ctx, &so);
+    }
+}
+
+static void master_thread_run(void *thread_func_param)
+{
+    struct mg_context *ctx = (struct mg_context *) thread_func_param;
+    struct mg_workerTLS tls;
+    struct pollfd *pfd;
+    int i;
+    int workerthreadcount;
+
+    /* Increase priority of the master thread */
+#if defined(_WIN32)
+    SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
+#elif defined(USE_MASTER_THREAD_PRIORITY)
+    int min_prio = sched_get_priority_min(SCHED_RR);
+    int max_prio = sched_get_priority_max(SCHED_RR);
+    if ((min_prio >=0) && (max_prio >= 0) &&
+        ((USE_MASTER_THREAD_PRIORITY) <= max_prio) &&
+        ((USE_MASTER_THREAD_PRIORITY) >= min_prio)
+       ) {
+        struct sched_param sched_param = {0};
+        sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
+        pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
+    }
+#endif
+
+    /* Initialize thread local storage */
+#if defined(_WIN32) && !defined(__SYMBIAN32__)
+    tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
+#endif
+    tls.is_master = 1;
+    pthread_setspecific(sTlsKey, &tls);
+
+    /* Server starts *now* */
+    ctx->start_time = (unsigned long)time(NULL);
+
+    /* Allocate memory for the listening sockets, and start the server */
+    pfd = (struct pollfd *) calloc(ctx->num_listening_sockets, sizeof(pfd[0]));
+    while (pfd != NULL && ctx->stop_flag == 0) {
+        for (i = 0; i < ctx->num_listening_sockets; i++) {
+            pfd[i].fd = ctx->listening_sockets[i].sock;
+            pfd[i].events = POLLIN;
+        }
+
+        if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
+            for (i = 0; i < ctx->num_listening_sockets; i++) {
+                /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
+                   successful poll, and POLLIN is defined as
+                   (POLLRDNORM | POLLRDBAND)
+                   Therefore, we're checking pfd[i].revents & POLLIN, not
+                   pfd[i].revents == POLLIN. */
+                if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
+                    accept_new_connection(&ctx->listening_sockets[i], ctx);
+                }
+            }
+        }
+    }
+    free(pfd);
+    DEBUG_TRACE(("stopping workers"));
+
+    /* Stop signal received: somebody called mg_stop. Quit. */
+    close_all_listening_sockets(ctx);
+
+    /* Wakeup workers that are waiting for connections to handle. */
+    pthread_cond_broadcast(&ctx->sq_full);
+
+    /* Wait until all threads finish */
+    (void) pthread_mutex_lock(&ctx->mutex);
+    while (ctx->num_threads > 0) {
+        (void) pthread_cond_wait(&ctx->cond, &ctx->mutex);
+    }
+    (void) pthread_mutex_unlock(&ctx->mutex);
+
+    /* Join all worker threads to avoid leaking threads. */
+    workerthreadcount = ctx->workerthreadcount;
+    for (i = 0; i < workerthreadcount; i++) {
+        mg_join_thread(ctx->workerthreadids[i]);
+    }
+
+    /* All threads exited, no sync is needed. Destroy mutex and condvars */
+    (void) pthread_mutex_destroy(&ctx->mutex);
+    (void) pthread_cond_destroy(&ctx->cond);
+    (void) pthread_cond_destroy(&ctx->sq_empty);
+    (void) pthread_cond_destroy(&ctx->sq_full);
+
+#if !defined(NO_SSL)
+    uninitialize_ssl(ctx);
+#endif
+    DEBUG_TRACE(("exiting"));
+
+#if defined(_WIN32) && !defined(__SYMBIAN32__)
+    CloseHandle(tls.pthread_cond_helper_mutex);
+#endif
+    pthread_setspecific(sTlsKey, 0);
+
+    /* Signal mg_stop() that we're done.
+       WARNING: This must be the very last thing this
+       thread does, as ctx becomes invalid after this line. */
+    ctx->stop_flag = 2;
+}
+
+/* Threads have different return types on Windows and Unix. */
+
+#ifdef _WIN32
+static unsigned __stdcall master_thread(void *thread_func_param)
+{
+    master_thread_run(thread_func_param);
+    return 0;
+}
+#else
+static void *master_thread(void *thread_func_param)
+{
+    master_thread_run(thread_func_param);
+    return NULL;
+}
+#endif /* _WIN32 */
+
+static void free_context(struct mg_context *ctx)
+{
+    int i;
+    struct mg_request_handler_info *tmp_rh;
+
+    if (ctx == NULL)
+        return;
+
+    /* Deallocate config parameters */
+    for (i = 0; i < NUM_OPTIONS; i++) {
+        if (ctx->config[i] != NULL)
+#ifdef WIN32
+#pragma warning(suppress: 6001)
+#endif
+            free(ctx->config[i]);
+    }
+
+    /* Deallocate request handlers */
+    while (ctx->request_handlers) {
+        tmp_rh = ctx->request_handlers;
+        ctx->request_handlers = tmp_rh->next;
+        free(tmp_rh->uri);
+        free(tmp_rh);
+    }
+
+#ifndef NO_SSL
+    /* Deallocate SSL context */
+    if (ctx->ssl_ctx != NULL) {
+        SSL_CTX_free(ctx->ssl_ctx);
+    }
+    if (ssl_mutexes != NULL) {
+        free(ssl_mutexes);
+        ssl_mutexes = NULL;
+    }
+#endif /* !NO_SSL */
+
+    /* Deallocate worker thread ID array */
+    if (ctx->workerthreadids != NULL) {
+        free(ctx->workerthreadids);
+    }
+
+    /* Deallocate the tls variable */
+    sTlsInit--;
+    if (sTlsInit==0) {
+        pthread_key_delete(sTlsKey);
+    }
+
+    /* Deallocate context itself */
+    free(ctx);
+}
+
+void mg_stop(struct mg_context *ctx)
+{
+    ctx->stop_flag = 1;
+
+    /* Wait until mg_fini() stops */
+    while (ctx->stop_flag != 2) {
+        (void) mg_sleep(10);
+    }
+    mg_join_thread(ctx->masterthreadid);
+    free_context(ctx);
+
+#if defined(_WIN32) && !defined(__SYMBIAN32__)
+    (void) WSACleanup();
+#endif /* _WIN32 && !__SYMBIAN32__ */
+}
+
+struct mg_context *mg_start(const struct mg_callbacks *callbacks,
+                            void *user_data,
+                            const char **options)
+{
+    struct mg_context *ctx;
+    const char *name, *value, *default_value;
+    int i;
+    int workerthreadcount;
+
+#if defined(_WIN32) && !defined(__SYMBIAN32__)
+    WSADATA data;
+    WSAStartup(MAKEWORD(2,2), &data);
+#pragma warning(suppress: 28125)
+    InitializeCriticalSection(&global_log_file_lock);
+#endif /* _WIN32 && !__SYMBIAN32__ */
+
+    /* Check if the config_options and the corresponding enum have compatible sizes. */
+    /* Could use static_assert, once it is verified that all compilers support this. */
+    assert(sizeof(config_options)/sizeof(config_options[0]) == NUM_OPTIONS*2+1);
+
+    /* Allocate context and initialize reasonable general case defaults.
+       TODO(lsm): do proper error handling here. */
+    if ((ctx = (struct mg_context *) calloc(1, sizeof(*ctx))) == NULL) {
+        return NULL;
+    }
+
+    if (sTlsInit==0) {
+        if (0 != pthread_key_create(&sTlsKey, NULL)) {
+            mg_cry(fc(ctx), "Cannot initialize thread local storage");
+            free(ctx);
+            return NULL;
+        }
+        sTlsInit++;
+    }
+
+    ctx->callbacks = *callbacks;
+    ctx->user_data = user_data;
+    ctx->request_handlers = 0;
+
+    while (options && (name = *options++) != NULL) {
+        if ((i = get_option_index(name)) == -1) {
+            mg_cry(fc(ctx), "Invalid option: %s", name);
+            free_context(ctx);
+            return NULL;
+        } else if ((value = *options++) == NULL) {
+            mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
+            free_context(ctx);
+            return NULL;
+        }
+        if (ctx->config[i] != NULL) {
+            mg_cry(fc(ctx), "warning: %s: duplicate option", name);
+            free(ctx->config[i]);
+        }
+        ctx->config[i] = mg_strdup(value);
+        DEBUG_TRACE(("[%s] -> [%s]", name, value));
+    }
+
+    /* Set default value if needed */
+    for (i = 0; config_options[i * 2] != NULL; i++) {
+        default_value = config_options[i * 2 + 1];
+        if (ctx->config[i] == NULL && default_value != NULL) {
+            ctx->config[i] = mg_strdup(default_value);
+        }
+    }
+
+    /* NOTE(lsm): order is important here. SSL certificates must
+       be initialized before listening ports. UID must be set last. */
+    if (!set_gpass_option(ctx) ||
+#if !defined(NO_SSL)
+        !set_ssl_option(ctx) ||
+#endif
+        !set_ports_option(ctx) ||
+#if !defined(_WIN32)
+        !set_uid_option(ctx) ||
+#endif
+        !set_acl_option(ctx)) {
+        free_context(ctx);
+        return NULL;
+    }
+
+#if !defined(_WIN32) && !defined(__SYMBIAN32__)
+    /* Ignore SIGPIPE signal, so if browser cancels the request, it
+       won't kill the whole process. */
+    (void) signal(SIGPIPE, SIG_IGN);
+#endif /* !_WIN32 && !__SYMBIAN32__ */
+
+    (void) pthread_mutex_init(&ctx->mutex, NULL);
+    (void) pthread_cond_init(&ctx->cond, NULL);
+    (void) pthread_cond_init(&ctx->sq_empty, NULL);
+    (void) pthread_cond_init(&ctx->sq_full, NULL);
+
+    workerthreadcount = atoi(ctx->config[NUM_THREADS]);
+
+    if (workerthreadcount > MAX_WORKER_THREADS) {
+        mg_cry(fc(ctx), "Too many worker threads");
+        free_context(ctx);
+        return NULL;
+    }
+
+    if (workerthreadcount > 0) {
+        ctx->workerthreadcount = workerthreadcount;
+        ctx->workerthreadids = calloc(workerthreadcount, sizeof(pthread_t));
+        if (ctx->workerthreadids == NULL) {
+            mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
+            free_context(ctx);
+            return NULL;
+        }
+    }
+
+    /* Start master (listening) thread */
+    mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
+
+    /* Start worker threads */
+    for (i = 0; i < workerthreadcount; i++) {
+        (void) pthread_mutex_lock(&ctx->mutex);
+        ctx->num_threads++;
+        (void) pthread_mutex_unlock(&ctx->mutex);
+        if (mg_start_thread_with_id(worker_thread, ctx,
+                                    &ctx->workerthreadids[i]) != 0) {
+            (void) pthread_mutex_lock(&ctx->mutex);
+            ctx->num_threads--;
+            (void) pthread_mutex_unlock(&ctx->mutex);
+            mg_cry(fc(ctx), "Cannot start worker thread: %ld", (long) ERRNO);
+        }
+    }
+
+    return ctx;
+}
diff --git a/src/civetweb/civetweb.h b/src/civetweb/civetweb.h
new file mode 100644
index 0000000..d6f4c55
--- /dev/null
+++ b/src/civetweb/civetweb.h
@@ -0,0 +1,510 @@
+/* Copyright (c) 2004-2013 Sergey Lyubka
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#ifndef CIVETWEB_HEADER_INCLUDED
+#define CIVETWEB_HEADER_INCLUDED
+
+#ifndef CIVETWEB_VERSION
+#define CIVETWEB_VERSION "1.6"
+#endif
+
+#ifndef CIVETWEB_API
+    #if defined(_WIN32)
+        #if defined(CIVETWEB_DLL_EXPORTS)
+            #define CIVETWEB_API __declspec(dllexport)
+        #elif defined(CIVETWEB_DLL_IMPORTS)
+            #define CIVETWEB_API __declspec(dllimport)
+        #else
+            #define CIVETWEB_API
+        #endif
+    #else
+        #define CIVETWEB_API
+    #endif
+#endif
+
+#include <stdio.h>
+#include <stddef.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+struct mg_context;     /* Handle for the HTTP service itself */
+struct mg_connection;  /* Handle for the individual connection */
+
+
+/* This structure contains information about the HTTP request. */
+struct mg_request_info {
+    const char *request_method; /* "GET", "POST", etc */
+    const char *uri;            /* URL-decoded URI */
+    const char *http_version;   /* E.g. "1.0", "1.1" */
+    const char *query_string;   /* URL part after '?', not including '?', or
+                                   NULL */
+    const char *remote_user;    /* Authenticated user, or NULL if no auth
+                                   used */
+    long remote_ip;             /* Client's IP address */
+    int remote_port;            /* Client's port */
+    int is_ssl;                 /* 1 if SSL-ed, 0 if not */
+    void *user_data;            /* User data pointer passed to mg_start() */
+    void *conn_data;            /* Connection-specific user data */
+
+    int num_headers;            /* Number of HTTP headers */
+    struct mg_header {
+        const char *name;       /* HTTP header name */
+        const char *value;      /* HTTP header value */
+    } http_headers[64];         /* Maximum 64 headers */
+};
+
+
+/* This structure needs to be passed to mg_start(), to let civetweb know
+   which callbacks to invoke. For detailed description, see
+   https://github.com/sunsetbrew/civetweb/blob/master/docs/UserManual.md */
+struct mg_callbacks {
+    /* Called when civetweb has received new HTTP request.
+       If callback returns non-zero,
+       callback must process the request by sending valid HTTP headers and
+       body, and civetweb will not do any further processing.
+       If callback returns 0, civetweb processes the request itself. In this
+       case, callback must not send any data to the client. */
+    int  (*begin_request)(struct mg_connection *);
+
+    /* Called when civetweb has finished processing request. */
+    void (*end_request)(const struct mg_connection *, int reply_status_code);
+
+    /* Called when civetweb is about to log a message. If callback returns
+       non-zero, civetweb does not log anything. */
+    int  (*log_message)(const struct mg_connection *, const char *message);
+
+    /* Called when civetweb initializes SSL library. */
+    int  (*init_ssl)(void *ssl_context, void *user_data);
+
+    /* Called when websocket request is received, before websocket handshake.
+       If callback returns 0, civetweb proceeds with handshake, otherwise
+       cinnection is closed immediately. */
+    int (*websocket_connect)(const struct mg_connection *);
+
+    /* Called when websocket handshake is successfully completed, and
+       connection is ready for data exchange. */
+    void (*websocket_ready)(struct mg_connection *);
+
+    /* Called when data frame has been received from the client.
+       Parameters:
+          bits: first byte of the websocket frame, see websocket RFC at
+                http://tools.ietf.org/html/rfc6455, section 5.2
+          data, data_len: payload, with mask (if any) already applied.
+       Return value:
+          non-0: keep this websocket connection opened.
+          0:     close this websocket connection. */
+    int  (*websocket_data)(struct mg_connection *, int bits,
+                           char *data, size_t data_len);
+
+    /* Called when civetweb is closing a connection.  The per-context mutex is
+       locked when this is invoked.  This is primarily useful for noting when
+       a websocket is closing and removing it from any application-maintained
+       list of clients. */
+    void (*connection_close)(struct mg_connection *);
+
+    /* Called when civetweb tries to open a file. Used to intercept file open
+       calls, and serve file data from memory instead.
+       Parameters:
+          path:     Full path to the file to open.
+          data_len: Placeholder for the file size, if file is served from
+                    memory.
+       Return value:
+          NULL: do not serve file from memory, proceed with normal file open.
+          non-NULL: pointer to the file contents in memory. data_len must be
+          initilized with the size of the memory block. */
+    const char * (*open_file)(const struct mg_connection *,
+                              const char *path, size_t *data_len);
+
+    /* Called when civetweb is about to serve Lua server page (.lp file), if
+       Lua support is enabled.
+       Parameters:
+         lua_context: "lua_State *" pointer. */
+    void (*init_lua)(struct mg_connection *, void *lua_context);
+
+    /* Called when civetweb has uploaded a file to a temporary directory as a
+       result of mg_upload() call.
+       Parameters:
+          file_file: full path name to the uploaded file. */
+    void (*upload)(struct mg_connection *, const char *file_name);
+
+    /* Called when civetweb is about to send HTTP error to the client.
+       Implementing this callback allows to create custom error pages.
+       Parameters:
+         status: HTTP error status code. */
+    int  (*http_error)(struct mg_connection *, int status);
+};
+
+/* Start web server.
+
+   Parameters:
+     callbacks: mg_callbacks structure with user-defined callbacks.
+     options: NULL terminated list of option_name, option_value pairs that
+              specify Civetweb configuration parameters.
+
+   Side-effects: on UNIX, ignores SIGCHLD and SIGPIPE signals. If custom
+      processing is required for these, signal handlers must be set up
+      after calling mg_start().
+
+
+   Example:
+     const char *options[] = {
+       "document_root", "/var/www",
+       "listening_ports", "80,443s",
+       NULL
+     };
+     struct mg_context *ctx = mg_start(&my_func, NULL, options);
+
+   Refer to https://github.com/sunsetbrew/civetweb/blob/master/docs/UserManual.md
+   for the list of valid option and their possible values.
+
+   Return:
+     web server context, or NULL on error. */
+CIVETWEB_API struct mg_context *mg_start(const struct mg_callbacks *callbacks,
+                            void *user_data,
+                            const char **configuration_options);
+
+
+/* Stop the web server.
+
+   Must be called last, when an application wants to stop the web server and
+   release all associated resources. This function blocks until all Civetweb
+   threads are stopped. Context pointer becomes invalid. */
+CIVETWEB_API void mg_stop(struct mg_context *);
+
+/* mg_request_handler
+
+   Called when a new request comes in.  This callback is URI based
+   and configured with mg_set_request_handler().
+
+   Parameters:
+      conn: current connection information.
+      cbdata: the callback data configured with mg_set_request_handler().
+   Returns:
+      0: the handler could not handle the request, so fall through.
+      1: the handler processed the request. */
+typedef int (* mg_request_handler)(struct mg_connection *conn, void *cbdata);
+
+/* mg_set_request_handler
+
+   Sets or removes a URI mapping for a request handler.
+
+   URI's are ordered and prefixed URI's are supported. For example,
+   consider two URIs: /a/b and /a
+           /a   matches /a
+           /a/b matches /a/b
+           /a/c matches /a
+
+   Parameters:
+      ctx: server context
+      uri: the URI to configure
+      handler: the callback handler to use when the URI is requested.
+               If NULL, the URI will be removed.
+      cbdata: the callback data to give to the handler when it s requested. */
+CIVETWEB_API void mg_set_request_handler(struct mg_context *ctx, const char *uri, mg_request_handler handler, void *cbdata);
+
+
+/* Get the value of particular configuration parameter.
+   The value returned is read-only. Civetweb does not allow changing
+   configuration at run time.
+   If given parameter name is not valid, NULL is returned. For valid
+   names, return value is guaranteed to be non-NULL. If parameter is not
+   set, zero-length string is returned. */
+CIVETWEB_API const char *mg_get_option(const struct mg_context *ctx, const char *name);
+
+
+/* Return array of strings that represent valid configuration options.
+   For each option, option name and default value is returned, i.e. the
+   number of entries in the array equals to number_of_options x 2.
+   Array is NULL terminated. */
+CIVETWEB_API const char **mg_get_valid_option_names(void);
+
+/* Get the list of ports that civetweb is listening on.
+   size is the size of the ports int array and ssl int array to fill.
+   It is the caller's responsibility to make sure ports and ssl each
+   contain at least size int elements worth of memory to write into.
+   Return value is the number of ports and ssl information filled in.
+   The value returned is read-only. Civetweb does not allow changing
+   configuration at run time. */
+CIVETWEB_API size_t mg_get_ports(const struct mg_context *ctx, size_t size, int* ports, int* ssl);
+
+/* Add, edit or delete the entry in the passwords file.
+
+   This function allows an application to manipulate .htpasswd files on the
+   fly by adding, deleting and changing user records. This is one of the
+   several ways of implementing authentication on the server side. For another,
+   cookie-based way please refer to the examples/chat in the source tree.
+
+   If password is not NULL, entry is added (or modified if already exists).
+   If password is NULL, entry is deleted.
+
+   Return:
+     1 on success, 0 on error. */
+CIVETWEB_API int mg_modify_passwords_file(const char *passwords_file_name,
+                                          const char *domain,
+                                          const char *user,
+                                          const char *password);
+
+
+/* Return information associated with the request. */
+CIVETWEB_API struct mg_request_info *mg_get_request_info(struct mg_connection *);
+
+
+/* Send data to the client.
+   Return:
+    0   when the connection has been closed
+    -1  on error
+    >0  number of bytes written on success */
+CIVETWEB_API int mg_write(struct mg_connection *, const void *buf, size_t len);
+
+
+/* Send data to a websocket client wrapped in a websocket frame.  Uses mg_lock
+   to ensure that the transmission is not interrupted, i.e., when the
+   application is proactively communicating and responding to a request
+   simultaneously.
+
+   Send data to a websocket client wrapped in a websocket frame.
+   This function is available when civetweb is compiled with -DUSE_WEBSOCKET
+
+   Return:
+    0   when the connection has been closed
+    -1  on error
+    >0  number of bytes written on success */
+CIVETWEB_API int mg_websocket_write(struct mg_connection* conn, int opcode,
+                                    const char *data, size_t data_len);
+
+/* Blocks until unique access is obtained to this connection. Intended for use
+   with websockets only.
+   Invoke this before mg_write or mg_printf when communicating with a
+   websocket if your code has server-initiated communication as well as
+   communication in direct response to a message. */
+CIVETWEB_API void mg_lock(struct mg_connection* conn);
+CIVETWEB_API void mg_unlock(struct mg_connection* conn);
+
+/* Opcodes, from http://tools.ietf.org/html/rfc6455 */
+enum {
+    WEBSOCKET_OPCODE_CONTINUATION = 0x0,
+    WEBSOCKET_OPCODE_TEXT = 0x1,
+    WEBSOCKET_OPCODE_BINARY = 0x2,
+    WEBSOCKET_OPCODE_CONNECTION_CLOSE = 0x8,
+    WEBSOCKET_OPCODE_PING = 0x9,
+    WEBSOCKET_OPCODE_PONG = 0xa
+};
+
+
+/* Macros for enabling compiler-specific checks for printf-like arguments. */
+#undef PRINTF_FORMAT_STRING
+#if defined(_MSC_VER) && _MSC_VER >= 1400
+#include <sal.h>
+#if defined(_MSC_VER) && _MSC_VER > 1400
+#define PRINTF_FORMAT_STRING(s) _Printf_format_string_ s
+#else
+#define PRINTF_FORMAT_STRING(s) __format_string s
+#endif
+#else
+#define PRINTF_FORMAT_STRING(s) s
+#endif
+
+#ifdef __GNUC__
+#define PRINTF_ARGS(x, y) __attribute__((format(printf, x, y)))
+#else
+#define PRINTF_ARGS(x, y)
+#endif
+
+/* Send data to the client using printf() semantics.
+
+   Works exactly like mg_write(), but allows to do message formatting. */
+CIVETWEB_API int mg_printf(struct mg_connection *,
+                           PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(2, 3);
+
+
+/* Send contents of the entire file together with HTTP headers. */
+CIVETWEB_API void mg_send_file(struct mg_connection *conn, const char *path);
+
+
+/* Read data from the remote end, return number of bytes read.
+   Return:
+     0     connection has been closed by peer. No more data could be read.
+     < 0   read error. No more data could be read from the connection.
+     > 0   number of bytes read into the buffer. */
+CIVETWEB_API int mg_read(struct mg_connection *, void *buf, size_t len);
+
+
+/* Get the value of particular HTTP header.
+
+   This is a helper function. It traverses request_info->http_headers array,
+   and if the header is present in the array, returns its value. If it is
+   not present, NULL is returned. */
+CIVETWEB_API const char *mg_get_header(const struct mg_connection *, const char *name);
+
+
+/* Get a value of particular form variable.
+
+   Parameters:
+     data: pointer to form-uri-encoded buffer. This could be either POST data,
+           or request_info.query_string.
+     data_len: length of the encoded data.
+     var_name: variable name to decode from the buffer
+     dst: destination buffer for the decoded variable
+     dst_len: length of the destination buffer
+
+   Return:
+     On success, length of the decoded variable.
+     On error:
+        -1 (variable not found).
+        -2 (destination buffer is NULL, zero length or too small to hold the
+            decoded variable).
+
+   Destination buffer is guaranteed to be '\0' - terminated if it is not
+   NULL or zero length. */
+CIVETWEB_API int mg_get_var(const char *data, size_t data_len,
+                            const char *var_name, char *dst, size_t dst_len);
+
+/* Get a value of particular form variable.
+
+   Parameters:
+     data: pointer to form-uri-encoded buffer. This could be either POST data,
+           or request_info.query_string.
+     data_len: length of the encoded data.
+     var_name: variable name to decode from the buffer
+     dst: destination buffer for the decoded variable
+     dst_len: length of the destination buffer
+     occurrence: which occurrence of the variable, 0 is the first, 1 the
+                 second...
+                this makes it possible to parse a query like
+                b=x&a=y&a=z which will have occurrence values b:0, a:0 and a:1
+
+   Return:
+     On success, length of the decoded variable.
+     On error:
+        -1 (variable not found).
+        -2 (destination buffer is NULL, zero length or too small to hold the
+            decoded variable).
+
+   Destination buffer is guaranteed to be '\0' - terminated if it is not
+   NULL or zero length. */
+CIVETWEB_API int mg_get_var2(const char *data, size_t data_len,
+                             const char *var_name, char *dst, size_t dst_len, size_t occurrence);
+
+/* Fetch value of certain cookie variable into the destination buffer.
+
+   Destination buffer is guaranteed to be '\0' - terminated. In case of
+   failure, dst[0] == '\0'. Note that RFC allows many occurrences of the same
+   parameter. This function returns only first occurrence.
+
+   Return:
+     On success, value length.
+     On error:
+        -1 (either "Cookie:" header is not present at all or the requested
+            parameter is not found).
+        -2 (destination buffer is NULL, zero length or too small to hold the
+            value). */
+CIVETWEB_API int mg_get_cookie(const char *cookie, const char *var_name,
+                               char *buf, size_t buf_len);
+
+
+/* Download data from the remote web server.
+     host: host name to connect to, e.g. "foo.com", or "10.12.40.1".
+     port: port number, e.g. 80.
+     use_ssl: wether to use SSL connection.
+     error_buffer, error_buffer_size: error message placeholder.
+     request_fmt,...: HTTP request.
+   Return:
+     On success, valid pointer to the new connection, suitable for mg_read().
+     On error, NULL. error_buffer contains error message.
+   Example:
+     char ebuf[100];
+     struct mg_connection *conn;
+     conn = mg_download("google.com", 80, 0, ebuf, sizeof(ebuf),
+                        "%s", "GET / HTTP/1.0\r\nHost: google.com\r\n\r\n");
+ */
+CIVETWEB_API struct mg_connection *mg_download(const char *host, int port, int use_ssl,
+                                               char *error_buffer, size_t error_buffer_size,
+                                               PRINTF_FORMAT_STRING(const char *request_fmt),
+                                               ...) PRINTF_ARGS(6, 7);
+
+
+/* Close the connection opened by mg_download(). */
+CIVETWEB_API void mg_close_connection(struct mg_connection *conn);
+
+
+/* File upload functionality. Each uploaded file gets saved into a temporary
+   file and MG_UPLOAD event is sent.
+   Return number of uploaded files. */
+CIVETWEB_API int mg_upload(struct mg_connection *conn, const char *destination_dir);
+
+
+/* Convenience function -- create detached thread.
+   Return: 0 on success, non-0 on error. */
+typedef void * (*mg_thread_func_t)(void *);
+CIVETWEB_API int mg_start_thread(mg_thread_func_t f, void *p);
+
+
+/* Return builtin mime type for the given file name.
+   For unrecognized extensions, "text/plain" is returned. */
+CIVETWEB_API const char *mg_get_builtin_mime_type(const char *file_name);
+
+
+/* Return Civetweb version. */
+CIVETWEB_API const char *mg_version(void);
+
+/* URL-decode input buffer into destination buffer.
+   0-terminate the destination buffer.
+   form-url-encoded data differs from URI encoding in a way that it
+   uses '+' as character for space, see RFC 1866 section 8.2.1
+   http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
+   Return: length of the decoded data, or -1 if dst buffer is too small. */
+CIVETWEB_API int mg_url_decode(const char *src, int src_len, char *dst,
+                               int dst_len, int is_form_url_encoded);
+
+/* URL-encode input buffer into destination buffer.
+   returns the length of the resulting buffer or -1
+   is the buffer is too small. */
+CIVETWEB_API int mg_url_encode(const char *src, char *dst, size_t dst_len);
+
+/* MD5 hash given strings.
+   Buffer 'buf' must be 33 bytes long. Varargs is a NULL terminated list of
+   ASCIIz strings. When function returns, buf will contain human-readable
+   MD5 hash. Example:
+     char buf[33];
+     mg_md5(buf, "aa", "bb", NULL); */
+CIVETWEB_API char *mg_md5(char buf[33], ...);
+
+
+/* Print error message to the opened error log stream.
+   This utilizes the provided logging configuration.
+     conn: connection
+     fmt: format string without the line return
+     ...: variable argument list
+   Example:
+     mg_cry(conn,"i like %s", "logging"); */
+CIVETWEB_API void mg_cry(struct mg_connection *conn,
+                         PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(2, 3);
+
+/* utility method to compare two buffers, case incensitive. */
+CIVETWEB_API int mg_strncasecmp(const char *s1, const char *s2, size_t len);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif /* CIVETWEB_HEADER_INCLUDED */
diff --git a/src/civetweb/hello.c b/src/civetweb/hello.c
new file mode 100644
index 0000000..39253c1
--- /dev/null
+++ b/src/civetweb/hello.c
@@ -0,0 +1,53 @@
+#include <stdio.h>
+#include <string.h>
+#include "civetweb.h"
+
+// This function will be called by civetweb on every new request.
+static int begin_request_handler(struct mg_connection *conn)
+{
+    const struct mg_request_info *request_info = mg_get_request_info(conn);
+    char content[100];
+
+    // Prepare the message we're going to send
+    int content_length = snprintf(content, sizeof(content),
+                                  "Hello from civetweb! Remote port: %d",
+                                  request_info->remote_port);
+
+    // Send HTTP reply to the client
+    mg_printf(conn,
+              "HTTP/1.1 200 OK\r\n"
+              "Content-Type: text/plain\r\n"
+              "Content-Length: %d\r\n"        // Always set Content-Length
+              "\r\n"
+              "%s",
+              content_length, content);
+
+    // Returning non-zero tells civetweb that our function has replied to
+    // the client, and civetweb should not send client any more data.
+    return 1;
+}
+
+int main(void)
+{
+    struct mg_context *ctx;
+    struct mg_callbacks callbacks;
+
+    // List of options. Last element must be NULL.
+    const char *options[] = {"listening_ports", "8080", NULL};
+
+    // Prepare callbacks structure. We have only one callback, the rest are NULL.
+    memset(&callbacks, 0, sizeof(callbacks));
+    callbacks.begin_request = begin_request_handler;
+
+    // Start the web server.
+    ctx = mg_start(&callbacks, NULL, options);
+
+    // Wait until user hits "enter". Server is running in separate thread.
+    // Navigating to http://localhost:8080 will invoke begin_request_handler().
+    getchar();
+
+    // Stop the server.
+    mg_stop(ctx);
+
+    return 0;
+}
diff --git a/src/civetweb/main.c b/src/civetweb/main.c
new file mode 100644
index 0000000..90929a8
--- /dev/null
+++ b/src/civetweb/main.c
@@ -0,0 +1,1147 @@
+/* Copyright (c) 2004-2013 Sergey Lyubka
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+*/
+
+#if defined(_WIN32)
+#define _CRT_SECURE_NO_WARNINGS  /* Disable deprecation warning in VS2005 */
+#else
+#define _XOPEN_SOURCE 600  /* For PATH_MAX on linux */
+#endif
+
+#ifndef IGNORE_UNUSED_RESULT
+#define IGNORE_UNUSED_RESULT(a) (void)((a) && 1)
+#endif
+
+#include <sys/stat.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <signal.h>
+#include <string.h>
+#include <errno.h>
+#include <limits.h>
+#include <stddef.h>
+#include <stdarg.h>
+#include <ctype.h>
+
+#include "civetweb.h"
+
+#ifdef _WIN32
+#include <windows.h>
+#include <winsvc.h>
+#include <shlobj.h>
+
+#define getcwd(a,b) _getcwd(a,b)
+extern char *_getcwd(char *buf, size_t size);
+
+#ifndef PATH_MAX
+#define PATH_MAX MAX_PATH
+#endif
+
+#ifndef S_ISDIR
+#define S_ISDIR(x) ((x) & _S_IFDIR)
+#endif
+
+#define DIRSEP '\\'
+#define snprintf _snprintf
+#define vsnprintf _vsnprintf
+#define sleep(x) Sleep((x) * 1000)
+#define WINCDECL __cdecl
+#define abs_path(rel, abs, abs_size) _fullpath((abs), (rel), (abs_size))
+#else
+#include <sys/wait.h>
+#include <unistd.h>
+#define DIRSEP '/'
+#define WINCDECL
+#define abs_path(rel, abs, abs_size) realpath((rel), (abs))
+#endif /* _WIN32 */
+
+#define MAX_OPTIONS 100
+#define MAX_CONF_FILE_LINE_SIZE (8 * 1024)
+
+static int exit_flag;
+static char server_name[40];        /* Set by init_server_name() */
+static char config_file[PATH_MAX] = ""; /* Set by
+                                           process_command_line_arguments() */
+static struct mg_context *ctx;      /* Set by start_civetweb() */
+
+#if !defined(CONFIG_FILE)
+#define CONFIG_FILE "civetweb.conf"
+#endif /* !CONFIG_FILE */
+
+/* backup config file */
+#if !defined(CONFIG_FILE2) && defined(LINUX)
+#define CONFIG_FILE2 "/usr/local/etc/civetweb.conf"
+#endif
+
+static void WINCDECL signal_handler(int sig_num)
+{
+    exit_flag = sig_num;
+}
+
+static void die(const char *fmt, ...)
+{
+    va_list ap;
+    char msg[200] = "";
+
+    va_start(ap, fmt);
+    (void) vsnprintf(msg, sizeof(msg) -1, fmt, ap);
+    msg[sizeof(msg)-1] = 0;
+    va_end(ap);
+
+#if defined(_WIN32)
+    MessageBox(NULL, msg, "Error", MB_OK);
+#else
+    fprintf(stderr, "%s\n", msg);
+#endif
+
+    exit(EXIT_FAILURE);
+}
+
+static void show_usage_and_exit(void)
+{
+    const char **names;
+    int i;
+
+    fprintf(stderr, "Civetweb v%s, built on %s\n",
+            mg_version(), __DATE__);
+    fprintf(stderr, "Usage:\n");
+    fprintf(stderr, "  civetweb -A <htpasswd_file> <realm> <user> <passwd>\n");
+    fprintf(stderr, "  civetweb [config_file]\n");
+    fprintf(stderr, "  civetweb [-option value ...]\n");
+    fprintf(stderr, "\nOPTIONS:\n");
+
+    names = mg_get_valid_option_names();
+    for (i = 0; names[i] != NULL; i += 2) {
+        fprintf(stderr, "  -%s %s\n",
+                names[i], names[i + 1] == NULL ? "<empty>" : names[i + 1]);
+    }
+    exit(EXIT_FAILURE);
+}
+
+#if defined(_WIN32) || defined(USE_COCOA)
+static const char *config_file_top_comment =
+    "# Civetweb web server configuration file.\n"
+    "# For detailed description of every option, visit\n"
+    "# https://github.com/sunsetbrew/civetweb/blob/master/docs/UserManual.md\n"
+    "# Lines starting with '#' and empty lines are ignored.\n"
+    "# To make a change, remove leading '#', modify option's value,\n"
+    "# save this file and then restart Civetweb.\n\n";
+
+static const char *get_url_to_first_open_port(const struct mg_context *ctx)
+{
+    static char url[100];
+    const char *open_ports = mg_get_option(ctx, "listening_ports");
+    int a, b, c, d, port, n;
+
+    if (sscanf(open_ports, "%d.%d.%d.%d:%d%n", &a, &b, &c, &d, &port, &n) == 5) {
+        snprintf(url, sizeof(url), "%s://%d.%d.%d.%d:%d",
+                 open_ports[n] == 's' ? "https" : "http", a, b, c, d, port);
+    } else if (sscanf(open_ports, "%d%n", &port, &n) == 1) {
+        snprintf(url, sizeof(url), "%s://localhost:%d",
+                 open_ports[n] == 's' ? "https" : "http", port);
+    } else {
+        snprintf(url, sizeof(url), "%s", "http://localhost:8080");
+    }
+
+    return url;
+}
+
+static void create_config_file(const char *path)
+{
+    const char **names, *value;
+    FILE *fp;
+    int i;
+
+    /* Create config file if it is not present yet */
+    if ((fp = fopen(path, "r")) != NULL) {
+        fclose(fp);
+    } else if ((fp = fopen(path, "a+")) != NULL) {
+        fprintf(fp, "%s", config_file_top_comment);
+        names = mg_get_valid_option_names();
+        for (i = 0; names[i * 2] != NULL; i++) {
+            value = mg_get_option(ctx, names[i * 2]);
+            fprintf(fp, "# %s %s\n", names[i * 2], value ? value : "<value>");
+        }
+        fclose(fp);
+    }
+}
+#endif
+
+static char *sdup(const char *str)
+{
+    size_t len;
+    char *p;
+
+    len = strlen(str) + 1;
+    if ((p = (char *) malloc(len)) != NULL) {
+        memcpy(p, str, len);
+    }
+    return p;
+}
+
+static void set_option(char **options, const char *name, const char *value)
+{
+    int i;
+
+    for (i = 0; i < MAX_OPTIONS - 3; i++) {
+        if (options[i] == NULL) {
+            options[i] = sdup(name);
+            options[i + 1] = sdup(value);
+            options[i + 2] = NULL;
+            break;
+        } else if (!strcmp(options[i], name)) {
+            free(options[i + 1]);
+            options[i + 1] = sdup(value);
+            break;
+        }
+    }
+
+    if (i == MAX_OPTIONS - 3) {
+        die("%s", "Too many options specified");
+    }
+}
+
+static void read_config_file(const char *config_file, char **options)
+{
+    char line[MAX_CONF_FILE_LINE_SIZE], opt[sizeof(line)], val[sizeof(line)], *p;
+    FILE *fp = NULL;
+    size_t i, cmd_line_opts_start = 1, line_no = 0;
+
+    fp = fopen(config_file, "r");
+
+    /* If config file was set in command line and open failed, die */
+    if (cmd_line_opts_start == 2 && fp == NULL) {
+        die("Cannot open config file %s: %s", config_file, strerror(errno));
+    }
+
+    /* Load config file settings first */
+    if (fp != NULL) {
+        fprintf(stderr, "Loading config file %s\n", config_file);
+
+        /* Loop over the lines in config file */
+        while (fgets(line, sizeof(line), fp) != NULL) {
+
+            if (!line_no && !memcmp(line,"\xEF\xBB\xBF",3)) {
+                /* strip UTF-8 BOM */
+                p = line+3;
+            } else {
+                p = line;
+            }
+            line_no++;
+
+            /* Ignore empty lines and comments */
+            for (i = 0; isspace(* (unsigned char *) &line[i]); ) i++;
+            if (p[i] == '#' || p[i] == '\0') {
+                continue;
+            }
+
+            if (sscanf(p, "%s %[^\r\n#]", opt, val) != 2) {
+                printf("%s: line %d is invalid, ignoring it:\n %s",
+                       config_file, (int) line_no, p);
+            } else {
+                set_option(options, opt, val);
+            }
+        }
+
+        (void) fclose(fp);
+    }
+}
+
+static void process_command_line_arguments(char *argv[], char **options)
+{
+    char *p;
+    FILE *fp = NULL;
+    size_t i, cmd_line_opts_start = 1, line_no = 0;
+
+    /* Should we use a config file ? */
+    if (argv[1] != NULL && argv[1][0] != '-') {
+        snprintf(config_file, sizeof(config_file), "%s", argv[1]);
+        cmd_line_opts_start = 2;
+    } else if ((p = strrchr(argv[0], DIRSEP)) == NULL) {
+        /* No command line flags specified. Look where binary lives */
+        snprintf(config_file, sizeof(config_file)-1, "%s", CONFIG_FILE);
+        config_file[sizeof(config_file)-1] = 0;
+    } else {
+        snprintf(config_file, sizeof(config_file)-1, "%.*s%c%s",
+                 (int) (p - argv[0]), argv[0], DIRSEP, CONFIG_FILE);
+        config_file[sizeof(config_file)-1] = 0;
+    }
+
+#ifdef CONFIG_FILE2
+    fp = fopen(config_file, "r");
+
+    /* try alternate config file */
+    if (fp == NULL) {
+        fp = fopen(CONFIG_FILE2, "r");
+        if (fp != NULL) {
+            strcpy(config_file, CONFIG_FILE2);
+        }
+    }
+    if (fp != NULL) {
+        fclose(fp);
+    }
+#endif
+
+    /* read all configurations from a config file */
+    (void)read_config_file(config_file, options);
+
+    /* If we're under MacOS and started by launchd, then the second
+       argument is process serial number, -psn_.....
+       In this case, don't process arguments at all. */
+    if (argv[1] == NULL || memcmp(argv[1], "-psn_", 5) != 0) {
+        /* Handle command line flags.
+           They override config file and default settings. */
+        for (i = cmd_line_opts_start; argv[i] != NULL; i += 2) {
+            if (argv[i][0] != '-' || argv[i + 1] == NULL) {
+                show_usage_and_exit();
+            }
+            set_option(options, &argv[i][1], argv[i + 1]);
+        }
+    }
+}
+
+static void init_server_name(void)
+{
+    snprintf(server_name, sizeof(server_name), "Civetweb v%s",
+             mg_version());
+}
+
+static int log_message(const struct mg_connection *conn, const char *message)
+{
+    (void) conn;
+    printf("%s\n", message);
+    return 0;
+}
+
+static int is_path_absolute(const char *path)
+{
+#ifdef _WIN32
+    return path != NULL &&
+           ((path[0] == '\\' && path[1] == '\\') ||  /* UNC path, e.g.
+                                                        \\server\dir */
+            (isalpha(path[0]) && path[1] == ':' && path[2] == '\\'));  /* E.g. X:\dir */
+#else
+    return path != NULL && path[0] == '/';
+#endif
+}
+
+static char *get_option(char **options, const char *option_name)
+{
+    int i;
+
+    for (i = 0; options[i] != NULL; i++)
+        if (!strcmp(options[i], option_name))
+            return options[i + 1];
+
+    return NULL;
+}
+
+static void verify_existence(char **options, const char *option_name,
+                             int must_be_dir)
+{
+    struct stat st;
+    const char *path = get_option(options, option_name);
+
+#ifdef _WIN32
+    wchar_t wbuf[1024];
+    char mbbuf[1024];
+    int len;
+
+    if (path) {
+        memset(wbuf, 0, sizeof(wbuf));
+        memset(mbbuf, 0, sizeof(mbbuf));
+        len = MultiByteToWideChar(CP_UTF8, 0, path, -1, wbuf, (int) sizeof(wbuf)/sizeof(wbuf[0])-1);
+        wcstombs(mbbuf, wbuf, sizeof(mbbuf)-1);
+        path = mbbuf;
+    }
+#endif
+
+    if (path != NULL && (stat(path, &st) != 0 ||
+                         ((S_ISDIR(st.st_mode) ? 1 : 0) != must_be_dir))) {
+        die("Invalid path for %s: [%s]: (%s). Make sure that path is either "
+            "absolute, or it is relative to civetweb executable.",
+            option_name, path, strerror(errno));
+    }
+}
+
+static void set_absolute_path(char *options[], const char *option_name,
+                              const char *path_to_civetweb_exe)
+{
+    char path[PATH_MAX] = "", abs[PATH_MAX] = "", *option_value;
+    const char *p;
+
+    /* Check whether option is already set */
+    option_value = get_option(options, option_name);
+
+    /* If option is already set and it is an absolute path,
+       leave it as it is -- it's already absolute. */
+    if (option_value != NULL && !is_path_absolute(option_value)) {
+        /* Not absolute. Use the directory where civetweb executable lives
+           be the relative directory for everything.
+           Extract civetweb executable directory into path. */
+        if ((p = strrchr(path_to_civetweb_exe, DIRSEP)) == NULL) {
+            IGNORE_UNUSED_RESULT(getcwd(path, sizeof(path)));
+        } else {
+            snprintf(path, sizeof(path)-1, "%.*s", (int) (p - path_to_civetweb_exe),
+                     path_to_civetweb_exe);
+            path[sizeof(path)-1] = 0;
+        }
+
+        strncat(path, "/", sizeof(path) - 1);
+        strncat(path, option_value, sizeof(path) - 1);
+
+        /* Absolutize the path, and set the option */
+        IGNORE_UNUSED_RESULT(abs_path(path, abs, sizeof(abs)));
+        set_option(options, option_name, abs);
+    }
+}
+
+static void start_civetweb(int argc, char *argv[])
+{
+    struct mg_callbacks callbacks;
+    char *options[MAX_OPTIONS];
+    int i;
+
+    /* Edit passwords file if -A option is specified */
+    if (argc > 1 && !strcmp(argv[1], "-A")) {
+        if (argc != 6) {
+            show_usage_and_exit();
+        }
+        exit(mg_modify_passwords_file(argv[2], argv[3], argv[4], argv[5]) ?
+             EXIT_SUCCESS : EXIT_FAILURE);
+    }
+
+    /* Show usage if -h or --help options are specified */
+    if (argc == 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))) {
+        show_usage_and_exit();
+    }
+
+    options[0] = NULL;
+    set_option(options, "document_root", ".");
+
+    /* Update config based on command line arguments */
+    process_command_line_arguments(argv, options);
+
+    /* Make sure we have absolute paths for files and directories */
+    set_absolute_path(options, "document_root", argv[0]);
+    set_absolute_path(options, "put_delete_auth_file", argv[0]);
+    set_absolute_path(options, "cgi_interpreter", argv[0]);
+    set_absolute_path(options, "access_log_file", argv[0]);
+    set_absolute_path(options, "error_log_file", argv[0]);
+    set_absolute_path(options, "global_auth_file", argv[0]);
+#ifdef USE_LUA
+    set_absolute_path(options, "lua_preload_file", argv[0]);
+#endif
+    set_absolute_path(options, "ssl_certificate", argv[0]);
+
+    /* Make extra verification for certain options */
+    verify_existence(options, "document_root", 1);
+    verify_existence(options, "cgi_interpreter", 0);
+    verify_existence(options, "ssl_certificate", 0);
+#ifdef USE_LUA
+    verify_existence(options, "lua_preload_file", 0);
+#endif
+
+    /* Setup signal handler: quit on Ctrl-C */
+    signal(SIGTERM, signal_handler);
+    signal(SIGINT, signal_handler);
+
+    /* Start Civetweb */
+    memset(&callbacks, 0, sizeof(callbacks));
+    callbacks.log_message = &log_message;
+    ctx = mg_start(&callbacks, NULL, (const char **) options);
+    for (i = 0; options[i] != NULL; i++) {
+        free(options[i]);
+    }
+
+    if (ctx == NULL) {
+        die("%s", "Failed to start Civetweb.");
+    }
+}
+
+#ifdef _WIN32
+enum {
+    ID_ICON = 100, ID_QUIT, ID_SETTINGS, ID_SEPARATOR, ID_INSTALL_SERVICE,
+    ID_REMOVE_SERVICE, ID_STATIC, ID_GROUP,
+    ID_SAVE, ID_RESET_DEFAULTS, ID_RESET_FILE, ID_RESET_ACTIVE,
+    ID_STATUS, ID_CONNECT,
+
+    /* All dynamically created text boxes for options have IDs starting from
+       ID_CONTROLS, incremented by one. */
+    ID_CONTROLS = 200,
+
+    /* Text boxes for files have "..." buttons to open file browser. These
+       buttons have IDs that are ID_FILE_BUTTONS_DELTA higher than associated
+       text box ID. */
+    ID_FILE_BUTTONS_DELTA = 1000
+};
+static HICON hIcon;
+static SERVICE_STATUS ss;
+static SERVICE_STATUS_HANDLE hStatus;
+static const char *service_magic_argument = "--";
+static NOTIFYICONDATA TrayIcon;
+
+static void WINAPI ControlHandler(DWORD code)
+{
+    if (code == SERVICE_CONTROL_STOP || code == SERVICE_CONTROL_SHUTDOWN) {
+        ss.dwWin32ExitCode = 0;
+        ss.dwCurrentState = SERVICE_STOPPED;
+    }
+    SetServiceStatus(hStatus, &ss);
+}
+
+static void WINAPI ServiceMain(void)
+{
+    ss.dwServiceType = SERVICE_WIN32;
+    ss.dwCurrentState = SERVICE_RUNNING;
+    ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
+
+    hStatus = RegisterServiceCtrlHandler(server_name, ControlHandler);
+    SetServiceStatus(hStatus, &ss);
+
+    while (ss.dwCurrentState == SERVICE_RUNNING) {
+        Sleep(1000);
+    }
+    mg_stop(ctx);
+
+    ss.dwCurrentState = SERVICE_STOPPED;
+    ss.dwWin32ExitCode = (DWORD) -1;
+    SetServiceStatus(hStatus, &ss);
+}
+
+
+static void show_error(void)
+{
+    char buf[256];
+    FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
+                  NULL, GetLastError(),
+                  MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+                  buf, sizeof(buf), NULL);
+    MessageBox(NULL, buf, "Error", MB_OK);
+}
+
+static void *align(void *ptr, DWORD alig)
+{
+    ULONG ul = (ULONG) ptr;
+    ul += alig;
+    ul &= ~alig;
+    return ((void *) ul);
+}
+
+static int is_boolean_option(const char *option_name)
+{
+    return !strcmp(option_name, "enable_directory_listing") ||
+           !strcmp(option_name, "enable_keep_alive");
+}
+
+static int is_filename_option(const char *option_name)
+{
+    return !strcmp(option_name, "cgi_interpreter") ||
+           !strcmp(option_name, "global_auth_file") ||
+           !strcmp(option_name, "put_delete_auth_file") ||
+           !strcmp(option_name, "access_log_file") ||
+           !strcmp(option_name, "error_log_file") ||
+#ifdef USE_LUA
+           !strcmp(option_name, "lua_preload_file") ||
+#endif
+           !strcmp(option_name, "ssl_certificate");
+}
+
+static int is_directory_option(const char *option_name)
+{
+    return !strcmp(option_name, "document_root") ||
+#if defined(USE_WEBSOCKET)
+           !strcmp(option_name, "websocket_root") ||
+#endif
+           0;
+}
+
+static int is_numeric_options(const char *option_name)
+{
+    return !strcmp(option_name, "num_threads") ||
+           !strcmp(option_name, "request_timeout_ms");
+}
+
+static void save_config(HWND hDlg, FILE *fp)
+{
+    char value[2000] = "";
+    const char **options, *name, *default_value;
+    int i, id;
+
+    fprintf(fp, "%s", config_file_top_comment);
+    options = mg_get_valid_option_names();
+    for (i = 0; options[i * 2] != NULL; i++) {
+        name = options[i * 2];
+        id = ID_CONTROLS + i;
+        if (is_boolean_option(name)) {
+            snprintf(value, sizeof(value)-1, "%s",
+                     IsDlgButtonChecked(hDlg, id) ? "yes" : "no");
+            value[sizeof(value)-1] = 0;
+        } else {
+            GetDlgItemText(hDlg, id, value, sizeof(value));
+        }
+        default_value = options[i * 2 + 1] == NULL ? "" : options[i * 2 + 1];
+        /* If value is the same as default, skip it */
+        if (strcmp(value, default_value) != 0) {
+            fprintf(fp, "%s %s\n", name, value);
+        }
+    }
+}
+
+static BOOL CALLBACK DlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP)
+{
+    FILE *fp;
+    int i, j;
+    const char *name, *value;
+    const char **default_options = mg_get_valid_option_names();
+    char *file_options[MAX_OPTIONS] = {0};
+
+    switch (msg) {
+    case WM_CLOSE:
+        DestroyWindow(hDlg);
+        break;
+
+    case WM_COMMAND:
+        switch (LOWORD(wParam)) {
+
+        case ID_SAVE:
+            EnableWindow(GetDlgItem(hDlg, ID_SAVE), FALSE);
+            if ((fp = fopen(config_file, "w+")) != NULL) {
+                save_config(hDlg, fp);
+                fclose(fp);
+                mg_stop(ctx);
+                start_civetweb(__argc, __argv);
+            }
+            EnableWindow(GetDlgItem(hDlg, ID_SAVE), TRUE);
+            break;
+
+        case ID_RESET_DEFAULTS:
+            for (i = 0; default_options[i * 2] != NULL; i++) {
+                name = default_options[i * 2];
+                value = default_options[i * 2 + 1] == NULL ? "" : default_options[i * 2 + 1];
+                if (is_boolean_option(name)) {
+                    CheckDlgButton(hDlg, ID_CONTROLS + i, !strcmp(value, "yes") ?
+                                   BST_CHECKED : BST_UNCHECKED);
+                } else {
+                    SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), value);
+                }
+            }
+            break;
+
+        case ID_RESET_FILE:
+            read_config_file(config_file, file_options);
+            for (i = 0; default_options[i * 2] != NULL; i++) {
+                name = default_options[i * 2];
+                value = default_options[i * 2 + 1];
+                for (j = 0; file_options[j * 2] != NULL; j++) {
+                    if (!strcmp(name, file_options[j * 2])) {
+                        value = file_options[j * 2 + 1];
+                    }
+                }
+                if (value == NULL) {
+                    value = "";
+                }
+                if (is_boolean_option(name)) {
+                    CheckDlgButton(hDlg, ID_CONTROLS + i, !strcmp(value, "yes") ? BST_CHECKED : BST_UNCHECKED);
+                } else {
+                    SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), value);
+                }
+            }
+            for (i = 0; i<MAX_OPTIONS; i++) {
+                free(file_options[i]);
+            }
+            break;
+
+        case ID_RESET_ACTIVE:
+            for (i = 0; default_options[i * 2] != NULL; i++) {
+                name = default_options[i * 2];
+                value = mg_get_option(ctx, name);
+                if (is_boolean_option(name)) {
+                    CheckDlgButton(hDlg, ID_CONTROLS + i, !strcmp(value, "yes") ?
+                                   BST_CHECKED : BST_UNCHECKED);
+                } else {
+                    SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), value);
+                }
+            }
+            break;
+        }
+
+        for (i = 0; default_options[i * 2] != NULL; i++) {
+            name = default_options[i * 2];
+            if ((is_filename_option(name) || is_directory_option(name)) &&
+                LOWORD(wParam) == ID_CONTROLS + i + ID_FILE_BUTTONS_DELTA) {
+                OPENFILENAME of;
+                BROWSEINFO bi;
+                char path[PATH_MAX] = "";
+
+                memset(&of, 0, sizeof(of));
+                of.lStructSize = sizeof(of);
+                of.hwndOwner = (HWND) hDlg;
+                of.lpstrFile = path;
+                of.nMaxFile = sizeof(path);
+                of.lpstrInitialDir = mg_get_option(ctx, "document_root");
+                of.Flags = OFN_CREATEPROMPT | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
+
+                memset(&bi, 0, sizeof(bi));
+                bi.hwndOwner = (HWND) hDlg;
+                bi.lpszTitle = "Choose WWW root directory:";
+                bi.ulFlags = BIF_RETURNONLYFSDIRS;
+
+                if (is_directory_option(name)) {
+                    SHGetPathFromIDList(SHBrowseForFolder(&bi), path);
+                } else {
+                    GetOpenFileName(&of);
+                }
+
+                if (path[0] != '\0') {
+                    SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), path);
+                }
+            }
+        }
+        break;
+
+    case WM_INITDIALOG:
+        SendMessage(hDlg, WM_SETICON,(WPARAM) ICON_SMALL, (LPARAM) hIcon);
+        SendMessage(hDlg, WM_SETICON,(WPARAM) ICON_BIG, (LPARAM) hIcon);
+        SetWindowText(hDlg, "Civetweb settings");
+        SetFocus(GetDlgItem(hDlg, ID_SAVE));
+        for (i = 0; default_options[i * 2] != NULL; i++) {
+            name = default_options[i * 2];
+            value = mg_get_option(ctx, name);
+            if (is_boolean_option(name)) {
+                CheckDlgButton(hDlg, ID_CONTROLS + i, !strcmp(value, "yes") ?
+                               BST_CHECKED : BST_UNCHECKED);
+            } else {
+                SetDlgItemText(hDlg, ID_CONTROLS + i, value == NULL ? "" : value);
+            }
+        }
+        break;
+
+    default:
+        break;
+    }
+
+    return FALSE;
+}
+
+static void add_control(unsigned char **mem, DLGTEMPLATE *dia, WORD type,
+                        DWORD id, DWORD style, WORD x, WORD y,
+                        WORD cx, WORD cy, const char *caption)
+{
+    DLGITEMTEMPLATE *tp;
+    LPWORD p;
+
+    dia->cdit++;
+
+    *mem = align(*mem, 3);
+    tp = (DLGITEMTEMPLATE *) *mem;
+
+    tp->id = (WORD)id;
+    tp->style = style;
+    tp->dwExtendedStyle = 0;
+    tp->x = x;
+    tp->y = y;
+    tp->cx = cx;
+    tp->cy = cy;
+
+    p = align(*mem + sizeof(*tp), 1);
+    *p++ = 0xffff;
+    *p++ = type;
+
+    while (*caption != '\0') {
+        *p++ = (WCHAR) *caption++;
+    }
+    *p++ = 0;
+    p = align(p, 1);
+
+    *p++ = 0;
+    *mem = (unsigned char *) p;
+}
+
+static void show_settings_dialog()
+{
+#define HEIGHT 15
+#define WIDTH 450
+#define LABEL_WIDTH 85
+
+    unsigned char mem[4096], *p;
+    const char **option_names, *long_option_name;
+    DWORD style;
+    DLGTEMPLATE *dia = (DLGTEMPLATE *) mem;
+    WORD i, cl, x, y, width, nelems = 0;
+    static int guard = 0; /* test if dialog is already open */
+
+    static struct {
+        DLGTEMPLATE template; /* 18 bytes */
+        WORD menu, class;
+        wchar_t caption[1];
+        WORD fontsiz;
+        wchar_t fontface[7];
+    } dialog_header = {{
+            WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE |
+            DS_SETFONT | WS_DLGFRAME, WS_EX_TOOLWINDOW, 0, 200, 200, WIDTH, 0
+        },
+        0, 0, L"", 8, L"Tahoma"
+    };
+
+    if (guard == 0) {
+        guard++;
+    } else {
+        return;
+    }
+
+    (void) memset(mem, 0, sizeof(mem));
+    (void) memcpy(mem, &dialog_header, sizeof(dialog_header));
+    p = mem + sizeof(dialog_header);
+
+    option_names = mg_get_valid_option_names();
+    for (i = 0; option_names[i * 2] != NULL; i++) {
+        long_option_name = option_names[i * 2];
+        style = WS_CHILD | WS_VISIBLE | WS_TABSTOP;
+        x = 10 + (WIDTH / 2) * (nelems % 2);
+        y = (nelems/2 + 1) * HEIGHT + 5;
+        width = WIDTH / 2 - 20 - LABEL_WIDTH;
+        if (is_numeric_options(long_option_name)) {
+            style |= ES_NUMBER;
+            cl = 0x81;
+            style |= WS_BORDER | ES_AUTOHSCROLL;
+        } else if (is_boolean_option(long_option_name)) {
+            cl = 0x80;
+            style |= BS_AUTOCHECKBOX;
+        } else if (is_filename_option(long_option_name) ||
+                   is_directory_option(long_option_name)) {
+            style |= WS_BORDER | ES_AUTOHSCROLL;
+            width -= 20;
+            cl = 0x81;
+            add_control(&p, dia, 0x80,
+                        ID_CONTROLS + i + ID_FILE_BUTTONS_DELTA,
+                        WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
+                        (WORD) (x + width + LABEL_WIDTH + 5),
+                        y, 15, 12, "...");
+        } else {
+            cl = 0x81;
+            style |= WS_BORDER | ES_AUTOHSCROLL;
+        }
+        add_control(&p, dia, 0x82, ID_STATIC, WS_VISIBLE | WS_CHILD,
+                    x, y, LABEL_WIDTH, HEIGHT, long_option_name);
+        add_control(&p, dia, cl, ID_CONTROLS + i, style,
+                    (WORD) (x + LABEL_WIDTH), y, width, 12, "");
+        nelems++;
+    }
+
+    y = (WORD) (((nelems + 1) / 2 + 1) * HEIGHT + 5);
+    add_control(&p, dia, 0x80, ID_GROUP, WS_CHILD | WS_VISIBLE |
+                BS_GROUPBOX, 5, 5, WIDTH - 10, y, " Settings ");
+    y += 10;
+    add_control(&p, dia, 0x80, ID_SAVE,
+                WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
+                WIDTH - 70, y, 65, 12, "Save Settings");
+    add_control(&p, dia, 0x80, ID_RESET_DEFAULTS,
+                WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
+                WIDTH - 140, y, 65, 12, "Reset to defaults");
+    add_control(&p, dia, 0x80, ID_RESET_FILE,
+                WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
+                WIDTH - 210, y, 65, 12, "Reload from file");
+    add_control(&p, dia, 0x80, ID_RESET_ACTIVE,
+                WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
+                WIDTH - 280, y, 65, 12, "Reload active");
+    add_control(&p, dia, 0x82, ID_STATIC,
+                WS_CHILD | WS_VISIBLE | WS_DISABLED,
+                5, y, 100, 12, server_name);
+
+    dia->cy = ((nelems + 1) / 2 + 1) * HEIGHT + 30;
+    DialogBoxIndirectParam(NULL, dia, NULL, DlgProc, (LPARAM) NULL);
+    guard--;
+}
+
+static int manage_service(int action)
+{
+    static const char *service_name = "Civetweb";
+    SC_HANDLE hSCM = NULL, hService = NULL;
+    SERVICE_DESCRIPTION descr = {server_name};
+    char path[PATH_MAX + 20] = "";/* Path to executable plus magic argument */
+    int success = 1;
+
+    if ((hSCM = OpenSCManager(NULL, NULL, action == ID_INSTALL_SERVICE ?
+                              GENERIC_WRITE : GENERIC_READ)) == NULL) {
+        success = 0;
+        show_error();
+    } else if (action == ID_INSTALL_SERVICE) {
+        path[sizeof(path)-1] = 0;
+        GetModuleFileName(NULL, path, sizeof(path)-1);
+        strncat(path, " ", sizeof(path)-1);
+        strncat(path, service_magic_argument, sizeof(path)-1);
+        hService = CreateService(hSCM, service_name, service_name,
+                                 SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
+                                 SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
+                                 path, NULL, NULL, NULL, NULL, NULL);
+        if (hService) {
+            ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &descr);
+        } else {
+            show_error();
+        }
+    } else if (action == ID_REMOVE_SERVICE) {
+        if ((hService = OpenService(hSCM, service_name, DELETE)) == NULL ||
+            !DeleteService(hService)) {
+            show_error();
+        }
+    } else if ((hService = OpenService(hSCM, service_name,
+                                       SERVICE_QUERY_STATUS)) == NULL) {
+        success = 0;
+    }
+
+    if (hService)
+        CloseServiceHandle(hService);
+    if (hSCM)
+        CloseServiceHandle(hSCM);
+
+    return success;
+}
+
+static LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam,
+                                   LPARAM lParam)
+{
+    static SERVICE_TABLE_ENTRY service_table[] = {
+        {server_name, (LPSERVICE_MAIN_FUNCTION) ServiceMain},
+        {NULL, NULL}
+    };
+    int service_installed;
+    char buf[200], *service_argv[] = {__argv[0], NULL};
+    POINT pt;
+    HMENU hMenu;
+    static UINT s_uTaskbarRestart; /* for taskbar creation */
+
+    switch (msg) {
+    case WM_CREATE:
+        if (__argv[1] != NULL &&
+            !strcmp(__argv[1], service_magic_argument)) {
+            start_civetweb(1, service_argv);
+            StartServiceCtrlDispatcher(service_table);
+            exit(EXIT_SUCCESS);
+        } else {
+            start_civetweb(__argc, __argv);
+            s_uTaskbarRestart = RegisterWindowMessage(TEXT("TaskbarCreated"));
+        }
+        break;
+    case WM_COMMAND:
+        switch (LOWORD(wParam)) {
+        case ID_QUIT:
+            mg_stop(ctx);
+            Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
+            PostQuitMessage(0);
+            return 0;
+        case ID_SETTINGS:
+            show_settings_dialog();
+            break;
+        case ID_INSTALL_SERVICE:
+        case ID_REMOVE_SERVICE:
+            manage_service(LOWORD(wParam));
+            break;
+        case ID_CONNECT:
+            printf("[%s]\n", get_url_to_first_open_port(ctx));
+            ShellExecute(NULL, "open", get_url_to_first_open_port(ctx),
+                         NULL, NULL, SW_SHOW);
+            break;
+        }
+        break;
+    case WM_USER:
+        switch (lParam) {
+        case WM_RBUTTONUP:
+        case WM_LBUTTONUP:
+        case WM_LBUTTONDBLCLK:
+            hMenu = CreatePopupMenu();
+            AppendMenu(hMenu, MF_STRING | MF_GRAYED, ID_SEPARATOR, server_name);
+            AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
+            service_installed = manage_service(0);
+            snprintf(buf, sizeof(buf)-1, "NT service: %s installed",
+                     service_installed ? "" : "not");
+            buf[sizeof(buf)-1] = 0;
+            AppendMenu(hMenu, MF_STRING | MF_GRAYED, ID_SEPARATOR, buf);
+            AppendMenu(hMenu, MF_STRING | (service_installed ? MF_GRAYED : 0),
+                       ID_INSTALL_SERVICE, "Install service");
+            AppendMenu(hMenu, MF_STRING | (!service_installed ? MF_GRAYED : 0),
+                       ID_REMOVE_SERVICE, "Deinstall service");
+            AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
+            AppendMenu(hMenu, MF_STRING, ID_CONNECT, "Start browser");
+            AppendMenu(hMenu, MF_STRING, ID_SETTINGS, "Edit Settings");
+            AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
+            AppendMenu(hMenu, MF_STRING, ID_QUIT, "Exit");
+            GetCursorPos(&pt);
+            SetForegroundWindow(hWnd);
+            TrackPopupMenu(hMenu, 0, pt.x, pt.y, 0, hWnd, NULL);
+            PostMessage(hWnd, WM_NULL, 0, 0);
+            DestroyMenu(hMenu);
+            break;
+        }
+        break;
+    case WM_CLOSE:
+        mg_stop(ctx);
+        Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
+        PostQuitMessage(0);
+        return 0;/* We've just sent our own quit message, with proper hwnd. */
+    default:
+        if (msg==s_uTaskbarRestart)
+            Shell_NotifyIcon(NIM_ADD, &TrayIcon);
+    }
+
+    return DefWindowProc(hWnd, msg, wParam, lParam);
+}
+
+int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR cmdline, int show)
+{
+    WNDCLASS cls;
+    HWND hWnd;
+    MSG msg;
+
+    init_server_name();
+    memset(&cls, 0, sizeof(cls));
+    cls.lpfnWndProc = (WNDPROC) WindowProc;
+    cls.hIcon = LoadIcon(NULL, IDI_APPLICATION);
+    cls.lpszClassName = server_name;
+
+    RegisterClass(&cls);
+    hWnd = CreateWindow(cls.lpszClassName, server_name, WS_OVERLAPPEDWINDOW,
+                        0, 0, 0, 0, NULL, NULL, NULL, NULL);
+    ShowWindow(hWnd, SW_HIDE);
+
+    TrayIcon.cbSize = sizeof(TrayIcon);
+    TrayIcon.uID = ID_ICON;
+    TrayIcon.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
+    TrayIcon.hIcon = hIcon = LoadImage(GetModuleHandle(NULL),
+                                       MAKEINTRESOURCE(ID_ICON),
+                                       IMAGE_ICON, 16, 16, 0);
+    TrayIcon.hWnd = hWnd;
+    snprintf(TrayIcon.szTip, sizeof(TrayIcon.szTip), "%s", server_name);
+    TrayIcon.uCallbackMessage = WM_USER;
+    Shell_NotifyIcon(NIM_ADD, &TrayIcon);
+
+    while (GetMessage(&msg, hWnd, 0, 0) > 0) {
+        TranslateMessage(&msg);
+        DispatchMessage(&msg);
+    }
+
+    /* Return the WM_QUIT value. */
+    return (int) msg.wParam;
+}
+#elif defined(USE_COCOA)
+#import <Cocoa/Cocoa.h>
+
+@interface Civetweb :
+NSObject<NSApplicationDelegate>
+- (void) openBrowser;
+- (void) shutDown;
+@end
+
+@implementation Civetweb
+- (void) openBrowser {
+    [[NSWorkspace sharedWorkspace]
+openURL:[NSURL URLWithString:
+[NSString stringWithUTF8String:get_url_to_first_open_port(ctx)]]];
+}
+- (void) editConfig {
+    create_config_file(config_file);
+    [[NSWorkspace sharedWorkspace]
+openFile:[NSString stringWithUTF8String:config_file]
+withApplication:@"TextEdit"];
+}
+- (void)shutDown {
+[NSApp terminate:nil];
+}
+@end
+
+int main(int argc, char *argv[])
+{
+    init_server_name();
+    start_civetweb(argc, argv);
+
+    [NSAutoreleasePool new];
+    [NSApplication sharedApplication];
+
+    /* Add delegate to process menu item actions */
+    Civetweb *myDelegate = [[Civetweb alloc] autorelease];
+[NSApp setDelegate: myDelegate];
+
+    /* Run this app as agent */
+    ProcessSerialNumber psn = { 0, kCurrentProcess };
+    TransformProcessType(&psn, kProcessTransformToBackgroundApplication);
+    SetFrontProcess(&psn);
+
+    /* Add status bar menu */
+    id menu = [[NSMenu new] autorelease];
+
+    /* Add version menu item */
+[menu addItem:[[[NSMenuItem alloc]
+                    /*initWithTitle:[NSString stringWithFormat:@"%s", server_name]*/
+                initWithTitle:[NSString stringWithUTF8String:server_name]
+                action:@selector(noexist) keyEquivalent:@""] autorelease]];
+
+    /* Add configuration menu item */
+[menu addItem:[[[NSMenuItem alloc]
+                initWithTitle:@"Edit configuration"
+                action:@selector(editConfig) keyEquivalent:@""] autorelease]];
+
+    /* Add connect menu item */
+[menu addItem:[[[NSMenuItem alloc]
+                initWithTitle:@"Open web root in a browser"
+                action:@selector(openBrowser) keyEquivalent:@""] autorelease]];
+
+    /* Separator */
+[menu addItem:[NSMenuItem separatorItem]];
+
+    /* Add quit menu item */
+[menu addItem:[[[NSMenuItem alloc]
+                initWithTitle:@"Quit"
+                action:@selector(shutDown) keyEquivalent:@"q"] autorelease]];
+
+    /* Attach menu to the status bar */
+    id item = [[[NSStatusBar systemStatusBar]
+            statusItemWithLength:NSVariableStatusItemLength] retain];
+[item setHighlightMode:YES];
+[item setImage:[NSImage imageNamed:@"civetweb_22x22.png"]];
+[item setMenu:menu];
+
+    /* Run the app */
+[NSApp activateIgnoringOtherApps:YES];
+    [NSApp run];
+
+    mg_stop(ctx);
+
+    return EXIT_SUCCESS;
+}
+#else
+int main(int argc, char *argv[])
+{
+    init_server_name();
+    start_civetweb(argc, argv);
+    printf("%s started on port(s) %s with web root [%s]\n",
+           server_name, mg_get_option(ctx, "listening_ports"),
+           mg_get_option(ctx, "document_root"));
+    while (exit_flag == 0) {
+        sleep(1);
+    }
+    printf("Exiting on signal %d, waiting for all threads to finish...",
+           exit_flag);
+    fflush(stdout);
+    mg_stop(ctx);
+    printf("%s", " done.\n");
+
+    return EXIT_SUCCESS;
+}
+#endif /* _WIN32 */
diff --git a/src/civetweb/md5.inl b/src/civetweb/md5.inl
new file mode 100644
index 0000000..4da933d
--- /dev/null
+++ b/src/civetweb/md5.inl
@@ -0,0 +1,461 @@
+/*
+ * This an amalgamation of md5.c and md5.h into a single file
+ * with all static declaration to reduce linker conflicts
+ * in Civetweb.
+ *
+ * The MD5_STATIC declaration was added to facilitate static
+ * inclusion.
+ * No Face Press, LLC
+ */
+
+/* $Id: md5.h,v 1.4 2002/04/13 19:20:28 lpd Exp $ */
+/*
+  Independent implementation of MD5 (RFC 1321).
+
+  This code implements the MD5 Algorithm defined in RFC 1321, whose
+  text is available at
+	http://www.ietf.org/rfc/rfc1321.txt
+  The code is derived from the text of the RFC, including the test suite
+  (section A.5) but excluding the rest of Appendix A.  It does not include
+  any code or documentation that is identified in the RFC as being
+  copyrighted.
+
+  The original and principal author of md5.h is L. Peter Deutsch
+  <ghost@aladdin.com>.  Other authors are noted in the change history
+  that follows (in reverse chronological order):
+
+  2002-04-13 lpd Removed support for non-ANSI compilers; removed
+	references to Ghostscript; clarified derivation from RFC 1321;
+	now handles byte order either statically or dynamically.
+  1999-11-04 lpd Edited comments slightly for automatic TOC extraction.
+  1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5);
+	added conditionalization for C++ compilation from Martin
+	Purschke <purschke@bnl.gov>.
+  1999-05-03 lpd Original version.
+ */
+
+#ifndef md5_INCLUDED
+#  define md5_INCLUDED
+
+/*
+ * This package supports both compile-time and run-time determination of CPU
+ * byte order.  If ARCH_IS_BIG_ENDIAN is defined as 0, the code will be
+ * compiled to run only on little-endian CPUs; if ARCH_IS_BIG_ENDIAN is
+ * defined as non-zero, the code will be compiled to run only on big-endian
+ * CPUs; if ARCH_IS_BIG_ENDIAN is not defined, the code will be compiled to
+ * run on either big- or little-endian CPUs, but will run slightly less
+ * efficiently on either one than if ARCH_IS_BIG_ENDIAN is defined.
+ */
+
+typedef unsigned char md5_byte_t; /* 8-bit byte */
+typedef unsigned int md5_word_t; /* 32-bit word */
+
+/* Define the state of the MD5 Algorithm. */
+typedef struct md5_state_s {
+    md5_word_t count[2];	/* message length in bits, lsw first */
+    md5_word_t abcd[4];		/* digest buffer */
+    md5_byte_t buf[64];		/* accumulate block */
+} md5_state_t;
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/* Initialize the algorithm. */
+MD5_STATIC void md5_init(md5_state_t *pms);
+
+/* Append a string to the message. */
+MD5_STATIC void md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes);
+
+/* Finish the message and return the digest. */
+MD5_STATIC void md5_finish(md5_state_t *pms, md5_byte_t digest[16]);
+
+#ifdef __cplusplus
+}  /* end extern "C" */
+#endif
+
+#endif /* md5_INCLUDED */
+
+/*
+  Copyright (C) 1999, 2000, 2002 Aladdin Enterprises.  All rights reserved.
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+
+  L. Peter Deutsch
+  ghost@aladdin.com
+
+ */
+/* $Id: md5.c,v 1.6 2002/04/13 19:20:28 lpd Exp $ */
+/*
+  Independent implementation of MD5 (RFC 1321).
+
+  This code implements the MD5 Algorithm defined in RFC 1321, whose
+  text is available at
+	http://www.ietf.org/rfc/rfc1321.txt
+  The code is derived from the text of the RFC, including the test suite
+  (section A.5) but excluding the rest of Appendix A.  It does not include
+  any code or documentation that is identified in the RFC as being
+  copyrighted.
+
+  The original and principal author of md5.c is L. Peter Deutsch
+  <ghost@aladdin.com>.  Other authors are noted in the change history
+  that follows (in reverse chronological order):
+
+  2002-04-13 lpd Clarified derivation from RFC 1321; now handles byte order
+	either statically or dynamically; added missing #include <string.h>
+	in library.
+  2002-03-11 lpd Corrected argument list for main(), and added int return
+	type, in test program and T value program.
+  2002-02-21 lpd Added missing #include <stdio.h> in test program.
+  2000-07-03 lpd Patched to eliminate warnings about "constant is
+	unsigned in ANSI C, signed in traditional"; made test program
+	self-checking.
+  1999-11-04 lpd Edited comments slightly for automatic TOC extraction.
+  1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5).
+  1999-05-03 lpd Original version.
+ */
+
+#ifndef MD5_STATIC
+#include <string.h>
+#endif
+
+#undef BYTE_ORDER	/* 1 = big-endian, -1 = little-endian, 0 = unknown */
+#ifdef ARCH_IS_BIG_ENDIAN
+#  define BYTE_ORDER (ARCH_IS_BIG_ENDIAN ? 1 : -1)
+#else
+#  define BYTE_ORDER 0
+#endif
+
+#define T_MASK ((md5_word_t)~0)
+#define T1 /* 0xd76aa478 */ (T_MASK ^ 0x28955b87)
+#define T2 /* 0xe8c7b756 */ (T_MASK ^ 0x173848a9)
+#define T3    0x242070db
+#define T4 /* 0xc1bdceee */ (T_MASK ^ 0x3e423111)
+#define T5 /* 0xf57c0faf */ (T_MASK ^ 0x0a83f050)
+#define T6    0x4787c62a
+#define T7 /* 0xa8304613 */ (T_MASK ^ 0x57cfb9ec)
+#define T8 /* 0xfd469501 */ (T_MASK ^ 0x02b96afe)
+#define T9    0x698098d8
+#define T10 /* 0x8b44f7af */ (T_MASK ^ 0x74bb0850)
+#define T11 /* 0xffff5bb1 */ (T_MASK ^ 0x0000a44e)
+#define T12 /* 0x895cd7be */ (T_MASK ^ 0x76a32841)
+#define T13    0x6b901122
+#define T14 /* 0xfd987193 */ (T_MASK ^ 0x02678e6c)
+#define T15 /* 0xa679438e */ (T_MASK ^ 0x5986bc71)
+#define T16    0x49b40821
+#define T17 /* 0xf61e2562 */ (T_MASK ^ 0x09e1da9d)
+#define T18 /* 0xc040b340 */ (T_MASK ^ 0x3fbf4cbf)
+#define T19    0x265e5a51
+#define T20 /* 0xe9b6c7aa */ (T_MASK ^ 0x16493855)
+#define T21 /* 0xd62f105d */ (T_MASK ^ 0x29d0efa2)
+#define T22    0x02441453
+#define T23 /* 0xd8a1e681 */ (T_MASK ^ 0x275e197e)
+#define T24 /* 0xe7d3fbc8 */ (T_MASK ^ 0x182c0437)
+#define T25    0x21e1cde6
+#define T26 /* 0xc33707d6 */ (T_MASK ^ 0x3cc8f829)
+#define T27 /* 0xf4d50d87 */ (T_MASK ^ 0x0b2af278)
+#define T28    0x455a14ed
+#define T29 /* 0xa9e3e905 */ (T_MASK ^ 0x561c16fa)
+#define T30 /* 0xfcefa3f8 */ (T_MASK ^ 0x03105c07)
+#define T31    0x676f02d9
+#define T32 /* 0x8d2a4c8a */ (T_MASK ^ 0x72d5b375)
+#define T33 /* 0xfffa3942 */ (T_MASK ^ 0x0005c6bd)
+#define T34 /* 0x8771f681 */ (T_MASK ^ 0x788e097e)
+#define T35    0x6d9d6122
+#define T36 /* 0xfde5380c */ (T_MASK ^ 0x021ac7f3)
+#define T37 /* 0xa4beea44 */ (T_MASK ^ 0x5b4115bb)
+#define T38    0x4bdecfa9
+#define T39 /* 0xf6bb4b60 */ (T_MASK ^ 0x0944b49f)
+#define T40 /* 0xbebfbc70 */ (T_MASK ^ 0x4140438f)
+#define T41    0x289b7ec6
+#define T42 /* 0xeaa127fa */ (T_MASK ^ 0x155ed805)
+#define T43 /* 0xd4ef3085 */ (T_MASK ^ 0x2b10cf7a)
+#define T44    0x04881d05
+#define T45 /* 0xd9d4d039 */ (T_MASK ^ 0x262b2fc6)
+#define T46 /* 0xe6db99e5 */ (T_MASK ^ 0x1924661a)
+#define T47    0x1fa27cf8
+#define T48 /* 0xc4ac5665 */ (T_MASK ^ 0x3b53a99a)
+#define T49 /* 0xf4292244 */ (T_MASK ^ 0x0bd6ddbb)
+#define T50    0x432aff97
+#define T51 /* 0xab9423a7 */ (T_MASK ^ 0x546bdc58)
+#define T52 /* 0xfc93a039 */ (T_MASK ^ 0x036c5fc6)
+#define T53    0x655b59c3
+#define T54 /* 0x8f0ccc92 */ (T_MASK ^ 0x70f3336d)
+#define T55 /* 0xffeff47d */ (T_MASK ^ 0x00100b82)
+#define T56 /* 0x85845dd1 */ (T_MASK ^ 0x7a7ba22e)
+#define T57    0x6fa87e4f
+#define T58 /* 0xfe2ce6e0 */ (T_MASK ^ 0x01d3191f)
+#define T59 /* 0xa3014314 */ (T_MASK ^ 0x5cfebceb)
+#define T60    0x4e0811a1
+#define T61 /* 0xf7537e82 */ (T_MASK ^ 0x08ac817d)
+#define T62 /* 0xbd3af235 */ (T_MASK ^ 0x42c50dca)
+#define T63    0x2ad7d2bb
+#define T64 /* 0xeb86d391 */ (T_MASK ^ 0x14792c6e)
+
+
+static void
+md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/)
+{
+    md5_word_t
+    a = pms->abcd[0], b = pms->abcd[1],
+    c = pms->abcd[2], d = pms->abcd[3];
+    md5_word_t t;
+#if BYTE_ORDER > 0
+    /* Define storage only for big-endian CPUs. */
+    md5_word_t X[16];
+#else
+    /* Define storage for little-endian or both types of CPUs. */
+    md5_word_t xbuf[16];
+    const md5_word_t *X;
+#endif
+
+    {
+#if BYTE_ORDER == 0
+        /*
+         * Determine dynamically whether this is a big-endian or
+         * little-endian machine, since we can use a more efficient
+         * algorithm on the latter.
+         */
+        static const int w = 1;
+
+        if (*((const md5_byte_t *)&w)) /* dynamic little-endian */
+#endif
+#if BYTE_ORDER <= 0		/* little-endian */
+        {
+            /*
+             * On little-endian machines, we can process properly aligned
+             * data without copying it.
+             */
+            if (!((data - (const md5_byte_t *)0) & 3)) {
+                /* data are properly aligned */
+                X = (const md5_word_t *)data;
+            } else {
+                /* not aligned */
+                memcpy(xbuf, data, 64);
+                X = xbuf;
+            }
+        }
+#endif
+#if BYTE_ORDER == 0
+        else			/* dynamic big-endian */
+#endif
+#if BYTE_ORDER >= 0		/* big-endian */
+        {
+            /*
+             * On big-endian machines, we must arrange the bytes in the
+             * right order.
+             */
+            const md5_byte_t *xp = data;
+            int i;
+
+#  if BYTE_ORDER == 0
+            X = xbuf;		/* (dynamic only) */
+#  else
+#    define xbuf X		/* (static only) */
+#  endif
+            for (i = 0; i < 16; ++i, xp += 4)
+                xbuf[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24);
+        }
+#endif
+    }
+
+#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n))))
+
+    /* Round 1. */
+    /* Let [abcd k s i] denote the operation
+       a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */
+#define F(x, y, z) (((x) & (y)) | (~(x) & (z)))
+#define SET(a, b, c, d, k, s, Ti)\
+  t = a + F(b,c,d) + X[k] + Ti;\
+  a = ROTATE_LEFT(t, s) + b
+    /* Do the following 16 operations. */
+    SET(a, b, c, d,  0,  7,  T1);
+    SET(d, a, b, c,  1, 12,  T2);
+    SET(c, d, a, b,  2, 17,  T3);
+    SET(b, c, d, a,  3, 22,  T4);
+    SET(a, b, c, d,  4,  7,  T5);
+    SET(d, a, b, c,  5, 12,  T6);
+    SET(c, d, a, b,  6, 17,  T7);
+    SET(b, c, d, a,  7, 22,  T8);
+    SET(a, b, c, d,  8,  7,  T9);
+    SET(d, a, b, c,  9, 12, T10);
+    SET(c, d, a, b, 10, 17, T11);
+    SET(b, c, d, a, 11, 22, T12);
+    SET(a, b, c, d, 12,  7, T13);
+    SET(d, a, b, c, 13, 12, T14);
+    SET(c, d, a, b, 14, 17, T15);
+    SET(b, c, d, a, 15, 22, T16);
+#undef SET
+
+    /* Round 2. */
+    /* Let [abcd k s i] denote the operation
+         a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */
+#define G(x, y, z) (((x) & (z)) | ((y) & ~(z)))
+#define SET(a, b, c, d, k, s, Ti)\
+  t = a + G(b,c,d) + X[k] + Ti;\
+  a = ROTATE_LEFT(t, s) + b
+    /* Do the following 16 operations. */
+    SET(a, b, c, d,  1,  5, T17);
+    SET(d, a, b, c,  6,  9, T18);
+    SET(c, d, a, b, 11, 14, T19);
+    SET(b, c, d, a,  0, 20, T20);
+    SET(a, b, c, d,  5,  5, T21);
+    SET(d, a, b, c, 10,  9, T22);
+    SET(c, d, a, b, 15, 14, T23);
+    SET(b, c, d, a,  4, 20, T24);
+    SET(a, b, c, d,  9,  5, T25);
+    SET(d, a, b, c, 14,  9, T26);
+    SET(c, d, a, b,  3, 14, T27);
+    SET(b, c, d, a,  8, 20, T28);
+    SET(a, b, c, d, 13,  5, T29);
+    SET(d, a, b, c,  2,  9, T30);
+    SET(c, d, a, b,  7, 14, T31);
+    SET(b, c, d, a, 12, 20, T32);
+#undef SET
+
+    /* Round 3. */
+    /* Let [abcd k s t] denote the operation
+         a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */
+#define H(x, y, z) ((x) ^ (y) ^ (z))
+#define SET(a, b, c, d, k, s, Ti)\
+  t = a + H(b,c,d) + X[k] + Ti;\
+  a = ROTATE_LEFT(t, s) + b
+    /* Do the following 16 operations. */
+    SET(a, b, c, d,  5,  4, T33);
+    SET(d, a, b, c,  8, 11, T34);
+    SET(c, d, a, b, 11, 16, T35);
+    SET(b, c, d, a, 14, 23, T36);
+    SET(a, b, c, d,  1,  4, T37);
+    SET(d, a, b, c,  4, 11, T38);
+    SET(c, d, a, b,  7, 16, T39);
+    SET(b, c, d, a, 10, 23, T40);
+    SET(a, b, c, d, 13,  4, T41);
+    SET(d, a, b, c,  0, 11, T42);
+    SET(c, d, a, b,  3, 16, T43);
+    SET(b, c, d, a,  6, 23, T44);
+    SET(a, b, c, d,  9,  4, T45);
+    SET(d, a, b, c, 12, 11, T46);
+    SET(c, d, a, b, 15, 16, T47);
+    SET(b, c, d, a,  2, 23, T48);
+#undef SET
+
+    /* Round 4. */
+    /* Let [abcd k s t] denote the operation
+         a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */
+#define I(x, y, z) ((y) ^ ((x) | ~(z)))
+#define SET(a, b, c, d, k, s, Ti)\
+  t = a + I(b,c,d) + X[k] + Ti;\
+  a = ROTATE_LEFT(t, s) + b
+    /* Do the following 16 operations. */
+    SET(a, b, c, d,  0,  6, T49);
+    SET(d, a, b, c,  7, 10, T50);
+    SET(c, d, a, b, 14, 15, T51);
+    SET(b, c, d, a,  5, 21, T52);
+    SET(a, b, c, d, 12,  6, T53);
+    SET(d, a, b, c,  3, 10, T54);
+    SET(c, d, a, b, 10, 15, T55);
+    SET(b, c, d, a,  1, 21, T56);
+    SET(a, b, c, d,  8,  6, T57);
+    SET(d, a, b, c, 15, 10, T58);
+    SET(c, d, a, b,  6, 15, T59);
+    SET(b, c, d, a, 13, 21, T60);
+    SET(a, b, c, d,  4,  6, T61);
+    SET(d, a, b, c, 11, 10, T62);
+    SET(c, d, a, b,  2, 15, T63);
+    SET(b, c, d, a,  9, 21, T64);
+#undef SET
+
+    /* Then perform the following additions. (That is increment each
+       of the four registers by the value it had before this block
+       was started.) */
+    pms->abcd[0] += a;
+    pms->abcd[1] += b;
+    pms->abcd[2] += c;
+    pms->abcd[3] += d;
+}
+
+MD5_STATIC void
+md5_init(md5_state_t *pms)
+{
+    pms->count[0] = pms->count[1] = 0;
+    pms->abcd[0] = 0x67452301;
+    pms->abcd[1] = /*0xefcdab89*/ T_MASK ^ 0x10325476;
+    pms->abcd[2] = /*0x98badcfe*/ T_MASK ^ 0x67452301;
+    pms->abcd[3] = 0x10325476;
+}
+
+MD5_STATIC void
+md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes)
+{
+    const md5_byte_t *p = data;
+    int left = nbytes;
+    int offset = (pms->count[0] >> 3) & 63;
+    md5_word_t nbits = (md5_word_t)(nbytes << 3);
+
+    if (nbytes <= 0)
+        return;
+
+    /* Update the message length. */
+    pms->count[1] += nbytes >> 29;
+    pms->count[0] += nbits;
+    if (pms->count[0] < nbits)
+        pms->count[1]++;
+
+    /* Process an initial partial block. */
+    if (offset) {
+        int copy = (offset + nbytes > 64 ? 64 - offset : nbytes);
+
+        memcpy(pms->buf + offset, p, copy);
+        if (offset + copy < 64)
+            return;
+        p += copy;
+        left -= copy;
+        md5_process(pms, pms->buf);
+    }
+
+    /* Process full blocks. */
+    for (; left >= 64; p += 64, left -= 64)
+        md5_process(pms, p);
+
+    /* Process a final partial block. */
+    if (left)
+        memcpy(pms->buf, p, left);
+}
+
+MD5_STATIC void
+md5_finish(md5_state_t *pms, md5_byte_t digest[16])
+{
+    static const md5_byte_t pad[64] = {
+        0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+    };
+    md5_byte_t data[8];
+    int i;
+
+    /* Save the length before padding. */
+    for (i = 0; i < 8; ++i)
+        data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3));
+    /* Pad to 56 bytes mod 64. */
+    md5_append(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1);
+    /* Append the length. */
+    md5_append(pms, data, 8);
+    for (i = 0; i < 16; ++i)
+        digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3));
+}
diff --git a/src/freeglut/src/android/fg_internal_android.h b/src/freeglut/src/android/fg_internal_android.h
index 1e7e2de..1888b1b 100644
--- a/src/freeglut/src/android/fg_internal_android.h
+++ b/src/freeglut/src/android/fg_internal_android.h
@@ -31,8 +31,6 @@
 /* Android OpenGL ES is accessed through EGL */
 #include "egl/fg_internal_egl.h"
 
-#include <stdbool.h>
-
 /* -- GLOBAL TYPE DEFINITIONS ---------------------------------------------- */
 /* The structure used by display initialization in freeglut_init.c */
 typedef struct tagSFG_PlatformDisplay SFG_PlatformDisplay;
diff --git a/src/freeglut/src/fg_menu.c b/src/freeglut/src/fg_menu.c
index bbae132..9e20d5d 100644
--- a/src/freeglut/src/fg_menu.c
+++ b/src/freeglut/src/fg_menu.c
@@ -607,7 +607,7 @@
                 fgSetWindow( parent_window );
                 fgStructure.CurrentMenu = active_menu;
 
-                /* Deactivate menu and then call callback (we don't want menu to stay in view while callback is executing) */
+                /* Deactivate menu and then call callback (we don't want menu to stay in view while callback is executing, and user should be able to change menus in callback) */
                 fgDeactivateMenu( parent_window );
                 active_menu->Callback( active_entry->ID );
 
diff --git a/src/freeglut/src/mswin/fg_main_mswin.c b/src/freeglut/src/mswin/fg_main_mswin.c
index 8162a5f..09e397f 100644
--- a/src/freeglut/src/mswin/fg_main_mswin.c
+++ b/src/freeglut/src/mswin/fg_main_mswin.c
@@ -578,6 +578,18 @@
             ( GetKeyState( VK_RMENU    ) < 0 )) ? GLUT_ACTIVE_ALT   : 0 );
 }
 
+/* Check whether a button (VK_*BUTTON) is currently depressed. Returns
+ * non-zero (not necessarily 1) if yes. */
+static SHORT fgGetAsyncKeyState(int vKey)
+{
+    /* MSDN says: "If the most significant bit is set, the key is down, and if
+     * the least significant bit is set, the key was pressed after the previous
+     * call to GetAsyncKeyState." This behavior cannot be relied upon however.
+     * Remove this bit so that we can simply test with ! if key is up.
+     */
+    return GetAsyncKeyState(vKey) & ~1;
+}
+
 static LRESULT fghWindowProcKeyPress(SFG_Window *window, UINT uMsg, GLboolean keydown, WPARAM wParam, LPARAM lParam)
 {
     static unsigned char lControl = 0, lShift = 0, lAlt = 0,
@@ -629,12 +641,12 @@
      * so when we get an alt, shift or control keypress here, we manually check whether it was the left or the right
      */
 #define ASYNC_KEY_EVENT(winKey,glutKey,keyStateVar)\
-    if (!keyStateVar && GetAsyncKeyState ( winKey ))\
+    if (!keyStateVar && fgGetAsyncKeyState ( winKey ))\
     {\
         keypress   = glutKey;\
         keyStateVar = 1;\
     }\
-    else if (keyStateVar && !GetAsyncKeyState ( winKey ))\
+    else if (keyStateVar && !fgGetAsyncKeyState ( winKey ))\
     {\
         keypress   = glutKey;\
         keyStateVar = 0;\
@@ -1237,7 +1249,7 @@
                 SetCapture ( window->Window.Handle ) ;
             setCaptureActive = 1; /* Set to false in WM_CAPTURECHANGED handler */
         }
-        else if (!GetAsyncKeyState(VK_LBUTTON) && !GetAsyncKeyState(VK_MBUTTON) && !GetAsyncKeyState(VK_RBUTTON))
+        else if (!fgGetAsyncKeyState(VK_LBUTTON) && !fgGetAsyncKeyState(VK_MBUTTON) && !fgGetAsyncKeyState(VK_RBUTTON))
           /* Make sure all mouse buttons are released before releasing capture */
           ReleaseCapture () ;
 
diff --git a/src/freeglut/src/x11/fg_init_x11.c b/src/freeglut/src/x11/fg_init_x11.c
index 0df54f2..49aefe6 100644
--- a/src/freeglut/src/x11/fg_init_x11.c
+++ b/src/freeglut/src/x11/fg_init_x11.c
@@ -82,9 +82,9 @@
 			       "fghGetWindowProperty");
 
   if (type_returned != type)
-    {
-      number_of_elements = 0;
-    }
+  {
+    number_of_elements = 0;
+  }
 
   return number_of_elements;
 }
@@ -113,30 +113,30 @@
                                            XA_WINDOW,
                                            (unsigned char **) window_ptr_1);
   if (number_of_windows == 1)
+  {
+    Window ** window_ptr_2;
+
+    window_ptr_2 = malloc(sizeof(Window *));
+
+    /* Check that the window has the same property set to the same value. */
+    number_of_windows = fghGetWindowProperty(**window_ptr_1,
+                                             wm_check,
+                                             XA_WINDOW,
+                                             (unsigned char **) window_ptr_2);
+    if ((number_of_windows == 1) && (**window_ptr_1 == **window_ptr_2))
     {
-      Window ** window_ptr_2;
-
-      window_ptr_2 = malloc(sizeof(Window *));
-
-      /* Check that the window has the same property set to the same value. */
-      number_of_windows = fghGetWindowProperty(**window_ptr_1,
-                                               wm_check,
-                                               XA_WINDOW,
-                                               (unsigned char **) window_ptr_2);
-      if ((number_of_windows == 1) && (**window_ptr_1 == **window_ptr_2))
-      {
-        /* NET WM compliant */
-        net_wm_supported = 1;
-      }
-
-      XFree(*window_ptr_2);
-      free(window_ptr_2);
+      /* NET WM compliant */
+      net_wm_supported = 1;
     }
 
-        XFree(*window_ptr_1);
-        free(window_ptr_1);
+    XFree(*window_ptr_2);
+    free(window_ptr_2);
+  }
 
-        return net_wm_supported;
+  XFree(*window_ptr_1);
+  free(window_ptr_1);
+
+  return net_wm_supported;
 }
 
 /*  Check if "hint" is present in "property" for "window". */
@@ -216,8 +216,12 @@
     /* Create the state and full screen atoms */
     fgDisplay.pDisplay.State           = None;
     fgDisplay.pDisplay.StateFullScreen = None;
+    fgDisplay.pDisplay.NetWMPid        = None;
+    fgDisplay.pDisplay.ClientMachine   = None;
 
-    if (fghNetWMSupported())
+    fgDisplay.pDisplay.NetWMSupported = fghNetWMSupported();
+
+    if (fgDisplay.pDisplay.NetWMSupported)
     {
       const Atom supported = fghGetAtom("_NET_SUPPORTED");
       const Atom state     = fghGetAtom("_NET_WM_STATE");
@@ -236,6 +240,9 @@
           fgDisplay.pDisplay.StateFullScreen = full_screen;
         }
       }
+
+      fgDisplay.pDisplay.NetWMPid = fghGetAtom("_NET_WM_PID");
+      fgDisplay.pDisplay.ClientMachine = fghGetAtom("WM_CLIENT_MACHINE");
     }
 
     /* Get start time */
diff --git a/src/freeglut/src/x11/fg_internal_x11.h b/src/freeglut/src/x11/fg_internal_x11.h
index c195225..cb927bf 100644
--- a/src/freeglut/src/x11/fg_internal_x11.h
+++ b/src/freeglut/src/x11/fg_internal_x11.h
@@ -62,6 +62,9 @@
     Atom            DeleteWindow;       /* The window deletion atom          */
     Atom            State;              /* The state atom                    */
     Atom            StateFullScreen;    /* The full screen atom              */
+    int             NetWMSupported;     /* Flag for EWMH Window Managers     */
+    Atom            NetWMPid;           /* The _NET_WM_PID atom              */
+    Atom            ClientMachine;      /* The client machine name atom      */
 
 #ifdef HAVE_X11_EXTENSIONS_XRANDR_H
     int prev_xsz, prev_ysz;
diff --git a/src/freeglut/src/x11/fg_window_x11.c b/src/freeglut/src/x11/fg_window_x11.c
index 103fed8..2cc2080 100644
--- a/src/freeglut/src/x11/fg_window_x11.c
+++ b/src/freeglut/src/x11/fg_window_x11.c
@@ -28,8 +28,9 @@
 
 #define FREEGLUT_BUILDING_LIB
 #include <GL/freeglut.h>
-#include <limits.h>  /* LONG_MAX */
-#include <unistd.h>  /* usleep */
+#include <limits.h>     /* LONG_MAX */
+#include <unistd.h>     /* usleep, gethostname, getpid */
+#include <sys/types.h>  /* pid_t */
 #include "../fg_internal.h"
 
 #ifdef EGL_VERSION_1_0
@@ -340,6 +341,41 @@
     XSetWMProtocols( fgDisplay.pDisplay.Display, window->Window.Handle,
                      &fgDisplay.pDisplay.DeleteWindow, 1 );
 
+    if (fgDisplay.pDisplay.NetWMSupported
+        && fgDisplay.pDisplay.NetWMPid != None
+        && fgDisplay.pDisplay.ClientMachine != None)
+    {
+      char hostname[HOST_NAME_MAX];
+      pid_t pid = getpid();
+
+      if (pid > 0 && gethostname(hostname, sizeof(hostname)) > -1)
+      {
+        hostname[sizeof(hostname) - 1] = '\0';
+
+        XChangeProperty(
+            fgDisplay.pDisplay.Display,
+            window->Window.Handle,
+            fgDisplay.pDisplay.NetWMPid,
+            XA_CARDINAL,
+            32,
+            PropModeReplace,
+            (unsigned char *) &pid,
+            1
+        );
+
+        XChangeProperty(
+            fgDisplay.pDisplay.Display,
+            window->Window.Handle,
+            fgDisplay.pDisplay.ClientMachine,
+            XA_STRING,
+            8,
+            PropModeReplace,
+            (unsigned char *) hostname,
+            strlen(hostname)
+        );
+      }
+    }
+
 #ifdef EGL_VERSION_1_0
     fghPlatformOpenWindowEGL(window);
 #else
diff --git a/src/glew/include/GL/glxew.h b/src/glew/include/GL/glxew.h
index 5713463..22204fc 100644
--- a/src/glew/include/GL/glxew.h
+++ b/src/glew/include/GL/glxew.h
@@ -889,6 +889,19 @@
 
 #endif /* GLX_NV_copy_image */
 
+/* ------------------------ GLX_NV_delay_before_swap ----------------------- */
+
+#ifndef GLX_NV_delay_before_swap
+#define GLX_NV_delay_before_swap 1
+
+typedef Bool ( * PFNGLXDELAYBEFORESWAPNVPROC) (Display* dpy, GLXDrawable drawable, GLfloat seconds);
+
+#define glXDelayBeforeSwapNV GLXEW_GET_FUN(__glewXDelayBeforeSwapNV)
+
+#define GLXEW_NV_delay_before_swap GLXEW_GET_VAR(__GLXEW_NV_delay_before_swap)
+
+#endif /* GLX_NV_delay_before_swap */
+
 /* -------------------------- GLX_NV_float_buffer -------------------------- */
 
 #ifndef GLX_NV_float_buffer
@@ -1483,6 +1496,8 @@
 
 GLXEW_FUN_EXPORT PFNGLXCOPYIMAGESUBDATANVPROC __glewXCopyImageSubDataNV;
 
+GLXEW_FUN_EXPORT PFNGLXDELAYBEFORESWAPNVPROC __glewXDelayBeforeSwapNV;
+
 GLXEW_FUN_EXPORT PFNGLXBINDVIDEODEVICENVPROC __glewXBindVideoDeviceNV;
 GLXEW_FUN_EXPORT PFNGLXENUMERATEVIDEODEVICESNVPROC __glewXEnumerateVideoDevicesNV;
 
@@ -1607,6 +1622,7 @@
 GLXEW_VAR_EXPORT GLboolean __GLXEW_MESA_set_3dfx_mode;
 GLXEW_VAR_EXPORT GLboolean __GLXEW_MESA_swap_control;
 GLXEW_VAR_EXPORT GLboolean __GLXEW_NV_copy_image;
+GLXEW_VAR_EXPORT GLboolean __GLXEW_NV_delay_before_swap;
 GLXEW_VAR_EXPORT GLboolean __GLXEW_NV_float_buffer;
 GLXEW_VAR_EXPORT GLboolean __GLXEW_NV_multisample_coverage;
 GLXEW_VAR_EXPORT GLboolean __GLXEW_NV_present_video;
diff --git a/src/glew/src/glew.c b/src/glew/src/glew.c
index 3132c6d..20be8f0 100644
--- a/src/glew/src/glew.c
+++ b/src/glew/src/glew.c
@@ -12570,6 +12570,8 @@
 
 PFNGLXCOPYIMAGESUBDATANVPROC __glewXCopyImageSubDataNV = NULL;
 
+PFNGLXDELAYBEFORESWAPNVPROC __glewXDelayBeforeSwapNV = NULL;
+
 PFNGLXBINDVIDEODEVICENVPROC __glewXBindVideoDeviceNV = NULL;
 PFNGLXENUMERATEVIDEODEVICESNVPROC __glewXEnumerateVideoDevicesNV = NULL;
 
@@ -12691,6 +12693,7 @@
 GLboolean __GLXEW_MESA_set_3dfx_mode = GL_FALSE;
 GLboolean __GLXEW_MESA_swap_control = GL_FALSE;
 GLboolean __GLXEW_NV_copy_image = GL_FALSE;
+GLboolean __GLXEW_NV_delay_before_swap = GL_FALSE;
 GLboolean __GLXEW_NV_float_buffer = GL_FALSE;
 GLboolean __GLXEW_NV_multisample_coverage = GL_FALSE;
 GLboolean __GLXEW_NV_present_video = GL_FALSE;
@@ -13034,6 +13037,19 @@
 
 #endif /* GLX_NV_copy_image */
 
+#ifdef GLX_NV_delay_before_swap
+
+static GLboolean _glewInit_GLX_NV_delay_before_swap (GLXEW_CONTEXT_ARG_DEF_INIT)
+{
+  GLboolean r = GL_FALSE;
+
+  r = ((glXDelayBeforeSwapNV = (PFNGLXDELAYBEFORESWAPNVPROC)glewGetProcAddress((const GLubyte*)"glXDelayBeforeSwapNV")) == NULL) || r;
+
+  return r;
+}
+
+#endif /* GLX_NV_delay_before_swap */
+
 #ifdef GLX_NV_float_buffer
 
 #endif /* GLX_NV_float_buffer */
@@ -13515,6 +13531,10 @@
   CONST_CAST(GLXEW_NV_copy_image) = _glewSearchExtension("GLX_NV_copy_image", extStart, extEnd);
   if (glewExperimental || GLXEW_NV_copy_image) CONST_CAST(GLXEW_NV_copy_image) = !_glewInit_GLX_NV_copy_image(GLEW_CONTEXT_ARG_VAR_INIT);
 #endif /* GLX_NV_copy_image */
+#ifdef GLX_NV_delay_before_swap
+  CONST_CAST(GLXEW_NV_delay_before_swap) = _glewSearchExtension("GLX_NV_delay_before_swap", extStart, extEnd);
+  if (glewExperimental || GLXEW_NV_delay_before_swap) CONST_CAST(GLXEW_NV_delay_before_swap) = !_glewInit_GLX_NV_delay_before_swap(GLEW_CONTEXT_ARG_VAR_INIT);
+#endif /* GLX_NV_delay_before_swap */
 #ifdef GLX_NV_float_buffer
   CONST_CAST(GLXEW_NV_float_buffer) = _glewSearchExtension("GLX_NV_float_buffer", extStart, extEnd);
 #endif /* GLX_NV_float_buffer */
@@ -18169,6 +18189,13 @@
           continue;
         }
 #endif
+#ifdef GLX_NV_delay_before_swap
+        if (_glewStrSame3(&pos, &len, (const GLubyte*)"delay_before_swap", 17))
+        {
+          ret = GLXEW_NV_delay_before_swap;
+          continue;
+        }
+#endif
 #ifdef GLX_NV_float_buffer
         if (_glewStrSame3(&pos, &len, (const GLubyte*)"float_buffer", 12))
         {
diff --git a/src/glew/src/glewinfo.c b/src/glew/src/glewinfo.c
index 7c24ed8..4b4b2fd 100644
--- a/src/glew/src/glewinfo.c
+++ b/src/glew/src/glewinfo.c
@@ -8289,6 +8289,17 @@
 
 #endif /* GLX_NV_copy_image */
 
+#ifdef GLX_NV_delay_before_swap
+
+static void _glewInfo_GLX_NV_delay_before_swap (void)
+{
+  glewPrintExt("GLX_NV_delay_before_swap", GLXEW_NV_delay_before_swap, glxewIsSupported("GLX_NV_delay_before_swap"), glxewGetExtension("GLX_NV_delay_before_swap"));
+
+  glewInfoFunc("glXDelayBeforeSwapNV", glXDelayBeforeSwapNV == NULL);
+}
+
+#endif /* GLX_NV_delay_before_swap */
+
 #ifdef GLX_NV_float_buffer
 
 static void _glewInfo_GLX_NV_float_buffer (void)
@@ -10465,6 +10476,9 @@
 #ifdef GLX_NV_copy_image
   _glewInfo_GLX_NV_copy_image();
 #endif /* GLX_NV_copy_image */
+#ifdef GLX_NV_delay_before_swap
+  _glewInfo_GLX_NV_delay_before_swap();
+#endif /* GLX_NV_delay_before_swap */
 #ifdef GLX_NV_float_buffer
   _glewInfo_GLX_NV_float_buffer();
 #endif /* GLX_NV_float_buffer */
diff --git a/src/mongoose/LICENSE.txt b/src/mongoose/LICENSE.txt
deleted file mode 100644
index edb1983..0000000
--- a/src/mongoose/LICENSE.txt
+++ /dev/null
@@ -1,19 +0,0 @@
-Copyright (c) 2004-2013 Sergey Lyubka
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE.
diff --git a/src/mongoose/README.md b/src/mongoose/README.md
deleted file mode 100644
index 0159cbf..0000000
--- a/src/mongoose/README.md
+++ /dev/null
@@ -1,68 +0,0 @@
-# Project Mission
-
-Project mission is to provide simple, functional, embeddable web server to
-make it easy for application and device developers to implement web interface
-for their application and devices, and to offer a simple web development
-environment.
-
-# Overview
-
-To accomplish it's mission, Mongoose keeps balance on functionality and
-simplicity by carefully selected list of features:
-
-- Liberal, commercial-friendly
-  [MIT license](http://en.wikipedia.org/wiki/MIT_License)
-- Works on Windows, Mac, UNIX, iPhone, Android, and many other platforms
-- Support for CGI, SSL, SSI, Digest (MD5) authorization, Websocket, WEbDAV
-- Lua server pages with Sqlite, see
-  [page.lp](https://github.com/valenok/mongoose/blob/master/test/page.lp)
-- Resumed download, URL rewrite, IP-based ACL, Windows service
-- Excluding files from serving by URI pattern (file blacklist)
-- Download speed limit based on client subnet or URI pattern
-- Small footprint: executable size is 50 kB on Linux 2.6 i386 system
-- 130 kilobytes Windows executable with all of the above and no dependencies
-- Simple and clean embedding API,
-  [mongoose.h](https://github.com/valenok/mongoose/blob/master/mongoose.h).
-  The source is in single
-  [mongoose.c](https://github.com/valenok/mongoose/blob/master/mongoose.c) file
-  to make things easy
-- Embedding examples:
-  [hello.c](https://github.com/valenok/mongoose/blob/master/examples/hello.c),
-  [post.c](https://github.com/valenok/mongoose/blob/master/examples/post.c),
-  [upload.c](https://github.com/valenok/mongoose/blob/master/examples/upload.c),
-  [websocket.c](https://github.com/valenok/mongoose/blob/master/examples/websocket.c)
-- HTTP client functionality for embedded usage, capable of
-  sending arbitrary HTTP/HTTPS requests
-- [User Manual](https://github.com/valenok/mongoose/blob/master/UserManual.md)
-
-Continuous build status: ![build status](https://api.travis-ci.org/valenok/mongoose.png)
-
-Questions can be asked at
-[mongoose-users@google.com](http://groups.google.com/group/mongoose-users)
-mailing list.
-
-
-# Keep Sergey happy
-
-I am Sergey Lyubka, a software engineer from Galway, Ireland. I started
-working on Mongoose in 2004, and since then continuously improve it,
-investing thousands of hours of work. My other project I'm contributing to the
-community for free is
-[Super Light Regular Expression library](http://code.google.com/p/slre).
-
-If you feel grateful for the stuff I've done, you can buy me a book from my
-[Amazon wishlist](http://amzn.com/w/1OC2ZCPTQYIEP?sort=priority). Many thanks
-to all who already did so: T.Barmann, D.Hughes, J.C.Sloan, R.Romeo,
-L.E.Spencer, S.Kotay, R.M.Shorter, W.Mar, J.Wilander, Santa from Memphis,
-S.Davies and 8 others.
-Appreciated guys, you keep my brains going! Cash is also welcome indeed.
-Press [<img src="http://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif">](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=DGZ2FMP95TAL6)
-button to donate. Donation progress: 710/1000 &euro;
-(thanks to O.M.Vilhunen, C.Radik, G.Woodcock, M.Szczepkowski,
-Eternal Lands Dev Team, T.Tollet, C.Tangerino, G.Karsai, A.Bourgett,
-C.Blakemore, D.Fonaryov, T.Andrle, O.IJsselmuiden, R.Womack, M.Tomlinson,
-A.Slåttå, L.Farrell, J.D.P.Ballestero, V.Albaev, B.Harker, T.Scheffel, H.Klein,
-R.Merit, T.Bennett, H.Solis, A.Zincenko, M.S., S.Krul, K.Cooke, S.McCallum,
-F.Morenius)
-
-![Progress](http://chart.googleapis.com/chart?chxr=0,0,1000&chxt=x&chbh=30,0,0&chs=300x35&cht=bhs&chco=90c0f0&chd=t:71.0)
diff --git a/src/mongoose/UserManual.md b/src/mongoose/UserManual.md
deleted file mode 100644
index 8590dce..0000000
--- a/src/mongoose/UserManual.md
+++ /dev/null
@@ -1,553 +0,0 @@
-# Overview
-
-Mongoose is small and easy to use web server. It is self-contained, and does
-not require any external software to run.
-
-On Windows, mongoose iconifies itself to the system tray icon when started.
-Right-click on the icon pops up a menu, where it is possible to stop
-mongoose, or configure it, or install it as Windows service. The easiest way
-to share a folder on Windows is to copy `mongoose.exe` to a folder,
-double-click the exe, and launch a browser at
-[http://localhost:8080](http://localhost:8080). Note that 'localhost' should
-be changed to a machine's name if a folder is accessed from other computer.
-
-On UNIX and Mac, mongoose is a command line utility. Running `mongoose` in
-terminal, optionally followed by configuration parameters
-(`mongoose [OPTIONS]`) or configuration file name
-(`mongoose [config_file_name]`) starts the
-web server. Mongoose does not detach from terminal. Pressing `Ctrl-C` keys
-would stop the server.
-
-When started, mongoose first searches for the configuration file.
-If configuration file is specified explicitly in the command line, i.e.
-`mongoose path_to_config_file`, then specified configuration file is used.
-Otherwise, mongoose would search for file `mongoose.conf` in the same directory
-where binary is located, and use it. Configuration file can be absent.
-
-
-Configuration file is a sequence of lines, each line containing
-command line argument name and it's value. Empty lines, and lines beginning
-with `#`, are ignored. Here is the example of `mongoose.conf` file:
-
-    document_root c:\www
-    listening_ports 8080,8043s
-    ssl_certificate c:\mongoose\ssl_cert.pem
-
-When configuration file is processed, mongoose process command line arguments,
-if they are specified. Command line arguments therefore can override
-configuration file settings. Command line arguments must start with `-`.
-For example, if `mongoose.conf` has line
-`document_root /var/www`, and mongoose has been started as
-`mongoose -document_root /etc`, then `/etc` directory will be served as
-document root, because command line options take priority over
-configuration file. Configuration options section below provide a good
-overview of Mongoose features.
-
-Note that configuration options on the command line must start with `-`,
-but their names are the same as in the config file. All option names are
-listed in the next section. Thus, the following two setups are equivalent:
-
-    # Using command line arguments
-    $ mongoose -listening_ports 1234 -document_root /var/www
-
-    # Using config file
-    $ cat mongoose.conf
-    listening_ports 1234
-    document_root /var/www
-    $ mongoose
-
-Mongoose can also be used to modify `.htpasswd` passwords file:
-
-    mongoose -A <htpasswd_file> <realm> <user> <passwd>
-
-Unlike other web servers, mongoose does not require CGI scripts be located in
-a special directory. CGI scripts can be anywhere. CGI (and SSI) files are
-recognized by the file name pattern. Mongoose uses shell-like glob
-patterns. Pattern match starts at the beginning of the string, so essentially
-patterns are prefix patterns. Syntax is as follows:
-
-     **      Matches everything
-     *       Matches everything but slash character, '/'
-     ?       Matches any character
-     $       Matches the end of the string
-     |       Matches if pattern on the left side or the right side matches.
-
-All other characters in the pattern match themselves. Examples:
-
-    **.cgi$      Any string that ends with .cgi
-    /foo         Any string that begins with /foo
-    **a$|**b$    Any string that ends with a or b
-
-# Configuration Options
-
-Below is a list of configuration options Mongoose understands. Every option
-is followed by it's default value. If default value is not present, then
-it is empty.
-
-### cgi_pattern `**.cgi$|**.pl$|**.php$`
-All files that match `cgi_pattern` are treated as CGI files. Default pattern
-allows CGI files be anywhere. To restrict CGIs to a certain directory,
-use `/path/to/cgi-bin/**.cgi` as pattern. Note that full file path is
-matched against the pattern, not the URI.
-
-### cgi_environment
-Extra environment variables to be passed to the CGI script in
-addition to standard ones. The list must be comma-separated list
-of name=value pairs, like this: `VARIABLE1=VALUE1,VARIABLE2=VALUE2`.
-
-### put\_delete\_auth\_file
-Passwords file for PUT and DELETE requests. Without it, PUT and DELETE requests
-will fail.
-
-### cgi_interpreter
-Path to an executable to use as CGI interpreter for __all__ CGI scripts
-regardless script extension. If this option is not set (which is a default),
-Mongoose looks at first line of a CGI script,
-[shebang line](http://en.wikipedia.org/wiki/Shebang_(Unix)), for an interpreter.
-
-For example, if both PHP and perl CGIs are used, then
-`#!/path/to/php-cgi.exe` and `#!/path/to/perl.exe` must be first lines of the
-respective CGI scripts. Note that paths should be either full file paths,
-or file paths relative to the current working directory of mongoose server.
-If mongoose is started by mouse double-click on Windows, current working
-directory is a directory where mongoose executable is located.
-
-If all CGIs use the same interpreter, for example they are all PHP, then
-`cgi_interpreter` can be set to the path to `php-cgi.exe` executable and
-shebang line in the CGI scripts can be omitted.
-Note that PHP scripts must use `php-cgi.exe` executable, not `php.exe`.
-
-### protect_uri
-Comma separated list of URI=PATH pairs, specifying that given
-URIs must be protected with respected password files. Paths must be full
-file paths.
-
-### authentication_domain `mydomain.com`
-Authorization realm used in `.htpasswd` authorization.
-
-### ssi_pattern `**.shtml$|**.shtm$`
-All files that match `ssi_pattern` are treated as SSI.
-
-Server Side Includes (SSI) is a simple interpreted server-side scripting
-language which is most commonly used to include the contents of a file into
-a web page. It can be useful when it is desirable to include a common piece
-of code throughout a website, for example, headers and footers.
-
-In order for a webpage to recognize an SSI-enabled HTML file, the filename
-should end with a special extension, by default the extension should be
-either `.shtml` or `.shtm`.
-
-Unknown SSI directives are silently ignored by mongoose. Currently, two SSI
-directives are supported, `<!--#include ...>` and
-`<!--#exec "command">`. Note that `<!--#include ...>` directive supports
-three path specifications:
-
-    <!--#include virtual="path">  Path is relative to web server root
-    <!--#include file="path">     Path is relative to web server working dir
-    <!--#include "path">          Path is relative to current document
-
-The `include` directive may be used to include the contents of a file or the
-result of running a CGI script. The `exec` directive is used to execute a
-command on a server, and show command's output. Example:
-
-    <!--#exec "ls -l" -->
-
-For more information on Server Side Includes, take a look at the Wikipedia:
-[Server Side Includes](http://en.wikipedia.org/wiki/Server_Side_Includes)
-
-### throttle
-Limit download speed for clients.  `throttle` is a comma-separated
-list of key=value pairs, where key could be:
-
-    *                   limit speed for all connections
-    x.x.x.x/mask        limit speed for specified subnet
-    uri_prefix_pattern  limit speed for given URIs
-
-The value is a floating-point number of bytes per second, optionally
-followed by a `k` or `m` character, meaning kilobytes and
-megabytes respectively. A limit of 0 means unlimited rate. The
-last matching rule wins. Examples:
-
-    *=1k,10.0.0.0/8=0   limit all accesses to 1 kilobyte per second,
-                        but give connections from 10.0.0.0/8 subnet
-                        unlimited speed
-
-    /downloads/=5k      limit accesses to all URIs in `/downloads/` to
-                        5 kilobytes per secods. All other accesses are unlimited
-
-### access\_log\_file
-Path to a file for access logs. Either full path, or relative to current
-working directory. If absent (default), then accesses are not logged.
-
-### error\_log\_file
-Path to a file for error logs. Either full path, or relative to current
-working directory. If absent (default), then errors are not logged.
-
-### enable\_directory\_listing `yes`
-Enable directory listing, either `yes` or `no`.
-
-### enable\_keep\_alive `no`
-Enable connection keep alive, either `yes` or `no`.
-
-Experimental feature. Allows clients to reuse TCP connection for
-subsequent HTTP requests, which improves performance.
-For this to work when using request handlers it's important to add the correct
-Content-Length HTTP header for each request. If this is forgotten the client
-will time out.
-
-
-### global\_auth\_file
-Path to a global passwords file, either full path or relative to the current
-working directory. If set, per-directory `.htpasswd` files are ignored,
-and all requests are authorised against that file.
-
-The file has to include the realm set through `authentication_domain` and the password in digest format:
-
-    user:realm:digest
-    test:test.com:ce0220efc2dd2fad6185e1f1af5a4327
-
-(e.g. use [this generator](http://www.askapache.com/online-tools/htpasswd-generator))
-
-### index_files `index.html,index.htm,index.cgi,index.shtml,index.php`
-Comma-separated list of files to be treated as directory index
-files.
-
-### access\_control\_list
-An Access Control List (ACL) allows restrictions to be put on the list of IP
-addresses which have access to the web server. In the case of the Mongoose
-web server, the ACL is a comma separated list of IP subnets, where each
-subnet is prepended by either a `-` or a `+` sign. A plus sign means allow,
-where a minus sign means deny. If a subnet mask is omitted, such as `-1.2.3.4`,
-this means to deny only that single IP address.
-
-Subnet masks may vary from 0 to 32, inclusive. The default setting is to allow
-all accesses. On each request the full list is traversed, and
-the last match wins. Examples:
-
-    -0.0.0.0/0,+192.168/16    deny all acccesses, only allow 192.168/16 subnet
-
-To learn more about subnet masks, see the
-[Wikipedia page on Subnetwork](http://en.wikipedia.org/wiki/Subnetwork)
-
-### extra\_mime\_types
-Extra mime types to recognize, in form `extension1=type1,exten-
-sion2=type2,...`. Extension must include dot.  Example:
-`.cpp=plain/text,.java=plain/text`
-
-### listening_ports `8080`
-Comma-separated list of ports to listen on. If the port is SSL, a
-letter `s` must be appeneded, for example, `80,443s` will open
-port 80 and port 443, and connections on port 443 will be SSL-ed.
-For non-SSL ports, it is allowed to append letter `r`, meaning 'redirect'.
-Redirect ports will redirect all their traffic to the first configured
-SSL port. For example, if `listening_ports` is `80r,443s`, then all
-HTTP traffic coming at port 80 will be redirected to HTTPS port 443.
-
-It is possible to specify an IP address to bind to. In this case,
-an IP address and a colon must be prepended to the port number.
-For example, to bind to a loopback interface on port 80 and to
-all interfaces on HTTPS port 443, use `127.0.0.1:80,443s`.
-
-### document_root `.`
-A directory to serve. By default, currect directory is served. Current
-directory is commonly referenced as dot (`.`).
-
-### ssl_certificate
-Path to SSL certificate file. This option is only required when at least one
-of the `listening_ports` is SSL. The file must be in PEM format,
-and it must have both private key and certificate, see for example
-[ssl_cert.pem](https://github.com/valenok/mongoose/blob/master/build/ssl_cert.pem)
-
-### num_threads `50`
-Number of worker threads. Mongoose handles each incoming connection in a
-separate thread. Therefore, the value of this option is effectively a number
-of concurrent HTTP connections Mongoose can handle.
-
-### run\_as\_user
-Switch to given user credentials after startup. Usually, this option is
-required when mongoose needs to bind on privileged port on UNIX. To do
-that, mongoose needs to be started as root. But running as root is a bad idea,
-therefore this option can be used to drop privileges. Example:
-
-    mongoose -listening_ports 80 -run_as_user nobody
-
-### url\_rewrite\_patterns
-Comma-separated list of URL rewrites in the form of
-`uri_pattern=file_or_directory_path`. When Mongoose receives the request,
-it constructs the file name to show by combining `document_root` and the URI.
-However, if the rewrite option is used and `uri_pattern` matches the
-requested URI, then `document_root` is ignored. Insted,
-`file_or_directory_path` is used, which should be a full path name or
-a path relative to the web server's current working directory. Note that
-`uri_pattern`, as all mongoose patterns, is a prefix pattern.
-
-This makes it possible to serve many directories outside from `document_root`,
-redirect all requests to scripts, and do other tricky things. For example,
-to redirect all accesses to `.doc` files to a special script, do:
-
-    mongoose -url_rewrite_patterns **.doc$=/path/to/cgi-bin/handle_doc.cgi
-
-Or, to imitate user home directories support, do:
-
-    mongoose -url_rewrite_patterns /~joe/=/home/joe/,/~bill=/home/bill/
-
-### hide\_files\_patterns
-A pattern for the files to hide. Files that match the pattern will not
-show up in directory listing and return `404 Not Found` if requested. Pattern
-must be for a file name only, not including directory name. Example:
-
-    mongoose -hide_files_patterns secret.txt|even_more_secret.txt
-
-# Lua Server Pages
-Pre-built Windows and Mac mongoose binaries have built-in Lua Server Pages
-support. That means it is possible to write PHP-like scripts with mongoose,
-using Lua programming language instead of PHP. Lua is known
-for it's speed and small size. Mongoose uses Lua version 5.2.1, the
-documentation for it can be found at
-[Lua 5.2 reference manual](http://www.lua.org/manual/5.2/).
-
-To create a Lua Page, make sure a file has `.lp` extension. For example,
-let's say it is going to be `my_page.lp`. The contents of the file, just like
-with PHP, is HTML with embedded Lua code. Lua code must be enclosed in
-`<?  ?>` blocks, and can appear anywhere on the page. For example, to
-print current weekday name, one can write:
-
-    <p>
-      <span>Today is:</span>
-      <? mg.write(os.date("%A")) ?>
-    </p>
-
-Note that this example uses function `mg.write()`, which prints data to the
-web page. Using function `mg.write()` is the way to generate web content from
-inside Lua code. In addition to `mg.write()`, all standard library functions
-are accessible from the Lua code (please check reference manual for details),
-and also information about the request is available in `mg.request_info` object,
-like request method, all headers, etcetera. Please refer to
-`struct mg_request_info` definition in
-[mongoose.h](https://github.com/valenok/mongoose/blob/master/mongoose.h)
-to see what kind of information is present in `mg.request_info` object. Also,
-[page.lp](https://github.com/valenok/mongoose/blob/master/test/page.lp) and
-[prime_numbers.lp](https://github.com/valenok/mongoose/blob/master/examples/lua/prime_numbers.lp)
-contains some example code that uses `request_info` and other functions(form submitting for example).
-
-Mongoose exports the following to the Lua server page:
-
-    mg.read()         -- reads a chunk from POST data, returns it as a string
-    mg.write(str)     -- writes string to the client
-    mg.include(path)  -- sources another Lua file
-    mg.redirect(uri)  -- internal redirect to a given URI
-    mg.onerror(msg)   -- error handler, can be overridden
-    mg.version        -- a string that holds Mongoose version
-    mg.request_info   -- a table with request information
-
-    -- Connect to the remote TCP server. This function is an implementation
-    -- of simple socket interface. It returns a socket object with three
-    -- methods: send, recv, close, which are synchronous (blocking).
-    -- connect() throws an exception on connection error.
-    connect(host, port, use_ssl)
-
-    -- Example of using connect() interface:
-    local host = 'code.google.com'  -- IP address or domain name
-    local ok, sock = pcall(connect, host, 80, 1)
-    if ok then
-      sock:send('GET /p/mongoose/ HTTP/1.0\r\n' ..
-                'Host: ' .. host .. '\r\n\r\n')
-      local reply = sock:recv()
-      sock:close()
-      -- reply now contains the web page https://code.google.com/p/mongoose
-    end
-
-
-**IMPORTANT: Mongoose does not send HTTP headers for Lua pages. Therefore,
-every Lua Page must begin with HTTP reply line and headers**, like this:
-
-    <? print('HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n') ?>
-    <html><body>
-      ... the rest of the web page ...
-
-To serve Lua Page, mongoose creates Lua context. That context is used for
-all Lua blocks within the page. That means, all Lua blocks on the same page
-share the same context. If one block defines a variable, for example, that
-variable is visible in the block that follows.
-
-# Common Problems
-- PHP doesn't work - getting empty page, or 'File not found' error. The
-  reason for that is wrong paths to the interpreter. Remember that with PHP,
-  correct interpreter is `php-cgi.exe` (`php-cgi` on UNIX). Solution: specify
-  full path to the PHP interpreter, e.g.:
-    `mongoose -cgi_interpreter /full/path/to/php-cgi`
-
-- Mongoose fails to start. If Mongoose exits immediately when run, this
-  usually indicates a syntax error in the configuration file
-  (named `mongoose.conf` by default) or the command-line arguments.
-  Syntax checking is omitted from Mongoose to keep its size low. However,
-  the Manual should be of help. Note: the syntax changes from time to time,
-  so updating the config file might be necessary after executable update.
-
-- Embedding with OpenSSL on Windows might fail because of calling convention.
-  To force Mongoose to use `__stdcall` convention, add `/Gz` compilation
-  flag in Visual Studio compiler.
-
-# Embedding
-Embedding Mongoose is easy. Copy
-[mongoose.c](https://github.com/valenok/mongoose/blob/master/mongoose.c) and
-[mongoose.h](https://github.com/valenok/mongoose/blob/master/mongoose.h)
-to your application's source tree and include them in the build. For
-example, your application's code lives in C++ file `my_app.cpp`, then on UNIX
-this command embeds Mongoose:
-
-    $ ls
-    my_app.cpp mongoose.c mongoose.h
-    $ g++ my_app.cc mongoose.c -o my_app
-
-Somewhere in the application code, call `mg_start()` to start the server.
-Pass configuration options and event handlers to `mg_start()`.
-Mongoose then calls handlers when certain events happen.
-For example, when new request arrives, Mongoose calls `begin_request`
-handler function to let user handle the request. In the handler, user code
-can get all information about the request -- parsed headers, etcetera.
-
-Mongoose API is logically divided in three categories: server setup/shutdown
-functions, functions to be used by user-written event handlers, and
-convenience utility functions.
-
-### Starting and stopping embedded web server
-To start the embedded web server, call `mg_start()`. To stop it, call
-`mg_stop()`.
-
-    // This structure needs to be passed to mg_start(), to let mongoose know
-    // which callbacks to invoke. For detailed description, see
-    // https://github.com/valenok/mongoose/blob/master/UserManual.md
-    struct mg_callbacks {
-      int  (*begin_request)(struct mg_connection *);
-      void (*end_request)(const struct mg_connection *, int reply_status_code);
-      int  (*log_message)(const struct mg_connection *, const char *message);
-      int  (*init_ssl)(void *ssl_context);
-      int (*websocket_connect)(const struct mg_connection *);
-      void (*websocket_ready)(struct mg_connection *);
-      int  (*websocket_data)(struct mg_connection *);
-      const char * (*open_file)(const struct mg_connection *,
-                                 const char *path, size_t *data_len);
-      void (*init_lua)(struct mg_connection *, void *lua_context);
-      void (*upload)(struct mg_connection *, const char *file_name);
-      int  (*http_error)(struct mg_connection *, int status);
-    };
-
-[hello.c](https://github.com/valenok/mongoose/blob/master/examples/hello.c)
-provides a minimalistic example.
-
-Common pattern is to implement `begin_request` callback, and serve static files
-from memory, and/or construct dynamic replies on the fly. Here is
-my [embed.c](https://gist.github.com/valenok/4714740) gist
-that shows how to easily any data can be embedded
-directly into the executable. If such data needs to be encrypted, then
-encrypted database or encryption dongles would be a better choice.
-
-# Build on Android
-
-This is a small guide to help you run mongoose on Android. Currently it is
-tested on the HTC Wildfire. If you have managed to run it on other devices
-as well, please comment or drop an email in the mailing list.
-Note : You dont need root access to run mongoose on Android.
-
-- Download the source from the Downloads page.
-- Download the Android NDK from
-  [here](http://developer.android.com/tools/sdk/ndk/index.html)
-- Make a folder (e.g. mongoose) and inside that make a folder named "jni".
-- Add `mongoose.h`, `mongoose.c` and `main.c` from the source to the jni folder.
-- Make a new file in the jni folder named "Android.mk".
-  This is the make file for ndk-build.
-
-Android.mk:
-
-    LOCAL_PATH := $(call my-dir)
-    include $(CLEAR_VARS)
-    LOCAL_MODULE    := mongoose
-    LOCAL_SRC_FILES := main.c mongoose.c
-    include $(BUILD_EXECUTABLE)
-
-- Run `./ndk-build -C /path/to/mongoose/`.
-  This should generate mongoose/lib/armeabi/mongoose
-- Using the adb tool, push the generated mongoose binary to `/data/local`
-  folder on device.
-- From adb shell, navigate to `/data/local` and execute `./mongoose`.
-- To test if the server is running fine, visit your web-browser and
-  navigate to `http://127.0.0.1:8080` You should see the `Index of /` page.
-
-![screenshot](https://a248.e.akamai.net/camo.github.com/b88428bf009a2b6141000937ab684e04cc8586af/687474703a2f2f692e696d6775722e636f6d2f62676f6b702e706e67)
-
-
-Notes:
-- jni stands for Java Native Interface. Read up on Android NDK if you want
-  to know how to interact with the native C functions of mongoose in Android
-  Java applications.
-- Download android-sdk for the adb tool.
-- TODO: A Java application that interacts with the native binary or a
-  shared library.
-
-# Mongoose internals
-
-Mongoose is multithreaded web server. `mg_start()` function allocates
-web server context (`struct mg_context`), which holds all information
-about web server instance:
-
-- configuration options. Note that mongoose makes internal copies of
-  passed options.
-- SSL context, if any
-- user-defined callbacks
-- opened listening sockets
-- a queue for accepted sockets
-- mutexes and condition variables for inter-thread synchronization
-
-When `mg_start()` returns, all initialization is quaranteed to be complete
-(e.g. listening ports are opened, SSL is initialized, etc). `mg_start()` starts
-two threads: a master thread, that accepts new connections, and several
-worker threads, that process accepted connections. The number of worker threads
-is configurable via `num_threads` configuration option. That number puts a
-limit on number of simultaneous requests that can be handled by mongoose.
-
-When master thread accepts new connection, a new accepted socket (described by
-`struct socket`) it placed into the accepted sockets queue,
-which has size of 20 (see [code](https://github.com/valenok/mongoose/blob/3892e0199e6ca9613b160535d9d107ede09daa43/mongoose.c#L486)). Any idle worker thread
-can grab accepted sockets from that queue. If all worker threads are busy,
-master thread can accept and queue up to 20 more TCP connections,
-filling up the queue.
-In the attempt to queue next accepted connection, master thread blocks
-until there is space in a queue. When master thread is blocked on a
-full queue, TCP layer in OS can also queue incoming connection.
-The number is limited by the `listen()` call parameter on listening socket,
-which is `SOMAXCONN` in case of Mongoose, and depends on a platform.
-
-Worker threads are running in an infinite loop, which in simplified form
-looks something like this:
-
-    static void *worker_thread() {
-      while (consume_socket()) {
-        process_new_connection();
-      }
-    }
-
-Function `consume_socket()` gets new accepted socket from the mongoose socket
-queue, atomically removing it from the queue. If the queue is empty,
-`consume_socket()` blocks and waits until new sockets are placed in a queue
-by the master thread. `process_new_connection()` actually processes the
-connection, i.e. reads the request, parses it, and performs appropriate action
-depending on a parsed request.
-
-Master thread uses `poll()` and `accept()` to accept new connections on
-listening sockets. `poll()` is used to avoid `FD_SETSIZE` limitation of
-`select()`. Since there are only a few listening sockets, there is no reason
-to use hi-performance alternatives like `epoll()` or `kqueue()`. Worker
-threads use blocking IO on accepted sockets for reading and writing data.
-All accepted sockets have `SO_RCVTIMEO` and `SO_SNDTIMEO` socket options set
-(controlled by `request_timeout_ms` mongoose option, 30 seconds default) which
-specify read/write timeout on client connection.
-
-# Other Resources
-- Presentation made by Arnout Vandecappelle at FOSDEM 2011 on 2011-02-06
-  in Brussels, Belgium, called
-  "Creating secure web based user interfaces for Embedded Devices"
-  ([pdf](http://mind.be/content/110206_Web-ui.pdf) |
-   [odp](http://mind.be/content/110206_Web-ui.odp))
-- Linux Journal article by Michel J.Hammel, 2010-04-01, called
-  [Mongoose: an Embeddable Web Server in C](http://www.linuxjournal.com/article/10680)
diff --git a/src/mongoose/hello.c b/src/mongoose/hello.c
deleted file mode 100644
index 680a012..0000000
--- a/src/mongoose/hello.c
+++ /dev/null
@@ -1,51 +0,0 @@
-#include <stdio.h>
-#include <string.h>
-#include "mongoose.h"
-
-// This function will be called by mongoose on every new request.
-static int begin_request_handler(struct mg_connection *conn) {
-  const struct mg_request_info *request_info = mg_get_request_info(conn);
-  char content[100];
-
-  // Prepare the message we're going to send
-  int content_length = snprintf(content, sizeof(content),
-                                "Hello from mongoose! Remote port: %d",
-                                request_info->remote_port);
-
-  // Send HTTP reply to the client
-  mg_printf(conn,
-            "HTTP/1.1 200 OK\r\n"
-            "Content-Type: text/plain\r\n"
-            "Content-Length: %d\r\n"        // Always set Content-Length
-            "\r\n"
-            "%s",
-            content_length, content);
-
-  // Returning non-zero tells mongoose that our function has replied to
-  // the client, and mongoose should not send client any more data.
-  return 1;
-}
-
-int main(void) {
-  struct mg_context *ctx;
-  struct mg_callbacks callbacks;
-
-  // List of options. Last element must be NULL.
-  const char *options[] = {"listening_ports", "8080", NULL};
-
-  // Prepare callbacks structure. We have only one callback, the rest are NULL.
-  memset(&callbacks, 0, sizeof(callbacks));
-  callbacks.begin_request = begin_request_handler;
-
-  // Start the web server.
-  ctx = mg_start(&callbacks, NULL, options);
-
-  // Wait until user hits "enter". Server is running in separate thread.
-  // Navigating to http://localhost:8080 will invoke begin_request_handler().
-  getchar();
-
-  // Stop the server.
-  mg_stop(ctx);
-
-  return 0;
-}
diff --git a/src/mongoose/main.c b/src/mongoose/main.c
deleted file mode 100644
index 990bbc5..0000000
--- a/src/mongoose/main.c
+++ /dev/null
@@ -1,913 +0,0 @@
-// Copyright (c) 2004-2013 Sergey Lyubka
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-#if defined(_WIN32)
-#define _CRT_SECURE_NO_WARNINGS  // Disable deprecation warning in VS2005
-#else
-#define _XOPEN_SOURCE 600  // For PATH_MAX on linux
-#endif
-
-#include <sys/stat.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <signal.h>
-#include <string.h>
-#include <errno.h>
-#include <limits.h>
-#include <stddef.h>
-#include <stdarg.h>
-#include <ctype.h>
-
-#include "mongoose.h"
-
-#ifdef _WIN32
-#include <windows.h>
-#include <winsvc.h>
-#include <shlobj.h>
-
-#ifndef PATH_MAX
-#define PATH_MAX MAX_PATH
-#endif
-
-#ifndef S_ISDIR
-#define S_ISDIR(x) ((x) & _S_IFDIR)
-#endif
-
-#define DIRSEP '\\'
-#define snprintf _snprintf
-#define vsnprintf _vsnprintf
-#define sleep(x) Sleep((x) * 1000)
-#define WINCDECL __cdecl
-#else
-#include <sys/wait.h>
-#include <unistd.h>
-#define DIRSEP '/'
-#define WINCDECL
-#endif // _WIN32
-
-#define MAX_OPTIONS 100
-#define MAX_CONF_FILE_LINE_SIZE (8 * 1024)
-
-static int exit_flag;
-static char server_name[40];        // Set by init_server_name()
-static char config_file[PATH_MAX];  // Set by process_command_line_arguments()
-static struct mg_context *ctx;      // Set by start_mongoose()
-
-#if !defined(CONFIG_FILE)
-#define CONFIG_FILE "mongoose.conf"
-#endif /* !CONFIG_FILE */
-
-static void WINCDECL signal_handler(int sig_num) {
-  exit_flag = sig_num;
-}
-
-static void die(const char *fmt, ...) {
-  va_list ap;
-  char msg[200];
-
-  va_start(ap, fmt);
-  vsnprintf(msg, sizeof(msg), fmt, ap);
-  va_end(ap);
-
-#if defined(_WIN32)
-  MessageBox(NULL, msg, "Error", MB_OK);
-#else
-  fprintf(stderr, "%s\n", msg);
-#endif
-
-  exit(EXIT_FAILURE);
-}
-
-static void show_usage_and_exit(void) {
-  const char **names;
-  int i;
-
-  fprintf(stderr, "Mongoose version %s (c) Sergey Lyubka, built on %s\n",
-          mg_version(), __DATE__);
-  fprintf(stderr, "Usage:\n");
-  fprintf(stderr, "  mongoose -A <htpasswd_file> <realm> <user> <passwd>\n");
-  fprintf(stderr, "  mongoose [config_file]\n");
-  fprintf(stderr, "  mongoose [-option value ...]\n");
-  fprintf(stderr, "\nOPTIONS:\n");
-
-  names = mg_get_valid_option_names();
-  for (i = 0; names[i] != NULL; i += 2) {
-    fprintf(stderr, "  -%s %s\n",
-            names[i], names[i + 1] == NULL ? "<empty>" : names[i + 1]);
-  }
-  exit(EXIT_FAILURE);
-}
-
-#if defined(_WIN32) || defined(USE_COCOA)
-static const char *config_file_top_comment =
-"# Mongoose web server configuration file.\n"
-"# For detailed description of every option, visit\n"
-"# https://github.com/valenok/mongoose/blob/master/UserManual.md\n"
-"# Lines starting with '#' and empty lines are ignored.\n"
-"# To make a change, remove leading '#', modify option's value,\n"
-"# save this file and then restart Mongoose.\n\n";
-
-static const char *get_url_to_first_open_port(const struct mg_context *ctx) {
-  static char url[100];
-  const char *open_ports = mg_get_option(ctx, "listening_ports");
-  int a, b, c, d, port, n;
-
-  if (sscanf(open_ports, "%d.%d.%d.%d:%d%n", &a, &b, &c, &d, &port, &n) == 5) {
-    snprintf(url, sizeof(url), "%s://%d.%d.%d.%d:%d",
-             open_ports[n] == 's' ? "https" : "http", a, b, c, d, port);
-  } else if (sscanf(open_ports, "%d%n", &port, &n) == 1) {
-    snprintf(url, sizeof(url), "%s://localhost:%d",
-             open_ports[n] == 's' ? "https" : "http", port);
-  } else {
-    snprintf(url, sizeof(url), "%s", "http://localhost:8080");
-  }
-
-  return url;
-}
-
-static void create_config_file(const char *path) {
-  const char **names, *value;
-  FILE *fp;
-  int i;
-
-  // Create config file if it is not present yet
-  if ((fp = fopen(path, "r")) != NULL) {
-    fclose(fp);
-  } else if ((fp = fopen(path, "a+")) != NULL) {
-    fprintf(fp, "%s", config_file_top_comment);
-    names = mg_get_valid_option_names();
-    for (i = 0; names[i * 2] != NULL; i++) {
-      value = mg_get_option(ctx, names[i * 2]);
-      fprintf(fp, "# %s %s\n", names[i * 2], value ? value : "<value>");
-    }
-    fclose(fp);
-  }
-}
-#endif
-
-static void verify_document_root(const char *root) {
-  const char *p, *path;
-  char buf[PATH_MAX];
-  struct stat st;
-
-  path = root;
-  if ((p = strchr(root, ',')) != NULL && (size_t) (p - root) < sizeof(buf)) {
-    memcpy(buf, root, p - root);
-    buf[p - root] = '\0';
-    path = buf;
-  }
-
-  if (stat(path, &st) != 0 || !S_ISDIR(st.st_mode)) {
-    die("Invalid root directory: [%s]: %s", root, strerror(errno));
-  }
-}
-
-static char *sdup(const char *str) {
-  char *p;
-  if ((p = (char *) malloc(strlen(str) + 1)) != NULL) {
-    strcpy(p, str);
-  }
-  return p;
-}
-
-static void set_option(char **options, const char *name, const char *value) {
-  int i;
-
-  if (!strcmp(name, "document_root") || !(strcmp(name, "r"))) {
-    verify_document_root(value);
-  }
-
-  for (i = 0; i < MAX_OPTIONS - 3; i++) {
-    if (options[i] == NULL) {
-      options[i] = sdup(name);
-      options[i + 1] = sdup(value);
-      options[i + 2] = NULL;
-      break;
-    }
-  }
-
-  if (i == MAX_OPTIONS - 3) {
-    die("%s", "Too many options specified");
-  }
-}
-
-static void process_command_line_arguments(char *argv[], char **options) {
-  char line[MAX_CONF_FILE_LINE_SIZE], opt[sizeof(line)], val[sizeof(line)], *p;
-  FILE *fp = NULL;
-  size_t i, cmd_line_opts_start = 1, line_no = 0;
-
-  options[0] = NULL;
-
-  // Should we use a config file ?
-  if (argv[1] != NULL && argv[1][0] != '-') {
-    snprintf(config_file, sizeof(config_file), "%s", argv[1]);
-    cmd_line_opts_start = 2;
-  } else if ((p = strrchr(argv[0], DIRSEP)) == NULL) {
-    // No command line flags specified. Look where binary lives
-    snprintf(config_file, sizeof(config_file), "%s", CONFIG_FILE);
-  } else {
-    snprintf(config_file, sizeof(config_file), "%.*s%c%s",
-             (int) (p - argv[0]), argv[0], DIRSEP, CONFIG_FILE);
-  }
-
-  fp = fopen(config_file, "r");
-
-  // If config file was set in command line and open failed, die
-  if (cmd_line_opts_start == 2 && fp == NULL) {
-    die("Cannot open config file %s: %s", config_file, strerror(errno));
-  }
-
-  // Load config file settings first
-  if (fp != NULL) {
-    fprintf(stderr, "Loading config file %s\n", config_file);
-
-    // Loop over the lines in config file
-    while (fgets(line, sizeof(line), fp) != NULL) {
-      line_no++;
-
-      // Ignore empty lines and comments
-      for (i = 0; isspace(* (unsigned char *) &line[i]); ) i++;
-      if (line[i] == '#' || line[i] == '\0') {
-        continue;
-      }
-
-      if (sscanf(line, "%s %[^\r\n#]", opt, val) != 2) {
-        printf("%s: line %d is invalid, ignoring it:\n %s",
-               config_file, (int) line_no, line);
-      } else {
-        set_option(options, opt, val);
-      }
-    }
-
-    (void) fclose(fp);
-  }
-
-  // If we're under MacOS and started by launchd, then the second
-  // argument is process serial number, -psn_.....
-  // In this case, don't process arguments at all.
-  if (argv[1] == NULL || memcmp(argv[1], "-psn_", 5) != 0) {
-    // Handle command line flags.
-    // They override config file and default settings.
-    for (i = cmd_line_opts_start; argv[i] != NULL; i += 2) {
-      if (argv[i][0] != '-' || argv[i + 1] == NULL) {
-        show_usage_and_exit();
-      }
-      set_option(options, &argv[i][1], argv[i + 1]);
-    }
-  }
-}
-
-static void init_server_name(void) {
-  snprintf(server_name, sizeof(server_name), "Mongoose web server v. %s",
-           mg_version());
-}
-
-static int log_message(const struct mg_connection *conn, const char *message) {
-  (void) conn;
-  printf("%s\n", message);
-  return 0;
-}
-
-static void start_mongoose(int argc, char *argv[]) {
-  struct mg_callbacks callbacks;
-  char *options[MAX_OPTIONS];
-  int i;
-
-  // Edit passwords file if -A option is specified
-  if (argc > 1 && !strcmp(argv[1], "-A")) {
-    if (argc != 6) {
-      show_usage_and_exit();
-    }
-    exit(mg_modify_passwords_file(argv[2], argv[3], argv[4], argv[5]) ?
-         EXIT_SUCCESS : EXIT_FAILURE);
-  }
-
-  // Show usage if -h or --help options are specified
-  if (argc == 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))) {
-    show_usage_and_exit();
-  }
-
-  /* Update config based on command line arguments */
-  process_command_line_arguments(argv, options);
-
-  /* Setup signal handler: quit on Ctrl-C */
-  signal(SIGTERM, signal_handler);
-  signal(SIGINT, signal_handler);
-
-  /* Start Mongoose */
-  memset(&callbacks, 0, sizeof(callbacks));
-  callbacks.log_message = &log_message;
-  ctx = mg_start(&callbacks, NULL, (const char **) options);
-  for (i = 0; options[i] != NULL; i++) {
-    free(options[i]);
-  }
-
-  if (ctx == NULL) {
-    die("%s", "Failed to start Mongoose.");
-  }
-}
-
-#ifdef _WIN32
-enum {
-  ID_ICON = 100, ID_QUIT, ID_SETTINGS, ID_SEPARATOR, ID_INSTALL_SERVICE,
-  ID_REMOVE_SERVICE, ID_STATIC, ID_GROUP, ID_SAVE, ID_RESET_DEFAULTS,
-  ID_STATUS, ID_CONNECT,
-
-  // All dynamically created text boxes for options have IDs starting from
-  // ID_CONTROLS, incremented by one.
-  ID_CONTROLS = 200,
-
-  // Text boxes for files have "..." buttons to open file browser. These
-  // buttons have IDs that are ID_FILE_BUTTONS_DELTA higher than associated
-  // text box ID.
-  ID_FILE_BUTTONS_DELTA = 1000
-};
-static HICON hIcon;
-static SERVICE_STATUS ss;
-static SERVICE_STATUS_HANDLE hStatus;
-static const char *service_magic_argument = "--";
-static NOTIFYICONDATA TrayIcon;
-
-static void WINAPI ControlHandler(DWORD code) {
-  if (code == SERVICE_CONTROL_STOP || code == SERVICE_CONTROL_SHUTDOWN) {
-    ss.dwWin32ExitCode = 0;
-    ss.dwCurrentState = SERVICE_STOPPED;
-  }
-  SetServiceStatus(hStatus, &ss);
-}
-
-static void WINAPI ServiceMain(void) {
-  ss.dwServiceType = SERVICE_WIN32;
-  ss.dwCurrentState = SERVICE_RUNNING;
-  ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
-
-  hStatus = RegisterServiceCtrlHandler(server_name, ControlHandler);
-  SetServiceStatus(hStatus, &ss);
-
-  while (ss.dwCurrentState == SERVICE_RUNNING) {
-    Sleep(1000);
-  }
-  mg_stop(ctx);
-
-  ss.dwCurrentState = SERVICE_STOPPED;
-  ss.dwWin32ExitCode = (DWORD) -1;
-  SetServiceStatus(hStatus, &ss);
-}
-
-
-static void show_error(void) {
-  char buf[256];
-  FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
-                NULL, GetLastError(),
-                MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
-                buf, sizeof(buf), NULL);
-  MessageBox(NULL, buf, "Error", MB_OK);
-}
-
-static void *align(void *ptr, DWORD alig) {
-  ULONG ul = (ULONG) ptr;
-  ul += alig;
-  ul &= ~alig;
-  return ((void *) ul);
-}
-
-static int is_boolean_option(const char *option_name) {
-  return !strcmp(option_name, "enable_directory_listing") ||
-    !strcmp(option_name, "enable_keep_alive");
-}
-
-static int is_filename_option(const char *option_name) {
-  return !strcmp(option_name, "cgi_interpreter") ||
-    !strcmp(option_name, "global_auth_file") ||
-    !strcmp(option_name, "put_delete_auth_file") ||
-    !strcmp(option_name, "access_log_file") ||
-    !strcmp(option_name, "error_log_file") ||
-    !strcmp(option_name, "ssl_certificate");
-}
-
-static int is_directory_option(const char *option_name) {
-  return !strcmp(option_name, "document_root");
-}
-
-static int is_numeric_options(const char *option_name) {
-  return !strcmp(option_name, "num_threads");
-}
-
-static void save_config(HWND hDlg, FILE *fp) {
-  char value[2000];
-  const char **options, *name, *default_value;
-  int i, id;
-
-  fprintf(fp, "%s", config_file_top_comment);
-  options = mg_get_valid_option_names();
-  for (i = 0; options[i * 2] != NULL; i++) {
-    name = options[i * 2];
-    id = ID_CONTROLS + i;
-    if (is_boolean_option(name)) {
-      snprintf(value, sizeof(value), "%s",
-               IsDlgButtonChecked(hDlg, id) ? "yes" : "no");
-    } else {
-      GetDlgItemText(hDlg, id, value, sizeof(value));
-    }
-    default_value = options[i * 2 + 1] == NULL ? "" : options[i * 2 + 1];
-    // If value is the same as default, skip it
-    if (strcmp(value, default_value) != 0) {
-      fprintf(fp, "%s %s\n", name, value);
-    }
-  }
-}
-
-static BOOL CALLBACK DlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP) {
-  FILE *fp;
-  int i;
-  const char *name, *value, **options = mg_get_valid_option_names();
-
-  switch (msg) {
-    case WM_CLOSE:
-      DestroyWindow(hDlg);
-      break;
-
-    case WM_COMMAND:
-      switch (LOWORD(wParam)) {
-        case ID_SAVE:
-          EnableWindow(GetDlgItem(hDlg, ID_SAVE), FALSE);
-          if ((fp = fopen(config_file, "w+")) != NULL) {
-            save_config(hDlg, fp);
-            fclose(fp);
-            mg_stop(ctx);
-            start_mongoose(__argc, __argv);
-          }
-          EnableWindow(GetDlgItem(hDlg, ID_SAVE), TRUE);
-          break;
-        case ID_RESET_DEFAULTS:
-          for (i = 0; options[i * 2] != NULL; i++) {
-            name = options[i * 2];
-            value = options[i * 2 + 1] == NULL ? "" : options[i * 2 + 1];
-            if (is_boolean_option(name)) {
-              CheckDlgButton(hDlg, ID_CONTROLS + i, !strcmp(value, "yes") ?
-                             BST_CHECKED : BST_UNCHECKED);
-            } else {
-              SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), value);
-            }
-          }
-          break;
-      }
-
-      for (i = 0; options[i * 2] != NULL; i++) {
-        name = options[i * 2];
-        if ((is_filename_option(name) || is_directory_option(name)) &&
-            LOWORD(wParam) == ID_CONTROLS + i + ID_FILE_BUTTONS_DELTA) {
-          OPENFILENAME of;
-          BROWSEINFO bi;
-          char path[PATH_MAX] = "";
-
-          memset(&of, 0, sizeof(of));
-          of.lStructSize = sizeof(of);
-          of.hwndOwner = (HWND) hDlg;
-          of.lpstrFile = path;
-          of.nMaxFile = sizeof(path);
-          of.lpstrInitialDir = mg_get_option(ctx, "document_root");
-          of.Flags = OFN_CREATEPROMPT | OFN_NOCHANGEDIR;
-
-          memset(&bi, 0, sizeof(bi));
-          bi.hwndOwner = (HWND) hDlg;
-          bi.lpszTitle = "Choose WWW root directory:";
-          bi.ulFlags = BIF_RETURNONLYFSDIRS;
-
-          if (is_directory_option(name)) {
-            SHGetPathFromIDList(SHBrowseForFolder(&bi), path);
-          } else {
-            GetOpenFileName(&of);
-          }
-
-          if (path[0] != '\0') {
-            SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), path);
-          }
-        }
-      }
-
-      break;
-
-    case WM_INITDIALOG:
-      SendMessage(hDlg, WM_SETICON,(WPARAM) ICON_SMALL, (LPARAM) hIcon);
-      SendMessage(hDlg, WM_SETICON,(WPARAM) ICON_BIG, (LPARAM) hIcon);
-      SetWindowText(hDlg, "Mongoose settings");
-      SetFocus(GetDlgItem(hDlg, ID_SAVE));
-      for (i = 0; options[i * 2] != NULL; i++) {
-        name = options[i * 2];
-        value = mg_get_option(ctx, name);
-        if (is_boolean_option(name)) {
-          CheckDlgButton(hDlg, ID_CONTROLS + i, !strcmp(value, "yes") ?
-                         BST_CHECKED : BST_UNCHECKED);
-        } else {
-          SetDlgItemText(hDlg, ID_CONTROLS + i, value == NULL ? "" : value);
-        }
-      }
-      break;
-    default:
-      break;
-  }
-
-  return FALSE;
-}
-
-static void add_control(unsigned char **mem, DLGTEMPLATE *dia, WORD type,
-                        DWORD id, DWORD style, WORD x, WORD y,
-                        WORD cx, WORD cy, const char *caption) {
-  DLGITEMTEMPLATE *tp;
-  LPWORD p;
-
-  dia->cdit++;
-
-  *mem = align(*mem, 3);
-  tp = (DLGITEMTEMPLATE *) *mem;
-
-  tp->id = (WORD)id;
-  tp->style = style;
-  tp->dwExtendedStyle = 0;
-  tp->x = x;
-  tp->y = y;
-  tp->cx = cx;
-  tp->cy = cy;
-
-  p = align(*mem + sizeof(*tp), 1);
-  *p++ = 0xffff;
-  *p++ = type;
-
-  while (*caption != '\0') {
-    *p++ = (WCHAR) *caption++;
-  }
-  *p++ = 0;
-  p = align(p, 1);
-
-  *p++ = 0;
-  *mem = (unsigned char *) p;
-}
-
-static void show_settings_dialog() {
-#define HEIGHT 15
-#define WIDTH 400
-#define LABEL_WIDTH 80
-
-  unsigned char mem[4096], *p;
-  const char **option_names, *long_option_name;
-  DWORD style;
-  DLGTEMPLATE *dia = (DLGTEMPLATE *) mem;
-  WORD i, cl, x, y, width, nelems = 0;
-  static int guard;
-
-  static struct {
-    DLGTEMPLATE template; // 18 bytes
-    WORD menu, class;
-    wchar_t caption[1];
-    WORD fontsiz;
-    wchar_t fontface[7];
-  } dialog_header = {{WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE |
-    DS_SETFONT | WS_DLGFRAME, WS_EX_TOOLWINDOW, 0, 200, 200, WIDTH, 0},
-    0, 0, L"", 8, L"Tahoma"};
-
-  if (guard == 0) {
-    guard++;
-  } else {
-    return;
-  }
-
-  (void) memset(mem, 0, sizeof(mem));
-  (void) memcpy(mem, &dialog_header, sizeof(dialog_header));
-  p = mem + sizeof(dialog_header);
-
-  option_names = mg_get_valid_option_names();
-  for (i = 0; option_names[i * 2] != NULL; i++) {
-    long_option_name = option_names[i * 2];
-    style = WS_CHILD | WS_VISIBLE | WS_TABSTOP;
-    x = 10 + (WIDTH / 2) * (nelems % 2);
-    y = (nelems/2 + 1) * HEIGHT + 5;
-    width = WIDTH / 2 - 20 - LABEL_WIDTH;
-    if (is_numeric_options(long_option_name)) {
-      style |= ES_NUMBER;
-      cl = 0x81;
-      style |= WS_BORDER | ES_AUTOHSCROLL;
-    } else if (is_boolean_option(long_option_name)) {
-      cl = 0x80;
-      style |= BS_AUTOCHECKBOX;
-    } else if (is_filename_option(long_option_name) ||
-               is_directory_option(long_option_name)) {
-      style |= WS_BORDER | ES_AUTOHSCROLL;
-      width -= 20;
-      cl = 0x81;
-      add_control(&p, dia, 0x80,
-                  ID_CONTROLS + i + ID_FILE_BUTTONS_DELTA,
-                  WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
-                  (WORD) (x + width + LABEL_WIDTH + 5),
-                  y, 15, 12, "...");
-    } else {
-      cl = 0x81;
-      style |= WS_BORDER | ES_AUTOHSCROLL;
-    }
-    add_control(&p, dia, 0x82, ID_STATIC, WS_VISIBLE | WS_CHILD,
-                x, y, LABEL_WIDTH, HEIGHT, long_option_name);
-    add_control(&p, dia, cl, ID_CONTROLS + i, style,
-                (WORD) (x + LABEL_WIDTH), y, width, 12, "");
-    nelems++;
-  }
-
-  y = (WORD) (((nelems + 1) / 2 + 1) * HEIGHT + 5);
-  add_control(&p, dia, 0x80, ID_GROUP, WS_CHILD | WS_VISIBLE |
-              BS_GROUPBOX, 5, 5, WIDTH - 10, y, " Settings ");
-  y += 10;
-  add_control(&p, dia, 0x80, ID_SAVE,
-              WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
-              WIDTH - 70, y, 65, 12, "Save Settings");
-  add_control(&p, dia, 0x80, ID_RESET_DEFAULTS,
-              WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP,
-              WIDTH - 140, y, 65, 12, "Reset to defaults");
-  add_control(&p, dia, 0x82, ID_STATIC,
-              WS_CHILD | WS_VISIBLE | WS_DISABLED,
-              5, y, 180, 12, server_name);
-
-  dia->cy = ((nelems + 1) / 2 + 1) * HEIGHT + 30;
-  DialogBoxIndirectParam(NULL, dia, NULL, DlgProc, (LPARAM) NULL);
-  guard--;
-}
-
-static int manage_service(int action) {
-  static const char *service_name = "Mongoose";
-  SC_HANDLE hSCM = NULL, hService = NULL;
-  SERVICE_DESCRIPTION descr = {server_name};
-  char path[PATH_MAX + 20];  // Path to executable plus magic argument
-  int success = 1;
-
-  if ((hSCM = OpenSCManager(NULL, NULL, action == ID_INSTALL_SERVICE ?
-                            GENERIC_WRITE : GENERIC_READ)) == NULL) {
-    success = 0;
-    show_error();
-  } else if (action == ID_INSTALL_SERVICE) {
-    GetModuleFileName(NULL, path, sizeof(path));
-    strncat(path, " ", sizeof(path));
-    strncat(path, service_magic_argument, sizeof(path));
-    hService = CreateService(hSCM, service_name, service_name,
-                             SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
-                             SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
-                             path, NULL, NULL, NULL, NULL, NULL);
-    if (hService) {
-      ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &descr);
-    } else {
-      show_error();
-    }
-  } else if (action == ID_REMOVE_SERVICE) {
-    if ((hService = OpenService(hSCM, service_name, DELETE)) == NULL ||
-        !DeleteService(hService)) {
-      show_error();
-    }
-  } else if ((hService = OpenService(hSCM, service_name,
-                                     SERVICE_QUERY_STATUS)) == NULL) {
-    success = 0;
-  }
-
-  CloseServiceHandle(hService);
-  CloseServiceHandle(hSCM);
-
-  return success;
-}
-
-static LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam,
-                                   LPARAM lParam) {
-  static SERVICE_TABLE_ENTRY service_table[] = {
-    {server_name, (LPSERVICE_MAIN_FUNCTION) ServiceMain},
-    {NULL, NULL}
-  };
-  int service_installed;
-  char buf[200], *service_argv[] = {__argv[0], NULL};
-  POINT pt;
-  HMENU hMenu;
-  static UINT s_uTaskbarRestart; // for taskbar creation
-
-  switch (msg) {
-    case WM_CREATE:
-      if (__argv[1] != NULL &&
-          !strcmp(__argv[1], service_magic_argument)) {
-        start_mongoose(1, service_argv);
-        StartServiceCtrlDispatcher(service_table);
-        exit(EXIT_SUCCESS);
-      } else {
-        start_mongoose(__argc, __argv);
-        s_uTaskbarRestart = RegisterWindowMessage(TEXT("TaskbarCreated"));
-      }
-      break;
-    case WM_COMMAND:
-      switch (LOWORD(wParam)) {
-        case ID_QUIT:
-          mg_stop(ctx);
-          Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
-          PostQuitMessage(0);
-          return 0;
-        case ID_SETTINGS:
-          show_settings_dialog();
-          break;
-        case ID_INSTALL_SERVICE:
-        case ID_REMOVE_SERVICE:
-          manage_service(LOWORD(wParam));
-          break;
-        case ID_CONNECT:
-          printf("[%s]\n", get_url_to_first_open_port(ctx));
-          ShellExecute(NULL, "open", get_url_to_first_open_port(ctx),
-                       NULL, NULL, SW_SHOW);
-          break;
-      }
-      break;
-    case WM_USER:
-      switch (lParam) {
-        case WM_RBUTTONUP:
-        case WM_LBUTTONUP:
-        case WM_LBUTTONDBLCLK:
-          hMenu = CreatePopupMenu();
-          AppendMenu(hMenu, MF_STRING | MF_GRAYED, ID_SEPARATOR, server_name);
-          AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
-          service_installed = manage_service(0);
-          snprintf(buf, sizeof(buf), "NT service: %s installed",
-                   service_installed ? "" : "not");
-          AppendMenu(hMenu, MF_STRING | MF_GRAYED, ID_SEPARATOR, buf);
-          AppendMenu(hMenu, MF_STRING | (service_installed ? MF_GRAYED : 0),
-                     ID_INSTALL_SERVICE, "Install service");
-          AppendMenu(hMenu, MF_STRING | (!service_installed ? MF_GRAYED : 0),
-                     ID_REMOVE_SERVICE, "Deinstall service");
-          AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
-          AppendMenu(hMenu, MF_STRING, ID_CONNECT, "Start browser");
-          AppendMenu(hMenu, MF_STRING, ID_SETTINGS, "Edit Settings");
-          AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
-          AppendMenu(hMenu, MF_STRING, ID_QUIT, "Exit");
-          GetCursorPos(&pt);
-          SetForegroundWindow(hWnd);
-          TrackPopupMenu(hMenu, 0, pt.x, pt.y, 0, hWnd, NULL);
-          PostMessage(hWnd, WM_NULL, 0, 0);
-          DestroyMenu(hMenu);
-          break;
-      }
-      break;
-    case WM_CLOSE:
-      mg_stop(ctx);
-      Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
-      PostQuitMessage(0);
-      return 0;  // We've just sent our own quit message, with proper hwnd.
-    default:
-      if (msg==s_uTaskbarRestart)
-        Shell_NotifyIcon(NIM_ADD, &TrayIcon);
-  }
-
-  return DefWindowProc(hWnd, msg, wParam, lParam);
-}
-
-int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR cmdline, int show) {
-  WNDCLASS cls;
-  HWND hWnd;
-  MSG msg;
-
-  init_server_name();
-  memset(&cls, 0, sizeof(cls));
-  cls.lpfnWndProc = (WNDPROC) WindowProc;
-  cls.hIcon = LoadIcon(NULL, IDI_APPLICATION);
-  cls.lpszClassName = server_name;
-
-  RegisterClass(&cls);
-  hWnd = CreateWindow(cls.lpszClassName, server_name, WS_OVERLAPPEDWINDOW,
-                      0, 0, 0, 0, NULL, NULL, NULL, NULL);
-  ShowWindow(hWnd, SW_HIDE);
-
-  TrayIcon.cbSize = sizeof(TrayIcon);
-  TrayIcon.uID = ID_ICON;
-  TrayIcon.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
-  TrayIcon.hIcon = hIcon = LoadImage(GetModuleHandle(NULL),
-                                     MAKEINTRESOURCE(ID_ICON),
-                                     IMAGE_ICON, 16, 16, 0);
-  TrayIcon.hWnd = hWnd;
-  snprintf(TrayIcon.szTip, sizeof(TrayIcon.szTip), "%s", server_name);
-  TrayIcon.uCallbackMessage = WM_USER;
-  Shell_NotifyIcon(NIM_ADD, &TrayIcon);
-
-  while (GetMessage(&msg, hWnd, 0, 0) > 0) {
-    TranslateMessage(&msg);
-    DispatchMessage(&msg);
-  }
-
-  // Return the WM_QUIT value.
-  return msg.wParam;
-}
-#elif defined(USE_COCOA)
-#import <Cocoa/Cocoa.h>
-
-@interface Mongoose : NSObject<NSApplicationDelegate>
-- (void) openBrowser;
-- (void) shutDown;
-@end
-
-@implementation Mongoose
-- (void) openBrowser {
-  [[NSWorkspace sharedWorkspace]
-    openURL:[NSURL URLWithString:
-      [NSString stringWithUTF8String:get_url_to_first_open_port(ctx)]]];
-}
-- (void) editConfig {
-  create_config_file(config_file);
-  [[NSWorkspace sharedWorkspace]
-    openFile:[NSString stringWithUTF8String:config_file]
-    withApplication:@"TextEdit"];
-}
-- (void)shutDown{
-  [NSApp terminate:nil];
-}
-@end
-
-int main(int argc, char *argv[]) {
-  init_server_name();
-  start_mongoose(argc, argv);
-
-  [NSAutoreleasePool new];
-  [NSApplication sharedApplication];
-
-  // Add delegate to process menu item actions
-  Mongoose *myDelegate = [[Mongoose alloc] autorelease];
-  [NSApp setDelegate: myDelegate];
-
-  // Run this app as agent
-  ProcessSerialNumber psn = { 0, kCurrentProcess };
-  TransformProcessType(&psn, kProcessTransformToBackgroundApplication);
-  SetFrontProcess(&psn);
-
-  // Add status bar menu
-  id menu = [[NSMenu new] autorelease];
-
-  // Add version menu item
-  [menu addItem:[[[NSMenuItem alloc]
-    //initWithTitle:[NSString stringWithFormat:@"%s", server_name]
-    initWithTitle:[NSString stringWithUTF8String:server_name]
-    action:@selector(noexist) keyEquivalent:@""] autorelease]];
-
-  // Add configuration menu item
-  [menu addItem:[[[NSMenuItem alloc]
-    initWithTitle:@"Edit configuration"
-    action:@selector(editConfig) keyEquivalent:@""] autorelease]];
-
-  // Add connect menu item
-  [menu addItem:[[[NSMenuItem alloc]
-    initWithTitle:@"Open web root in a browser"
-    action:@selector(openBrowser) keyEquivalent:@""] autorelease]];
-
-  // Separator
-  [menu addItem:[NSMenuItem separatorItem]];
-
-  // Add quit menu item
-  [menu addItem:[[[NSMenuItem alloc]
-    initWithTitle:@"Quit"
-    action:@selector(shutDown) keyEquivalent:@"q"] autorelease]];
-
-  // Attach menu to the status bar
-  id item = [[[NSStatusBar systemStatusBar]
-    statusItemWithLength:NSVariableStatusItemLength] retain];
-  [item setHighlightMode:YES];
-  [item setImage:[NSImage imageNamed:@"mongoose_22x22.png"]];
-  [item setMenu:menu];
-
-  // Run the app
-  [NSApp activateIgnoringOtherApps:YES];
-  [NSApp run];
-
-  mg_stop(ctx);
-
-  return EXIT_SUCCESS;
-}
-#else
-int main(int argc, char *argv[]) {
-  init_server_name();
-  start_mongoose(argc, argv);
-  printf("%s started on port(s) %s with web root [%s]\n",
-         server_name, mg_get_option(ctx, "listening_ports"),
-         mg_get_option(ctx, "document_root"));
-  while (exit_flag == 0) {
-    sleep(1);
-  }
-  printf("Exiting on signal %d, waiting for all threads to finish...",
-         exit_flag);
-  fflush(stdout);
-  mg_stop(ctx);
-  printf("%s", " done.\n");
-
-  return EXIT_SUCCESS;
-}
-#endif /* _WIN32 */
diff --git a/src/mongoose/mongoose.1 b/src/mongoose/mongoose.1
deleted file mode 100644
index 4c12445..0000000
--- a/src/mongoose/mongoose.1
+++ /dev/null
@@ -1,184 +0,0 @@
-.\" Process this file with
-.\" groff -man -Tascii mongoose.1
-.\" $Id: mongoose.1,v 1.12 2008/11/29 15:32:42 drozd Exp $
-.Dd Sep 23, 2012
-.Dt mongoose 1
-.Sh NAME
-.Nm mongoose
-.Nd lightweight web server
-.Sh SYNOPSIS
-.Nm
-.Op Ar config_file
-.Op Ar OPTIONS
-.Nm
-.Fl A Ar htpasswd_file domain_name user_name password
-.Sh DESCRIPTION
-.Nm
-is small, fast and easy to use web server with CGI, SSL, MD5 authorization,
-and basic SSI support.
-.Pp
-.Nm
-does not detach from terminal, and uses current working directory
-as the web root, unless
-.Fl r
-option is specified.
-It is possible to specify multiple ports to listen on. For example, to make
-mongoose listen on HTTP port 80 and HTTPS port 443, one should start it as:
-.Nm
-.Fl s Ar cert.pem Fl p Ar 80,443s
-.Pp
-Unlike other web servers,
-.Nm
-does not require CGI scripts be put in a special directory. CGI scripts can
-be anywhere. CGI (and SSI) files are recognized by the file name pattern.
-.Nm
-uses shell-like glob patterns with the following syntax:
-.Bl -tag -compact -width indent
-.It **
-Matches everything
-.It *
-Matches everything but slash character, '/'
-.It ?
-Matches any character
-.It $
-Matches the end of the string
-.It |
-Matches if pattern on the left side or the right side matches. Pattern on the
-left side is matched first
-.El
-All other characters in the pattern match themselves.
-.Pp
-If no arguments are given,
-.Nm
-searches for a configuration file called "mongoose.conf" in the same directory
-where mongoose binary is located. Alternatively, a file name could be
-specified in the command line. Format of the configuration file is the same
-as for the command line options except that each option must be specified
-on a separate line, leading dashes for option names must be omitted.
-Lines beginning with '#' and empty lines are ignored.
-.Pp
-.Sh OPTIONS
-.Bl -tag -width indent
-.It Fl A Ar htpasswd_file domain_name user_name password
-Add/edit user's password in the passwords file. Deleting users can be done
-with any text editor. Functionality is similar to Apache's
-.Ic htdigest
-utility.
-.It Fl C Ar cgi_pattern
-All files that fully match cgi_pattern are treated as CGI.
-Default pattern allows CGI files be
-anywhere. To restrict CGIs to certain directory, use e.g. "-C /cgi-bin/**.cgi".
-Default: "**.cgi$|**.pl$|**.php$"
-.It Fl E Ar cgi_environment
-Extra environment variables to be passed to the CGI script in addition to
-standard ones. The list must be comma-separated list of X=Y pairs, like this:
-"VARIABLE1=VALUE1,VARIABLE2=VALUE2". Default: ""
-.It Fl G Ar put_delete_passwords_file
-PUT and DELETE passwords file. This must be specified if PUT or
-DELETE methods are used. Default: ""
-.It Fl I Ar cgi_interpreter
-Use
-.Ar cgi_interpreter
-as a CGI interpreter for all CGI scripts regardless script extension.
-Mongoose decides which interpreter to use by looking at
-the first line of a CGI script.  Default: "".
-.It Fl P Ar protect_uri
-Comma separated list of URI=PATH pairs, specifying that given URIs
-must be protected with respected password files. Default: ""
-.It Fl R Ar authentication_domain
-Authorization realm. Default: "mydomain.com"
-.It Fl S Ar ssi_pattern
-All files that fully match ssi_pattern are treated as SSI.
-Unknown SSI directives are silently ignored. Currently, two SSI directives
-are supported, "include" and "exec".  Default: "**.shtml$|**.shtm$"
-.It Fl T Ar throttle
-Limit download speed for clients.
-.Ar throttle
-is a comma-separated list of key=value pairs, where
-key could be a '*' character (limit for all connections), a subnet in form
-x.x.x.x/mask (limit for a given subnet, for example 10.0.0.0/8), or an
-URI prefix pattern (limit for the set of URIs, for example /foo/**). The value
-is a floating-point number of bytes per second, optionally followed by a
-`k' or `m' character, meaning kilobytes and megabytes respectively. A limit
-of 0 means unlimited rate. The last matching rule wins. For example,
-"*=1k,10.0.0.0/8" means limit everybody to 1 kilobyte per second, but give
-people from 10/8 subnet unlimited speed. Default: ""
-.It Fl a Ar access_log_file
-Access log file. Default: "", no logging is done.
-.It Fl d Ar enable_directory_listing
-Enable/disable directory listing. Default: "yes"
-.It Fl e Ar error_log_file
-Error log file. Default: "", no errors are logged.
-.It Fl g Ar global_passwords_file
-Location of a global passwords file. If set, per-directory .htpasswd files are
-ignored, and all requests must be authorised against that file.  Default: ""
-.It Fl i Ar index_files
-Comma-separated list of files to be treated as directory index files.
-Default: "index.html,index.htm,index.cgi"
-.It Fl l Ar access_control_list
-Specify access control list (ACL). ACL is a comma separated list
-of IP subnets, each subnet is prepended by '-' or '+' sign. Plus means allow,
-minus means deny. If subnet mask is
-omitted, like "-1.2.3.4", then it means single IP address. Mask may vary
-from 0 to 32 inclusive. On each request, full list is traversed, and
-last match wins. Default setting is to allow all. For example, to allow only
-192.168/16 subnet to connect, run "mongoose -0.0.0.0/0,+192.168/16".
-Default: ""
-.It Fl m Ar extra_mime_types
-Extra mime types to recognize, in form
-"extension1=type1,extension2=type2,...". Extension must include dot.
-Example: "mongoose -m .cpp=plain/text,.java=plain/text". Default: ""
-.It Fl p Ar listening_ports
-Comma-separated list of ports to listen on. If the port is SSL, a letter 's'
-must be appeneded, for example, "-p 80,443s" will open port 80 and port 443,
-and connections on port 443 will be SSL-ed. It is possible to specify an
-IP address to bind to. In this case, an IP address and a colon must be
-prepended to the port number. For example, to bind to a loopback interface
-on port 80 and to all interfaces on HTTPS port 443, use
-"mongoose -p 127.0.0.1:80,443s". Default: "8080"
-.It Fl r Ar document_root
-Location of the WWW root directory. Default: "."
-.It Fl s Ar ssl_certificate
-Location of SSL certificate file. Default: ""
-.It Fl t Ar num_threads
-Number of worker threads to start. Default: "10"
-.It Fl u Ar run_as_user
-Switch to given user's credentials after startup. Default: ""
-.It Fl w Ar url_rewrite_patterns
-Comma-separated list of URL rewrites in the form of
-"pattern=substitution,..." If the "pattern" matches some prefix
-of the requested URL, then matched prefix gets substituted with "substitution".
-For example, "-w /config=/etc,**.doc|**.rtf=/path/to/cgi-bin/handle_doc.cgi"
-will serve all URLs that start with "/config" from the "/etc" directory, and
-call handle_doc.cgi script for .doc and .rtf file requests. If some pattern
-matches, no further matching/substitution is performed
-(first matching pattern wins). Use full paths in substitutions. Default: ""
-.It Fl x Ar hide_files_patterns
-A prefix pattern for the files to hide. Files that match the pattern will not
-show up in directory listing and return 404 Not Found if requested. Default: ""
-.El
-.Pp
-.Sh EMBEDDING
-.Nm
-was designed to be embeddable into C/C++ applications. Since the
-source code is contained in single C file, it is fairly easy to embed it
-and follow the updates. Please refer to http://code.google.com/p/mongoose
-for details.
-.Pp
-.Sh EXAMPLES
-.Bl -tag -width indent
-.It Nm Fl r Ar /var/www Fl s Ar /etc/cert.pem Fl p Ar 8080,8043s
-Start serving files from /var/www. Listen on port 8080 for HTTP, and 8043
-for HTTPS connections.  Use /etc/cert.pem as SSL certificate file.
-.It Nm Fl l Ar -0.0.0.0/0,+10.0.0.0/8,+1.2.3.4
-Deny connections from everywhere, allow only IP address 1.2.3.4 and
-all IP addresses from 10.0.0.0/8 subnet to connect.
-.It Nm Fl w Ar **=/usr/bin/script.cgi
-Invoke /usr/bin/script.cgi for every incoming request, regardless of the URL.
-.El
-.Pp
-.Sh COPYRIGHT
-.Nm
-is licensed under the terms of the MIT license.
-.Sh AUTHOR
-.An Sergey Lyubka Aq valenok@gmail.com .
diff --git a/src/mongoose/mongoose.c b/src/mongoose/mongoose.c
deleted file mode 100644
index 88b6498..0000000
--- a/src/mongoose/mongoose.c
+++ /dev/null
@@ -1,5383 +0,0 @@
-// Copyright (c) 2004-2013 Sergey Lyubka
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-#if defined(_WIN32)
-#if !defined(_CRT_SECURE_NO_WARNINGS)
-#define _CRT_SECURE_NO_WARNINGS // Disable deprecation warning in VS2005
-#endif
-#else
-#ifdef __linux__
-#define _XOPEN_SOURCE 600     // For flockfile() on Linux
-#endif
-#define _LARGEFILE_SOURCE     // Enable 64-bit file offsets
-#define __STDC_FORMAT_MACROS  // <inttypes.h> wants this for C++
-#define __STDC_LIMIT_MACROS   // C++ wants that for INT64_MAX
-#endif
-
-#if defined (_MSC_VER)
-// conditional expression is constant: introduced by FD_SET(..)
-#pragma warning (disable : 4127)
-// non-constant aggregate initializer: issued due to missing C99 support
-#pragma warning (disable : 4204)
-#endif
-
-// Disable WIN32_LEAN_AND_MEAN.
-// This makes windows.h always include winsock2.h
-#ifdef WIN32_LEAN_AND_MEAN
-#undef WIN32_LEAN_AND_MEAN
-#endif
-
-#if defined(__SYMBIAN32__)
-#define NO_SSL // SSL is not supported
-#define NO_CGI // CGI is not supported
-#define PATH_MAX FILENAME_MAX
-#endif // __SYMBIAN32__
-
-#ifndef _WIN32_WCE // Some ANSI #includes are not available on Windows CE
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <errno.h>
-#include <signal.h>
-#include <fcntl.h>
-#endif // !_WIN32_WCE
-
-#include <time.h>
-#include <stdlib.h>
-#include <stdarg.h>
-#include <assert.h>
-#include <string.h>
-#include <ctype.h>
-#include <limits.h>
-#include <stddef.h>
-#include <stdio.h>
-
-#if defined(_WIN32) && !defined(__SYMBIAN32__) // Windows specific
-#undef _WIN32_WINNT
-#define _WIN32_WINNT 0x0400 // To make it link in VS2005
-#include <windows.h>
-
-#ifndef PATH_MAX
-#define PATH_MAX MAX_PATH
-#endif
-
-#ifndef _WIN32_WCE
-#include <process.h>
-#include <direct.h>
-#include <io.h>
-#else // _WIN32_WCE
-#define NO_CGI // WinCE has no pipes
-
-typedef long off_t;
-
-#define errno   GetLastError()
-#define strerror(x)  _ultoa(x, (char *) _alloca(sizeof(x) *3 ), 10)
-#endif // _WIN32_WCE
-
-#define MAKEUQUAD(lo, hi) ((uint64_t)(((uint32_t)(lo)) | \
-      ((uint64_t)((uint32_t)(hi))) << 32))
-#define RATE_DIFF 10000000 // 100 nsecs
-#define EPOCH_DIFF MAKEUQUAD(0xd53e8000, 0x019db1de)
-#define SYS2UNIX_TIME(lo, hi) \
-  (time_t) ((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF)
-
-// Visual Studio 6 does not know __func__ or __FUNCTION__
-// The rest of MS compilers use __FUNCTION__, not C99 __func__
-// Also use _strtoui64 on modern M$ compilers
-#if defined(_MSC_VER) && _MSC_VER < 1300
-#define STRX(x) #x
-#define STR(x) STRX(x)
-#define __func__ __FILE__ ":" STR(__LINE__)
-#define strtoull(x, y, z) (unsigned __int64) _atoi64(x)
-#define strtoll(x, y, z) _atoi64(x)
-#else
-#define __func__  __FUNCTION__
-#define strtoull(x, y, z) _strtoui64(x, y, z)
-#define strtoll(x, y, z) _strtoi64(x, y, z)
-#endif // _MSC_VER
-
-#define ERRNO   GetLastError()
-#define NO_SOCKLEN_T
-#define SSL_LIB   "ssleay32.dll"
-#define CRYPTO_LIB  "libeay32.dll"
-#define O_NONBLOCK  0
-#if !defined(EWOULDBLOCK)
-#define EWOULDBLOCK  WSAEWOULDBLOCK
-#endif // !EWOULDBLOCK
-#define _POSIX_
-#define INT64_FMT  "I64d"
-
-#define WINCDECL __cdecl
-#define SHUT_WR 1
-#define snprintf _snprintf
-#define vsnprintf _vsnprintf
-#define mg_sleep(x) Sleep(x)
-
-#define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
-#ifndef popen
-#define popen(x, y) _popen(x, y)
-#endif
-#ifndef pclose
-#define pclose(x) _pclose(x)
-#endif
-#define close(x) _close(x)
-#define dlsym(x,y) GetProcAddress((HINSTANCE) (x), (y))
-#define RTLD_LAZY  0
-#define fseeko(x, y, z) _lseeki64(_fileno(x), (y), (z))
-#define fdopen(x, y) _fdopen((x), (y))
-#define write(x, y, z) _write((x), (y), (unsigned) z)
-#define read(x, y, z) _read((x), (y), (unsigned) z)
-#define flockfile(x) EnterCriticalSection(&global_log_file_lock)
-#define funlockfile(x) LeaveCriticalSection(&global_log_file_lock)
-#define sleep(x) Sleep((x) * 1000)
-
-#if !defined(va_copy)
-#define va_copy(x, y) x = y
-#endif // !va_copy MINGW #defines va_copy
-
-#if !defined(fileno)
-#define fileno(x) _fileno(x)
-#endif // !fileno MINGW #defines fileno
-
-typedef HANDLE pthread_mutex_t;
-typedef struct {HANDLE signal, broadcast;} pthread_cond_t;
-typedef DWORD pthread_t;
-#define pid_t HANDLE // MINGW typedefs pid_t to int. Using #define here.
-
-static int pthread_mutex_lock(pthread_mutex_t *);
-static int pthread_mutex_unlock(pthread_mutex_t *);
-static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len);
-struct file;
-static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p);
-
-#if defined(HAVE_STDINT)
-#include <stdint.h>
-#else
-typedef unsigned int  uint32_t;
-typedef unsigned short  uint16_t;
-typedef unsigned __int64 uint64_t;
-typedef __int64   int64_t;
-#define INT64_MAX  9223372036854775807
-#endif // HAVE_STDINT
-
-// POSIX dirent interface
-struct dirent {
-  char d_name[PATH_MAX];
-};
-
-typedef struct DIR {
-  HANDLE   handle;
-  WIN32_FIND_DATAW info;
-  struct dirent  result;
-} DIR;
-
-#ifndef HAVE_POLL
-struct pollfd {
-  int fd;
-  short events;
-  short revents;
-};
-#define POLLIN 1
-#endif
-
-
-// Mark required libraries
-#ifdef _MSC_VER
-#pragma comment(lib, "Ws2_32.lib")
-#endif
-
-#else    // UNIX  specific
-#include <sys/wait.h>
-#include <sys/socket.h>
-#include <sys/poll.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-#include <sys/time.h>
-#include <stdint.h>
-#include <inttypes.h>
-#include <netdb.h>
-
-#include <pwd.h>
-#include <unistd.h>
-#include <dirent.h>
-#if !defined(NO_SSL_DL) && !defined(NO_SSL)
-#include <dlfcn.h>
-#endif
-#include <pthread.h>
-#if defined(__MACH__)
-#define SSL_LIB   "libssl.dylib"
-#define CRYPTO_LIB  "libcrypto.dylib"
-#else
-#if !defined(SSL_LIB)
-#define SSL_LIB   "libssl.so"
-#endif
-#if !defined(CRYPTO_LIB)
-#define CRYPTO_LIB  "libcrypto.so"
-#endif
-#endif
-#ifndef O_BINARY
-#define O_BINARY  0
-#endif // O_BINARY
-#define closesocket(a) close(a)
-#define mg_mkdir(x, y) mkdir(x, y)
-#define mg_remove(x) remove(x)
-#define mg_sleep(x) usleep((x) * 1000)
-#define ERRNO errno
-#define INVALID_SOCKET (-1)
-#define INT64_FMT PRId64
-typedef int SOCKET;
-#define WINCDECL
-
-#endif // End of Windows and UNIX specific includes
-
-#include "mongoose.h"
-
-#define MONGOOSE_VERSION "3.8"
-#define PASSWORDS_FILE_NAME ".htpasswd"
-#define CGI_ENVIRONMENT_SIZE 4096
-#define MAX_CGI_ENVIR_VARS 64
-#define MG_BUF_LEN 8192
-#define MAX_REQUEST_SIZE 16384
-#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
-
-#ifdef _WIN32
-static CRITICAL_SECTION global_log_file_lock;
-static pthread_t pthread_self(void) {
-  return GetCurrentThreadId();
-}
-#endif // _WIN32
-
-#ifdef DEBUG_TRACE
-#undef DEBUG_TRACE
-#define DEBUG_TRACE(x)
-#else
-#if defined(DEBUG)
-#define DEBUG_TRACE(x) do { \
-  flockfile(stdout); \
-  printf("*** %lu.%p.%s.%d: ", \
-         (unsigned long) time(NULL), (void *) pthread_self(), \
-         __func__, __LINE__); \
-  printf x; \
-  putchar('\n'); \
-  fflush(stdout); \
-  funlockfile(stdout); \
-} while (0)
-#else
-#define DEBUG_TRACE(x)
-#endif // DEBUG
-#endif // DEBUG_TRACE
-
-// Darwin prior to 7.0 and Win32 do not have socklen_t
-#ifdef NO_SOCKLEN_T
-typedef int socklen_t;
-#endif // NO_SOCKLEN_T
-#define _DARWIN_UNLIMITED_SELECT
-
-#define IP_ADDR_STR_LEN 50  // IPv6 hex string is 46 chars
-
-#if !defined(MSG_NOSIGNAL)
-#define MSG_NOSIGNAL 0
-#endif
-
-#if !defined(SOMAXCONN)
-#define SOMAXCONN 100
-#endif
-
-#if !defined(PATH_MAX)
-#define PATH_MAX 4096
-#endif
-
-static const char *http_500_error = "Internal Server Error";
-
-#if defined(NO_SSL_DL)
-#include <openssl/ssl.h>
-#else
-// SSL loaded dynamically from DLL.
-// I put the prototypes here to be independent from OpenSSL source installation.
-typedef struct ssl_st SSL;
-typedef struct ssl_method_st SSL_METHOD;
-typedef struct ssl_ctx_st SSL_CTX;
-
-struct ssl_func {
-  const char *name;   // SSL function name
-  void  (*ptr)(void); // Function pointer
-};
-
-#define SSL_free (* (void (*)(SSL *)) ssl_sw[0].ptr)
-#define SSL_accept (* (int (*)(SSL *)) ssl_sw[1].ptr)
-#define SSL_connect (* (int (*)(SSL *)) ssl_sw[2].ptr)
-#define SSL_read (* (int (*)(SSL *, void *, int)) ssl_sw[3].ptr)
-#define SSL_write (* (int (*)(SSL *, const void *,int)) ssl_sw[4].ptr)
-#define SSL_get_error (* (int (*)(SSL *, int)) ssl_sw[5].ptr)
-#define SSL_set_fd (* (int (*)(SSL *, SOCKET)) ssl_sw[6].ptr)
-#define SSL_new (* (SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
-#define SSL_CTX_new (* (SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
-#define SSLv23_server_method (* (SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
-#define SSL_library_init (* (int (*)(void)) ssl_sw[10].ptr)
-#define SSL_CTX_use_PrivateKey_file (* (int (*)(SSL_CTX *, \
-        const char *, int)) ssl_sw[11].ptr)
-#define SSL_CTX_use_certificate_file (* (int (*)(SSL_CTX *, \
-        const char *, int)) ssl_sw[12].ptr)
-#define SSL_CTX_set_default_passwd_cb \
-  (* (void (*)(SSL_CTX *, mg_callback_t)) ssl_sw[13].ptr)
-#define SSL_CTX_free (* (void (*)(SSL_CTX *)) ssl_sw[14].ptr)
-#define SSL_load_error_strings (* (void (*)(void)) ssl_sw[15].ptr)
-#define SSL_CTX_use_certificate_chain_file \
-  (* (int (*)(SSL_CTX *, const char *)) ssl_sw[16].ptr)
-#define SSLv23_client_method (* (SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
-#define SSL_pending (* (int (*)(SSL *)) ssl_sw[18].ptr)
-#define SSL_CTX_set_verify (* (void (*)(SSL_CTX *, int, int)) ssl_sw[19].ptr)
-#define SSL_shutdown (* (int (*)(SSL *)) ssl_sw[20].ptr)
-
-#define CRYPTO_num_locks (* (int (*)(void)) crypto_sw[0].ptr)
-#define CRYPTO_set_locking_callback \
-  (* (void (*)(void (*)(int, int, const char *, int))) crypto_sw[1].ptr)
-#define CRYPTO_set_id_callback \
-  (* (void (*)(unsigned long (*)(void))) crypto_sw[2].ptr)
-#define ERR_get_error (* (unsigned long (*)(void)) crypto_sw[3].ptr)
-#define ERR_error_string (* (char * (*)(unsigned long,char *)) crypto_sw[4].ptr)
-
-// set_ssl_option() function updates this array.
-// It loads SSL library dynamically and changes NULLs to the actual addresses
-// of respective functions. The macros above (like SSL_connect()) are really
-// just calling these functions indirectly via the pointer.
-static struct ssl_func ssl_sw[] = {
-  {"SSL_free",   NULL},
-  {"SSL_accept",   NULL},
-  {"SSL_connect",   NULL},
-  {"SSL_read",   NULL},
-  {"SSL_write",   NULL},
-  {"SSL_get_error",  NULL},
-  {"SSL_set_fd",   NULL},
-  {"SSL_new",   NULL},
-  {"SSL_CTX_new",   NULL},
-  {"SSLv23_server_method", NULL},
-  {"SSL_library_init",  NULL},
-  {"SSL_CTX_use_PrivateKey_file", NULL},
-  {"SSL_CTX_use_certificate_file",NULL},
-  {"SSL_CTX_set_default_passwd_cb",NULL},
-  {"SSL_CTX_free",  NULL},
-  {"SSL_load_error_strings", NULL},
-  {"SSL_CTX_use_certificate_chain_file", NULL},
-  {"SSLv23_client_method", NULL},
-  {"SSL_pending", NULL},
-  {"SSL_CTX_set_verify", NULL},
-  {"SSL_shutdown",   NULL},
-  {NULL,    NULL}
-};
-
-// Similar array as ssl_sw. These functions could be located in different lib.
-#if !defined(NO_SSL)
-static struct ssl_func crypto_sw[] = {
-  {"CRYPTO_num_locks",  NULL},
-  {"CRYPTO_set_locking_callback", NULL},
-  {"CRYPTO_set_id_callback", NULL},
-  {"ERR_get_error",  NULL},
-  {"ERR_error_string", NULL},
-  {NULL,    NULL}
-};
-#endif // NO_SSL
-#endif // NO_SSL_DL
-
-static const char *month_names[] = {
-  "Jan", "Feb", "Mar", "Apr", "May", "Jun",
-  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
-};
-
-// Unified socket address. For IPv6 support, add IPv6 address structure
-// in the union u.
-union usa {
-  struct sockaddr sa;
-  struct sockaddr_in sin;
-#if defined(USE_IPV6)
-  struct sockaddr_in6 sin6;
-#endif
-};
-
-// Describes a string (chunk of memory).
-struct vec {
-  const char *ptr;
-  size_t len;
-};
-
-struct file {
-  int is_directory;
-  time_t modification_time;
-  int64_t size;
-  FILE *fp;
-  const char *membuf;   // Non-NULL if file data is in memory
-  // set to 1 if the content is gzipped
-  // in which case we need a content-encoding: gzip header
-  int gzipped;
-};
-#define STRUCT_FILE_INITIALIZER {0, 0, 0, NULL, NULL, 0}
-
-// Describes listening socket, or socket which was accept()-ed by the master
-// thread and queued for future handling by the worker thread.
-struct socket {
-  SOCKET sock;          // Listening socket
-  union usa lsa;        // Local socket address
-  union usa rsa;        // Remote socket address
-  unsigned is_ssl:1;    // Is port SSL-ed
-  unsigned ssl_redir:1; // Is port supposed to redirect everything to SSL port
-};
-
-// NOTE(lsm): this enum shoulds be in sync with the config_options below.
-enum {
-  CGI_EXTENSIONS, CGI_ENVIRONMENT, PUT_DELETE_PASSWORDS_FILE, CGI_INTERPRETER,
-  PROTECT_URI, AUTHENTICATION_DOMAIN, SSI_EXTENSIONS, THROTTLE,
-  ACCESS_LOG_FILE, ENABLE_DIRECTORY_LISTING, ERROR_LOG_FILE,
-  GLOBAL_PASSWORDS_FILE, INDEX_FILES, ENABLE_KEEP_ALIVE, ACCESS_CONTROL_LIST,
-  EXTRA_MIME_TYPES, LISTENING_PORTS, DOCUMENT_ROOT, SSL_CERTIFICATE,
-  NUM_THREADS, RUN_AS_USER, REWRITE, HIDE_FILES, REQUEST_TIMEOUT,
-  NUM_OPTIONS
-};
-
-static const char *config_options[] = {
-  "cgi_pattern", "**.cgi$|**.pl$|**.php$",
-  "cgi_environment", NULL,
-  "put_delete_auth_file", NULL,
-  "cgi_interpreter", NULL,
-  "protect_uri", NULL,
-  "authentication_domain", "mydomain.com",
-  "ssi_pattern", "**.shtml$|**.shtm$",
-  "throttle", NULL,
-  "access_log_file", NULL,
-  "enable_directory_listing", "yes",
-  "error_log_file", NULL,
-  "global_auth_file", NULL,
-  "index_files",
-    "index.html,index.htm,index.cgi,index.shtml,index.php,index.lp",
-  "enable_keep_alive", "no",
-  "access_control_list", NULL,
-  "extra_mime_types", NULL,
-  "listening_ports", "8080",
-  "document_root",  ".",
-  "ssl_certificate", NULL,
-  "num_threads", "50",
-  "run_as_user", NULL,
-  "url_rewrite_patterns", NULL,
-  "hide_files_patterns", NULL,
-  "request_timeout_ms", "30000",
-  NULL
-};
-
-struct mg_context {
-  volatile int stop_flag;         // Should we stop event loop
-  SSL_CTX *ssl_ctx;               // SSL context
-  char *config[NUM_OPTIONS];      // Mongoose configuration parameters
-  struct mg_callbacks callbacks;  // User-defined callback function
-  void *user_data;                // User-defined data
-
-  struct socket *listening_sockets;
-  int num_listening_sockets;
-
-  volatile int num_threads;  // Number of threads
-  pthread_mutex_t mutex;     // Protects (max|num)_threads
-  pthread_cond_t  cond;      // Condvar for tracking workers terminations
-
-  struct socket queue[20];   // Accepted sockets
-  volatile int sq_head;      // Head of the socket queue
-  volatile int sq_tail;      // Tail of the socket queue
-  pthread_cond_t sq_full;    // Signaled when socket is produced
-  pthread_cond_t sq_empty;   // Signaled when socket is consumed
-};
-
-struct mg_connection {
-  struct mg_request_info request_info;
-  struct mg_context *ctx;
-  SSL *ssl;                   // SSL descriptor
-  SSL_CTX *client_ssl_ctx;    // SSL context for client connections
-  struct socket client;       // Connected client
-  time_t birth_time;          // Time when request was received
-  int64_t num_bytes_sent;     // Total bytes sent to client
-  int64_t content_len;        // Content-Length header value
-  int64_t consumed_content;   // How many bytes of content have been read
-  char *buf;                  // Buffer for received data
-  char *path_info;            // PATH_INFO part of the URL
-  int must_close;             // 1 if connection must be closed
-  int buf_size;               // Buffer size
-  int request_len;            // Size of the request + headers in a buffer
-  int data_len;               // Total size of data in a buffer
-  int status_code;            // HTTP reply status code, e.g. 200
-  int throttle;               // Throttling, bytes/sec. <= 0 means no throttle
-  time_t last_throttle_time;  // Last time throttled data was sent
-  int64_t last_throttle_bytes;// Bytes sent this second
-};
-
-// Directory entry
-struct de {
-  struct mg_connection *conn;
-  char *file_name;
-  struct file file;
-};
-
-const char **mg_get_valid_option_names(void) {
-  return config_options;
-}
-
-static int is_file_in_memory(struct mg_connection *conn, const char *path,
-                             struct file *filep) {
-  size_t size = 0;
-  if ((filep->membuf = conn->ctx->callbacks.open_file == NULL ? NULL :
-       conn->ctx->callbacks.open_file(conn, path, &size)) != NULL) {
-    // NOTE: override filep->size only on success. Otherwise, it might break
-    // constructs like if (!mg_stat() || !mg_fopen()) ...
-    filep->size = size;
-  }
-  return filep->membuf != NULL;
-}
-
-static int is_file_opened(const struct file *filep) {
-  return filep->membuf != NULL || filep->fp != NULL;
-}
-
-static int mg_fopen(struct mg_connection *conn, const char *path,
-                    const char *mode, struct file *filep) {
-  if (!is_file_in_memory(conn, path, filep)) {
-#ifdef _WIN32
-    wchar_t wbuf[PATH_MAX], wmode[20];
-    to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
-    MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
-    filep->fp = _wfopen(wbuf, wmode);
-#else
-    filep->fp = fopen(path, mode);
-#endif
-  }
-
-  return is_file_opened(filep);
-}
-
-static void mg_fclose(struct file *filep) {
-  if (filep != NULL && filep->fp != NULL) {
-    fclose(filep->fp);
-  }
-}
-
-static int get_option_index(const char *name) {
-  int i;
-
-  for (i = 0; config_options[i * 2] != NULL; i++) {
-    if (strcmp(config_options[i * 2], name) == 0) {
-      return i;
-    }
-  }
-  return -1;
-}
-
-const char *mg_get_option(const struct mg_context *ctx, const char *name) {
-  int i;
-  if ((i = get_option_index(name)) == -1) {
-    return NULL;
-  } else if (ctx->config[i] == NULL) {
-    return "";
-  } else {
-    return ctx->config[i];
-  }
-}
-
-static void sockaddr_to_string(char *buf, size_t len,
-                                     const union usa *usa) {
-  buf[0] = '\0';
-#if defined(USE_IPV6)
-  inet_ntop(usa->sa.sa_family, usa->sa.sa_family == AF_INET ?
-            (void *) &usa->sin.sin_addr :
-            (void *) &usa->sin6.sin6_addr, buf, len);
-#elif defined(_WIN32)
-  // Only Windoze Vista (and newer) have inet_ntop()
-  strncpy(buf, inet_ntoa(usa->sin.sin_addr), len);
-#else
-  inet_ntop(usa->sa.sa_family, (void *) &usa->sin.sin_addr, buf, len);
-#endif
-}
-
-static void cry(struct mg_connection *conn,
-                PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(2, 3);
-
-// Print error message to the opened error log stream.
-static void cry(struct mg_connection *conn, const char *fmt, ...) {
-  char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
-  va_list ap;
-  FILE *fp;
-  time_t timestamp;
-
-  va_start(ap, fmt);
-  (void) vsnprintf(buf, sizeof(buf), fmt, ap);
-  va_end(ap);
-
-  // Do not lock when getting the callback value, here and below.
-  // I suppose this is fine, since function cannot disappear in the
-  // same way string option can.
-  if (conn->ctx->callbacks.log_message == NULL ||
-      conn->ctx->callbacks.log_message(conn, buf) == 0) {
-    fp = conn->ctx == NULL || conn->ctx->config[ERROR_LOG_FILE] == NULL ? NULL :
-      fopen(conn->ctx->config[ERROR_LOG_FILE], "a+");
-
-    if (fp != NULL) {
-      flockfile(fp);
-      timestamp = time(NULL);
-
-      sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
-      fprintf(fp, "[%010lu] [error] [client %s] ", (unsigned long) timestamp,
-              src_addr);
-
-      if (conn->request_info.request_method != NULL) {
-        fprintf(fp, "%s %s: ", conn->request_info.request_method,
-                conn->request_info.uri);
-      }
-
-      fprintf(fp, "%s", buf);
-      fputc('\n', fp);
-      funlockfile(fp);
-      fclose(fp);
-    }
-  }
-}
-
-// Return fake connection structure. Used for logging, if connection
-// is not applicable at the moment of logging.
-static struct mg_connection *fc(struct mg_context *ctx) {
-  static struct mg_connection fake_connection;
-  fake_connection.ctx = ctx;
-  return &fake_connection;
-}
-
-const char *mg_version(void) {
-  return MONGOOSE_VERSION;
-}
-
-struct mg_request_info *mg_get_request_info(struct mg_connection *conn) {
-  return &conn->request_info;
-}
-
-static void mg_strlcpy(register char *dst, register const char *src, size_t n) {
-  for (; *src != '\0' && n > 1; n--) {
-    *dst++ = *src++;
-  }
-  *dst = '\0';
-}
-
-static int lowercase(const char *s) {
-  return tolower(* (const unsigned char *) s);
-}
-
-static int mg_strncasecmp(const char *s1, const char *s2, size_t len) {
-  int diff = 0;
-
-  if (len > 0)
-    do {
-      diff = lowercase(s1++) - lowercase(s2++);
-    } while (diff == 0 && s1[-1] != '\0' && --len > 0);
-
-  return diff;
-}
-
-static int mg_strcasecmp(const char *s1, const char *s2) {
-  int diff;
-
-  do {
-    diff = lowercase(s1++) - lowercase(s2++);
-  } while (diff == 0 && s1[-1] != '\0');
-
-  return diff;
-}
-
-static char * mg_strndup(const char *ptr, size_t len) {
-  char *p;
-
-  if ((p = (char *) malloc(len + 1)) != NULL) {
-    mg_strlcpy(p, ptr, len + 1);
-  }
-
-  return p;
-}
-
-static char * mg_strdup(const char *str) {
-  return mg_strndup(str, strlen(str));
-}
-
-static const char *mg_strcasestr(const char *big_str, const char *small_str) {
-  int i, big_len = strlen(big_str), small_len = strlen(small_str);
-
-  for (i = 0; i <= big_len - small_len; i++) {
-    if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
-      return big_str + i;
-    }
-  }
-
-  return NULL;
-}
-
-// Like snprintf(), but never returns negative value, or a value
-// that is larger than a supplied buffer.
-// Thanks to Adam Zeldis to pointing snprintf()-caused vulnerability
-// in his audit report.
-static int mg_vsnprintf(struct mg_connection *conn, char *buf, size_t buflen,
-                        const char *fmt, va_list ap) {
-  int n;
-
-  if (buflen == 0)
-    return 0;
-
-  n = vsnprintf(buf, buflen, fmt, ap);
-
-  if (n < 0) {
-    cry(conn, "vsnprintf error");
-    n = 0;
-  } else if (n >= (int) buflen) {
-    cry(conn, "truncating vsnprintf buffer: [%.*s]",
-        n > 200 ? 200 : n, buf);
-    n = (int) buflen - 1;
-  }
-  buf[n] = '\0';
-
-  return n;
-}
-
-static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,
-                       PRINTF_FORMAT_STRING(const char *fmt), ...)
-  PRINTF_ARGS(4, 5);
-
-static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,
-                       const char *fmt, ...) {
-  va_list ap;
-  int n;
-
-  va_start(ap, fmt);
-  n = mg_vsnprintf(conn, buf, buflen, fmt, ap);
-  va_end(ap);
-
-  return n;
-}
-
-// Skip the characters until one of the delimiters characters found.
-// 0-terminate resulting word. Skip the delimiter and following whitespaces.
-// Advance pointer to buffer to the next word. Return found 0-terminated word.
-// Delimiters can be quoted with quotechar.
-static char *skip_quoted(char **buf, const char *delimiters,
-                         const char *whitespace, char quotechar) {
-  char *p, *begin_word, *end_word, *end_whitespace;
-
-  begin_word = *buf;
-  end_word = begin_word + strcspn(begin_word, delimiters);
-
-  // Check for quotechar
-  if (end_word > begin_word) {
-    p = end_word - 1;
-    while (*p == quotechar) {
-      // If there is anything beyond end_word, copy it
-      if (*end_word == '\0') {
-        *p = '\0';
-        break;
-      } else {
-        size_t end_off = strcspn(end_word + 1, delimiters);
-        memmove (p, end_word, end_off + 1);
-        p += end_off; // p must correspond to end_word - 1
-        end_word += end_off + 1;
-      }
-    }
-    for (p++; p < end_word; p++) {
-      *p = '\0';
-    }
-  }
-
-  if (*end_word == '\0') {
-    *buf = end_word;
-  } else {
-    end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
-
-    for (p = end_word; p < end_whitespace; p++) {
-      *p = '\0';
-    }
-
-    *buf = end_whitespace;
-  }
-
-  return begin_word;
-}
-
-// Simplified version of skip_quoted without quote char
-// and whitespace == delimiters
-static char *skip(char **buf, const char *delimiters) {
-  return skip_quoted(buf, delimiters, delimiters, 0);
-}
-
-
-// Return HTTP header value, or NULL if not found.
-static const char *get_header(const struct mg_request_info *ri,
-                              const char *name) {
-  int i;
-
-  for (i = 0; i < ri->num_headers; i++)
-    if (!mg_strcasecmp(name, ri->http_headers[i].name))
-      return ri->http_headers[i].value;
-
-  return NULL;
-}
-
-const char *mg_get_header(const struct mg_connection *conn, const char *name) {
-  return get_header(&conn->request_info, name);
-}
-
-// A helper function for traversing a comma separated list of values.
-// It returns a list pointer shifted to the next value, or NULL if the end
-// of the list found.
-// Value is stored in val vector. If value has form "x=y", then eq_val
-// vector is initialized to point to the "y" part, and val vector length
-// is adjusted to point only to "x".
-static const char *next_option(const char *list, struct vec *val,
-                               struct vec *eq_val) {
-  if (list == NULL || *list == '\0') {
-    // End of the list
-    list = NULL;
-  } else {
-    val->ptr = list;
-    if ((list = strchr(val->ptr, ',')) != NULL) {
-      // Comma found. Store length and shift the list ptr
-      val->len = list - val->ptr;
-      list++;
-    } else {
-      // This value is the last one
-      list = val->ptr + strlen(val->ptr);
-      val->len = list - val->ptr;
-    }
-
-    if (eq_val != NULL) {
-      // Value has form "x=y", adjust pointers and lengths
-      // so that val points to "x", and eq_val points to "y".
-      eq_val->len = 0;
-      eq_val->ptr = (const char *) memchr(val->ptr, '=', val->len);
-      if (eq_val->ptr != NULL) {
-        eq_val->ptr++;  // Skip over '=' character
-        eq_val->len = val->ptr + val->len - eq_val->ptr;
-        val->len = (eq_val->ptr - val->ptr) - 1;
-      }
-    }
-  }
-
-  return list;
-}
-
-static int match_prefix(const char *pattern, int pattern_len, const char *str) {
-  const char *or_str;
-  int i, j, len, res;
-
-  if ((or_str = (const char *) memchr(pattern, '|', pattern_len)) != NULL) {
-    res = match_prefix(pattern, or_str - pattern, str);
-    return res > 0 ? res :
-        match_prefix(or_str + 1, (pattern + pattern_len) - (or_str + 1), str);
-  }
-
-  i = j = 0;
-  res = -1;
-  for (; i < pattern_len; i++, j++) {
-    if (pattern[i] == '?' && str[j] != '\0') {
-      continue;
-    } else if (pattern[i] == '$') {
-      return str[j] == '\0' ? j : -1;
-    } else if (pattern[i] == '*') {
-      i++;
-      if (pattern[i] == '*') {
-        i++;
-        len = (int) strlen(str + j);
-      } else {
-        len = (int) strcspn(str + j, "/");
-      }
-      if (i == pattern_len) {
-        return j + len;
-      }
-      do {
-        res = match_prefix(pattern + i, pattern_len - i, str + j + len);
-      } while (res == -1 && len-- > 0);
-      return res == -1 ? -1 : j + res + len;
-    } else if (pattern[i] != str[j]) {
-      return -1;
-    }
-  }
-  return j;
-}
-
-// HTTP 1.1 assumes keep alive if "Connection:" header is not set
-// This function must tolerate situations when connection info is not
-// set up, for example if request parsing failed.
-static int should_keep_alive(const struct mg_connection *conn) {
-  const char *http_version = conn->request_info.http_version;
-  const char *header = mg_get_header(conn, "Connection");
-  if (conn->must_close ||
-      conn->status_code == 401 ||
-      mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0 ||
-      (header != NULL && mg_strcasecmp(header, "keep-alive") != 0) ||
-      (header == NULL && http_version && strcmp(http_version, "1.1"))) {
-    return 0;
-  }
-  return 1;
-}
-
-static const char *suggest_connection_header(const struct mg_connection *conn) {
-  return should_keep_alive(conn) ? "keep-alive" : "close";
-}
-
-static void send_http_error(struct mg_connection *, int, const char *,
-                            PRINTF_FORMAT_STRING(const char *fmt), ...)
-  PRINTF_ARGS(4, 5);
-
-
-static void send_http_error(struct mg_connection *conn, int status,
-                            const char *reason, const char *fmt, ...) {
-  char buf[MG_BUF_LEN];
-  va_list ap;
-  int len = 0;
-
-  conn->status_code = status;
-  if (conn->ctx->callbacks.http_error == NULL ||
-      conn->ctx->callbacks.http_error(conn, status)) {
-    buf[0] = '\0';
-
-    // Errors 1xx, 204 and 304 MUST NOT send a body
-    if (status > 199 && status != 204 && status != 304) {
-      len = mg_snprintf(conn, buf, sizeof(buf), "Error %d: %s", status, reason);
-      buf[len++] = '\n';
-
-      va_start(ap, fmt);
-      len += mg_vsnprintf(conn, buf + len, sizeof(buf) - len, fmt, ap);
-      va_end(ap);
-    }
-    DEBUG_TRACE(("[%s]", buf));
-
-    mg_printf(conn, "HTTP/1.1 %d %s\r\n"
-              "Content-Length: %d\r\n"
-              "Connection: %s\r\n\r\n", status, reason, len,
-              suggest_connection_header(conn));
-    conn->num_bytes_sent += mg_printf(conn, "%s", buf);
-  }
-}
-
-#if defined(_WIN32) && !defined(__SYMBIAN32__)
-static int pthread_mutex_init(pthread_mutex_t *mutex, void *unused) {
-  (void) unused;
-  *mutex = CreateMutex(NULL, FALSE, NULL);
-  return *mutex == NULL ? -1 : 0;
-}
-
-static int pthread_mutex_destroy(pthread_mutex_t *mutex) {
-  return CloseHandle(*mutex) == 0 ? -1 : 0;
-}
-
-static int pthread_mutex_lock(pthread_mutex_t *mutex) {
-  return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1;
-}
-
-static int pthread_mutex_unlock(pthread_mutex_t *mutex) {
-  return ReleaseMutex(*mutex) == 0 ? -1 : 0;
-}
-
-static int pthread_cond_init(pthread_cond_t *cv, const void *unused) {
-  (void) unused;
-  cv->signal = CreateEvent(NULL, FALSE, FALSE, NULL);
-  cv->broadcast = CreateEvent(NULL, TRUE, FALSE, NULL);
-  return cv->signal != NULL && cv->broadcast != NULL ? 0 : -1;
-}
-
-static int pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex) {
-  HANDLE handles[] = {cv->signal, cv->broadcast};
-  ReleaseMutex(*mutex);
-  WaitForMultipleObjects(2, handles, FALSE, INFINITE);
-  return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1;
-}
-
-static int pthread_cond_signal(pthread_cond_t *cv) {
-  return SetEvent(cv->signal) == 0 ? -1 : 0;
-}
-
-static int pthread_cond_broadcast(pthread_cond_t *cv) {
-  // Implementation with PulseEvent() has race condition, see
-  // http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
-  return PulseEvent(cv->broadcast) == 0 ? -1 : 0;
-}
-
-static int pthread_cond_destroy(pthread_cond_t *cv) {
-  return CloseHandle(cv->signal) && CloseHandle(cv->broadcast) ? 0 : -1;
-}
-
-// For Windows, change all slashes to backslashes in path names.
-static void change_slashes_to_backslashes(char *path) {
-  int i;
-
-  for (i = 0; path[i] != '\0'; i++) {
-    if (path[i] == '/')
-      path[i] = '\\';
-    // i > 0 check is to preserve UNC paths, like \\server\file.txt
-    if (path[i] == '\\' && i > 0)
-      while (path[i + 1] == '\\' || path[i + 1] == '/')
-        (void) memmove(path + i + 1,
-            path + i + 2, strlen(path + i + 1));
-  }
-}
-
-// Encode 'path' which is assumed UTF-8 string, into UNICODE string.
-// wbuf and wbuf_len is a target buffer and its length.
-static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len) {
-  char buf[PATH_MAX], buf2[PATH_MAX];
-
-  mg_strlcpy(buf, path, sizeof(buf));
-  change_slashes_to_backslashes(buf);
-
-  // Convert to Unicode and back. If doubly-converted string does not
-  // match the original, something is fishy, reject.
-  memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
-  MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
-  WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
-                      NULL, NULL);
-  if (strcmp(buf, buf2) != 0) {
-    wbuf[0] = L'\0';
-  }
-}
-
-#if defined(_WIN32_WCE)
-static time_t time(time_t *ptime) {
-  time_t t;
-  SYSTEMTIME st;
-  FILETIME ft;
-
-  GetSystemTime(&st);
-  SystemTimeToFileTime(&st, &ft);
-  t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
-
-  if (ptime != NULL) {
-    *ptime = t;
-  }
-
-  return t;
-}
-
-static struct tm *localtime(const time_t *ptime, struct tm *ptm) {
-  int64_t t = ((int64_t) *ptime) * RATE_DIFF + EPOCH_DIFF;
-  FILETIME ft, lft;
-  SYSTEMTIME st;
-  TIME_ZONE_INFORMATION tzinfo;
-
-  if (ptm == NULL) {
-    return NULL;
-  }
-
-  * (int64_t *) &ft = t;
-  FileTimeToLocalFileTime(&ft, &lft);
-  FileTimeToSystemTime(&lft, &st);
-  ptm->tm_year = st.wYear - 1900;
-  ptm->tm_mon = st.wMonth - 1;
-  ptm->tm_wday = st.wDayOfWeek;
-  ptm->tm_mday = st.wDay;
-  ptm->tm_hour = st.wHour;
-  ptm->tm_min = st.wMinute;
-  ptm->tm_sec = st.wSecond;
-  ptm->tm_yday = 0; // hope nobody uses this
-  ptm->tm_isdst =
-    GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;
-
-  return ptm;
-}
-
-static struct tm *gmtime(const time_t *ptime, struct tm *ptm) {
-  // FIXME(lsm): fix this.
-  return localtime(ptime, ptm);
-}
-
-static size_t strftime(char *dst, size_t dst_size, const char *fmt,
-                       const struct tm *tm) {
-  (void) snprintf(dst, dst_size, "implement strftime() for WinCE");
-  return 0;
-}
-#endif
-
-// Windows happily opens files with some garbage at the end of file name.
-// For example, fopen("a.cgi    ", "r") on Windows successfully opens
-// "a.cgi", despite one would expect an error back.
-// This function returns non-0 if path ends with some garbage.
-static int path_cannot_disclose_cgi(const char *path) {
-  static const char *allowed_last_characters = "_-";
-  int last = path[strlen(path) - 1];
-  return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
-}
-
-static int mg_stat(struct mg_connection *conn, const char *path,
-                   struct file *filep) {
-  wchar_t wbuf[PATH_MAX];
-  WIN32_FILE_ATTRIBUTE_DATA info;
-
-  if (!is_file_in_memory(conn, path, filep)) {
-    to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
-    if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
-      filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
-      filep->modification_time = SYS2UNIX_TIME(
-          info.ftLastWriteTime.dwLowDateTime,
-          info.ftLastWriteTime.dwHighDateTime);
-      filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
-      // If file name is fishy, reset the file structure and return error.
-      // Note it is important to reset, not just return the error, cause
-      // functions like is_file_opened() check the struct.
-      if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
-        memset(filep, 0, sizeof(*filep));
-      }
-    }
-  }
-
-  return filep->membuf != NULL || filep->modification_time != 0;
-}
-
-static int mg_remove(const char *path) {
-  wchar_t wbuf[PATH_MAX];
-  to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
-  return DeleteFileW(wbuf) ? 0 : -1;
-}
-
-static int mg_mkdir(const char *path, int mode) {
-  char buf[PATH_MAX];
-  wchar_t wbuf[PATH_MAX];
-
-  (void) mode;
-  mg_strlcpy(buf, path, sizeof(buf));
-  change_slashes_to_backslashes(buf);
-
-  (void) MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, ARRAY_SIZE(wbuf));
-
-  return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
-}
-
-// Implementation of POSIX opendir/closedir/readdir for Windows.
-static DIR * opendir(const char *name) {
-  DIR *dir = NULL;
-  wchar_t wpath[PATH_MAX];
-  DWORD attrs;
-
-  if (name == NULL) {
-    SetLastError(ERROR_BAD_ARGUMENTS);
-  } else if ((dir = (DIR *) malloc(sizeof(*dir))) == NULL) {
-    SetLastError(ERROR_NOT_ENOUGH_MEMORY);
-  } else {
-    to_unicode(name, wpath, ARRAY_SIZE(wpath));
-    attrs = GetFileAttributesW(wpath);
-    if (attrs != 0xFFFFFFFF &&
-        ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {
-      (void) wcscat(wpath, L"\\*");
-      dir->handle = FindFirstFileW(wpath, &dir->info);
-      dir->result.d_name[0] = '\0';
-    } else {
-      free(dir);
-      dir = NULL;
-    }
-  }
-
-  return dir;
-}
-
-static int closedir(DIR *dir) {
-  int result = 0;
-
-  if (dir != NULL) {
-    if (dir->handle != INVALID_HANDLE_VALUE)
-      result = FindClose(dir->handle) ? 0 : -1;
-
-    free(dir);
-  } else {
-    result = -1;
-    SetLastError(ERROR_BAD_ARGUMENTS);
-  }
-
-  return result;
-}
-
-static struct dirent *readdir(DIR *dir) {
-  struct dirent *result = 0;
-
-  if (dir) {
-    if (dir->handle != INVALID_HANDLE_VALUE) {
-      result = &dir->result;
-      (void) WideCharToMultiByte(CP_UTF8, 0,
-          dir->info.cFileName, -1, result->d_name,
-          sizeof(result->d_name), NULL, NULL);
-
-      if (!FindNextFileW(dir->handle, &dir->info)) {
-        (void) FindClose(dir->handle);
-        dir->handle = INVALID_HANDLE_VALUE;
-      }
-
-    } else {
-      SetLastError(ERROR_FILE_NOT_FOUND);
-    }
-  } else {
-    SetLastError(ERROR_BAD_ARGUMENTS);
-  }
-
-  return result;
-}
-
-#ifndef HAVE_POLL
-static int poll(struct pollfd *pfd, int n, int milliseconds) {
-  struct timeval tv;
-  fd_set set;
-  int i, result, maxfd = 0;
-
-  tv.tv_sec = milliseconds / 1000;
-  tv.tv_usec = (milliseconds % 1000) * 1000;
-  FD_ZERO(&set);
-
-  for (i = 0; i < n; i++) {
-    FD_SET((SOCKET) pfd[i].fd, &set);
-    pfd[i].revents = 0;
-
-    if (pfd[i].fd > maxfd) {
-        maxfd = pfd[i].fd;
-    }
-  }
-
-  if ((result = select(maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
-    for (i = 0; i < n; i++) {
-      if (FD_ISSET(pfd[i].fd, &set)) {
-        pfd[i].revents = POLLIN;
-      }
-    }
-  }
-
-  return result;
-}
-#endif // HAVE_POLL
-
-#define set_close_on_exec(x) // No FD_CLOEXEC on Windows
-
-int mg_start_thread(mg_thread_func_t f, void *p) {
-  return (long)_beginthread((void (__cdecl *)(void *)) f, 0, p) == -1L ? -1 : 0;
-}
-
-static HANDLE dlopen(const char *dll_name, int flags) {
-  wchar_t wbuf[PATH_MAX];
-  (void) flags;
-  to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));
-  return LoadLibraryW(wbuf);
-}
-
-#if !defined(NO_CGI)
-#define SIGKILL 0
-static int kill(pid_t pid, int sig_num) {
-  (void) TerminateProcess(pid, sig_num);
-  (void) CloseHandle(pid);
-  return 0;
-}
-
-static void trim_trailing_whitespaces(char *s) {
-  char *e = s + strlen(s) - 1;
-  while (e > s && isspace(* (unsigned char *) e)) {
-    *e-- = '\0';
-  }
-}
-
-static pid_t spawn_process(struct mg_connection *conn, const char *prog,
-                           char *envblk, char *envp[], int fd_stdin,
-                           int fd_stdout, const char *dir) {
-  HANDLE me;
-  char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
-       cmdline[PATH_MAX], buf[PATH_MAX];
-  struct file file = STRUCT_FILE_INITIALIZER;
-  STARTUPINFOA si;
-  PROCESS_INFORMATION pi = { 0 };
-
-  (void) envp;
-
-  memset(&si, 0, sizeof(si));
-  si.cb = sizeof(si);
-
-  // TODO(lsm): redirect CGI errors to the error log file
-  si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
-  si.wShowWindow = SW_HIDE;
-
-  me = GetCurrentProcess();
-  DuplicateHandle(me, (HANDLE) _get_osfhandle(fd_stdin), me,
-                  &si.hStdInput, 0, TRUE, DUPLICATE_SAME_ACCESS);
-  DuplicateHandle(me, (HANDLE) _get_osfhandle(fd_stdout), me,
-                  &si.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS);
-
-  // If CGI file is a script, try to read the interpreter line
-  interp = conn->ctx->config[CGI_INTERPRETER];
-  if (interp == NULL) {
-    buf[0] = buf[1] = '\0';
-
-    // Read the first line of the script into the buffer
-    snprintf(cmdline, sizeof(cmdline), "%s%c%s", dir, '/', prog);
-    if (mg_fopen(conn, cmdline, "r", &file)) {
-      p = (char *) file.membuf;
-      mg_fgets(buf, sizeof(buf), &file, &p);
-      mg_fclose(&file);
-      buf[sizeof(buf) - 1] = '\0';
-    }
-
-    if (buf[0] == '#' && buf[1] == '!') {
-      trim_trailing_whitespaces(buf + 2);
-    } else {
-      buf[2] = '\0';
-    }
-    interp = buf + 2;
-  }
-
-  if (interp[0] != '\0') {
-    GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
-    interp = full_interp;
-  }
-  GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
-
-  mg_snprintf(conn, cmdline, sizeof(cmdline), "%s%s%s\\%s",
-              interp, interp[0] == '\0' ? "" : " ", full_dir, prog);
-
-  DEBUG_TRACE(("Running [%s]", cmdline));
-  if (CreateProcessA(NULL, cmdline, NULL, NULL, TRUE,
-        CREATE_NEW_PROCESS_GROUP, envblk, NULL, &si, &pi) == 0) {
-    cry(conn, "%s: CreateProcess(%s): %ld",
-        __func__, cmdline, ERRNO);
-    pi.hProcess = (pid_t) -1;
-  }
-
-  // Always close these to prevent handle leakage.
-  (void) close(fd_stdin);
-  (void) close(fd_stdout);
-
-  (void) CloseHandle(si.hStdOutput);
-  (void) CloseHandle(si.hStdInput);
-  (void) CloseHandle(pi.hThread);
-
-  return (pid_t) pi.hProcess;
-}
-#endif // !NO_CGI
-
-static int set_non_blocking_mode(SOCKET sock) {
-  unsigned long on = 1;
-  return ioctlsocket(sock, FIONBIO, &on);
-}
-
-#else
-static int mg_stat(struct mg_connection *conn, const char *path,
-                   struct file *filep) {
-  struct stat st;
-
-  if (!is_file_in_memory(conn, path, filep) && !stat(path, &st)) {
-    filep->size = st.st_size;
-    filep->modification_time = st.st_mtime;
-    filep->is_directory = S_ISDIR(st.st_mode);
-  } else {
-    filep->modification_time = (time_t) 0;
-  }
-
-  return filep->membuf != NULL || filep->modification_time != (time_t) 0;
-}
-
-static void set_close_on_exec(int fd) {
-  fcntl(fd, F_SETFD, FD_CLOEXEC);
-}
-
-int mg_start_thread(mg_thread_func_t func, void *param) {
-  pthread_t thread_id;
-  pthread_attr_t attr;
-  int result;
-
-  (void) pthread_attr_init(&attr);
-  (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
-  // TODO(lsm): figure out why mongoose dies on Linux if next line is enabled
-  // (void) pthread_attr_setstacksize(&attr, sizeof(struct mg_connection) * 5);
-
-  result = pthread_create(&thread_id, &attr, func, param);
-  pthread_attr_destroy(&attr);
-
-  return result;
-}
-
-#ifndef NO_CGI
-static pid_t spawn_process(struct mg_connection *conn, const char *prog,
-                           char *envblk, char *envp[], int fd_stdin,
-                           int fd_stdout, const char *dir) {
-  pid_t pid;
-  const char *interp;
-
-  (void) envblk;
-
-  if ((pid = fork()) == -1) {
-    // Parent
-    send_http_error(conn, 500, http_500_error, "fork(): %s", strerror(ERRNO));
-  } else if (pid == 0) {
-    // Child
-    if (chdir(dir) != 0) {
-      cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
-    } else if (dup2(fd_stdin, 0) == -1) {
-      cry(conn, "%s: dup2(%d, 0): %s", __func__, fd_stdin, strerror(ERRNO));
-    } else if (dup2(fd_stdout, 1) == -1) {
-      cry(conn, "%s: dup2(%d, 1): %s", __func__, fd_stdout, strerror(ERRNO));
-    } else {
-      // Not redirecting stderr to stdout, to avoid output being littered
-      // with the error messages.
-      (void) close(fd_stdin);
-      (void) close(fd_stdout);
-
-      // After exec, all signal handlers are restored to their default values,
-      // with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
-      // implementation, SIGCHLD's handler will leave unchanged after exec
-      // if it was set to be ignored. Restore it to default action.
-      signal(SIGCHLD, SIG_DFL);
-
-      interp = conn->ctx->config[CGI_INTERPRETER];
-      if (interp == NULL) {
-        (void) execle(prog, prog, NULL, envp);
-        cry(conn, "%s: execle(%s): %s", __func__, prog, strerror(ERRNO));
-      } else {
-        (void) execle(interp, interp, prog, NULL, envp);
-        cry(conn, "%s: execle(%s %s): %s", __func__, interp, prog,
-            strerror(ERRNO));
-      }
-    }
-    exit(EXIT_FAILURE);
-  }
-
-  // Parent. Close stdio descriptors
-  (void) close(fd_stdin);
-  (void) close(fd_stdout);
-
-  return pid;
-}
-#endif // !NO_CGI
-
-static int set_non_blocking_mode(SOCKET sock) {
-  int flags;
-
-  flags = fcntl(sock, F_GETFL, 0);
-  (void) fcntl(sock, F_SETFL, flags | O_NONBLOCK);
-
-  return 0;
-}
-#endif // _WIN32
-
-// Write data to the IO channel - opened file descriptor, socket or SSL
-// descriptor. Return number of bytes written.
-static int64_t push(FILE *fp, SOCKET sock, SSL *ssl, const char *buf,
-                    int64_t len) {
-  int64_t sent;
-  int n, k;
-
-  (void) ssl;  // Get rid of warning
-  sent = 0;
-  while (sent < len) {
-
-    // How many bytes we send in this iteration
-    k = len - sent > INT_MAX ? INT_MAX : (int) (len - sent);
-
-#ifndef NO_SSL
-    if (ssl != NULL) {
-      n = SSL_write(ssl, buf + sent, k);
-    } else
-#endif
-      if (fp != NULL) {
-      n = (int) fwrite(buf + sent, 1, (size_t) k, fp);
-      if (ferror(fp))
-        n = -1;
-    } else {
-      n = send(sock, buf + sent, (size_t) k, MSG_NOSIGNAL);
-    }
-
-    if (n <= 0)
-      break;
-
-    sent += n;
-  }
-
-  return sent;
-}
-
-// Read from IO channel - opened file descriptor, socket, or SSL descriptor.
-// Return negative value on error, or number of bytes read on success.
-static int pull(FILE *fp, struct mg_connection *conn, char *buf, int len) {
-  int nread;
-
-  if (fp != NULL) {
-    // Use read() instead of fread(), because if we're reading from the CGI
-    // pipe, fread() may block until IO buffer is filled up. We cannot afford
-    // to block and must pass all read bytes immediately to the client.
-    nread = read(fileno(fp), buf, (size_t) len);
-#ifndef NO_SSL
-  } else if (conn->ssl != NULL) {
-    nread = SSL_read(conn->ssl, buf, len);
-#endif
-  } else {
-    nread = recv(conn->client.sock, buf, (size_t) len, 0);
-  }
-
-  return conn->ctx->stop_flag ? -1 : nread;
-}
-
-static int pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len) {
-  int n, nread = 0;
-
-  while (len > 0) {
-    n = pull(fp, conn, buf + nread, len);
-    if (n < 0) {
-      nread = n;  // Propagate the error
-      break;
-    } else if (n == 0) {
-      break;  // No more data to read
-    } else {
-      conn->consumed_content += n;
-      nread += n;
-      len -= n;
-    }
-  }
-
-  return nread;
-}
-
-int mg_read(struct mg_connection *conn, void *buf, size_t len) {
-  int n, buffered_len, nread;
-  const char *body;
-
-  // If Content-Length is not set, read until socket is closed
-  if (conn->consumed_content == 0 && conn->content_len == 0) {
-    conn->content_len = INT64_MAX;
-    conn->must_close = 1;
-  }
-
-  nread = 0;
-  if (conn->consumed_content < conn->content_len) {
-    // Adjust number of bytes to read.
-    int64_t to_read = conn->content_len - conn->consumed_content;
-    if (to_read < (int64_t) len) {
-      len = (size_t) to_read;
-    }
-
-    // Return buffered data
-    body = conn->buf + conn->request_len + conn->consumed_content;
-    buffered_len = &conn->buf[conn->data_len] - body;
-    if (buffered_len > 0) {
-      if (len < (size_t) buffered_len) {
-        buffered_len = (int) len;
-      }
-      memcpy(buf, body, (size_t) buffered_len);
-      len -= buffered_len;
-      conn->consumed_content += buffered_len;
-      nread += buffered_len;
-      buf = (char *) buf + buffered_len;
-    }
-
-    // We have returned all buffered data. Read new data from the remote socket.
-    n = pull_all(NULL, conn, (char *) buf, (int) len);
-    nread = n >= 0 ? nread + n : n;
-  }
-  return nread;
-}
-
-int mg_write(struct mg_connection *conn, const void *buf, size_t len) {
-  time_t now;
-  int64_t n, total, allowed;
-
-  if (conn->throttle > 0) {
-    if ((now = time(NULL)) != conn->last_throttle_time) {
-      conn->last_throttle_time = now;
-      conn->last_throttle_bytes = 0;
-    }
-    allowed = conn->throttle - conn->last_throttle_bytes;
-    if (allowed > (int64_t) len) {
-      allowed = len;
-    }
-    if ((total = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
-                      (int64_t) allowed)) == allowed) {
-      buf = (char *) buf + total;
-      conn->last_throttle_bytes += total;
-      while (total < (int64_t) len && conn->ctx->stop_flag == 0) {
-        allowed = conn->throttle > (int64_t) len - total ?
-          (int64_t) len - total : conn->throttle;
-        if ((n = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
-                      (int64_t) allowed)) != allowed) {
-          break;
-        }
-        sleep(1);
-        conn->last_throttle_bytes = allowed;
-        conn->last_throttle_time = time(NULL);
-        buf = (char *) buf + n;
-        total += n;
-      }
-    }
-  } else {
-    total = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
-                 (int64_t) len);
-  }
-  return (int) total;
-}
-
-// Print message to buffer. If buffer is large enough to hold the message,
-// return buffer. If buffer is to small, allocate large enough buffer on heap,
-// and return allocated buffer.
-static int alloc_vprintf(char **buf, size_t size, const char *fmt, va_list ap) {
-  va_list ap_copy;
-  int len;
-
-  // Windows is not standard-compliant, and vsnprintf() returns -1 if
-  // buffer is too small. Also, older versions of msvcrt.dll do not have
-  // _vscprintf().  However, if size is 0, vsnprintf() behaves correctly.
-  // Therefore, we make two passes: on first pass, get required message length.
-  // On second pass, actually print the message.
-  va_copy(ap_copy, ap);
-  len = vsnprintf(NULL, 0, fmt, ap_copy);
-
-  if (len > (int) size &&
-      (size = len + 1) > 0 &&
-      (*buf = (char *) malloc(size)) == NULL) {
-    len = -1;  // Allocation failed, mark failure
-  } else {
-    va_copy(ap_copy, ap);
-    vsnprintf(*buf, size, fmt, ap_copy);
-  }
-
-  return len;
-}
-
-int mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap) {
-  char mem[MG_BUF_LEN], *buf = mem;
-  int len;
-
-  if ((len = alloc_vprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
-    len = mg_write(conn, buf, (size_t) len);
-  }
-  if (buf != mem && buf != NULL) {
-    free(buf);
-  }
-
-  return len;
-}
-
-int mg_printf(struct mg_connection *conn, const char *fmt, ...) {
-  va_list ap;
-  va_start(ap, fmt);
-  return mg_vprintf(conn, fmt, ap);
-}
-
-int mg_url_decode(const char *src, int src_len, char *dst,
-                  int dst_len, int is_form_url_encoded) {
-  int i, j, a, b;
-#define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
-
-  for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
-    if (src[i] == '%' && i < src_len - 2 &&
-        isxdigit(* (const unsigned char *) (src + i + 1)) &&
-        isxdigit(* (const unsigned char *) (src + i + 2))) {
-      a = tolower(* (const unsigned char *) (src + i + 1));
-      b = tolower(* (const unsigned char *) (src + i + 2));
-      dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
-      i += 2;
-    } else if (is_form_url_encoded && src[i] == '+') {
-      dst[j] = ' ';
-    } else {
-      dst[j] = src[i];
-    }
-  }
-
-  dst[j] = '\0'; // Null-terminate the destination
-
-  return i >= src_len ? j : -1;
-}
-
-int mg_get_var(const char *data, size_t data_len, const char *name,
-               char *dst, size_t dst_len) {
-  const char *p, *e, *s;
-  size_t name_len;
-  int len;
-
-  if (dst == NULL || dst_len == 0) {
-    len = -2;
-  } else if (data == NULL || name == NULL || data_len == 0) {
-    len = -1;
-    dst[0] = '\0';
-  } else {
-    name_len = strlen(name);
-    e = data + data_len;
-    len = -1;
-    dst[0] = '\0';
-
-    // data is "var1=val1&var2=val2...". Find variable first
-    for (p = data; p + name_len < e; p++) {
-      if ((p == data || p[-1] == '&') && p[name_len] == '=' &&
-          !mg_strncasecmp(name, p, name_len)) {
-
-        // Point p to variable value
-        p += name_len + 1;
-
-        // Point s to the end of the value
-        s = (const char *) memchr(p, '&', (size_t)(e - p));
-        if (s == NULL) {
-          s = e;
-        }
-        assert(s >= p);
-
-        // Decode variable into destination buffer
-        len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1);
-
-        // Redirect error code from -1 to -2 (destination buffer too small).
-        if (len == -1) {
-          len = -2;
-        }
-        break;
-      }
-    }
-  }
-
-  return len;
-}
-
-int mg_get_cookie(const char *cookie_header, const char *var_name,
-                  char *dst, size_t dst_size) {
-  const char *s, *p, *end;
-  int name_len, len = -1;
-
-  if (dst == NULL || dst_size == 0) {
-    len = -2;
-  } else if (var_name == NULL || (s = cookie_header) == NULL) {
-    len = -1;
-    dst[0] = '\0';
-  } else {
-    name_len = (int) strlen(var_name);
-    end = s + strlen(s);
-    dst[0] = '\0';
-
-    for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
-      if (s[name_len] == '=') {
-        s += name_len + 1;
-        if ((p = strchr(s, ' ')) == NULL)
-          p = end;
-        if (p[-1] == ';')
-          p--;
-        if (*s == '"' && p[-1] == '"' && p > s + 1) {
-          s++;
-          p--;
-        }
-        if ((size_t) (p - s) < dst_size) {
-          len = p - s;
-          mg_strlcpy(dst, s, (size_t) len + 1);
-        } else {
-          len = -3;
-        }
-        break;
-      }
-    }
-  }
-  return len;
-}
-
-static void convert_uri_to_file_name(struct mg_connection *conn, char *buf,
-                                     size_t buf_len, struct file *filep) {
-  struct vec a, b;
-  const char *rewrite, *uri = conn->request_info.uri;
-  char *p;
-  int match_len;
-  char gz_path[PATH_MAX];
-  char const* accept_encoding;
-
-  // Using buf_len - 1 because memmove() for PATH_INFO may shift part
-  // of the path one byte on the right.
-  mg_snprintf(conn, buf, buf_len - 1, "%s%s", conn->ctx->config[DOCUMENT_ROOT],
-              uri);
-
-  rewrite = conn->ctx->config[REWRITE];
-  while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
-    if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
-      mg_snprintf(conn, buf, buf_len - 1, "%.*s%s", (int) b.len, b.ptr,
-                  uri + match_len);
-      break;
-    }
-  }
-
-  if (mg_stat(conn, buf, filep)) return;
-
-  // if we can't find the actual file, look for the file
-  // with the same name but a .gz extension. If we find it,
-  // use that and set the gzipped flag in the file struct
-  // to indicate that the response need to have the content-
-  // encoding: gzip header
-  // we can only do this if the browser declares support
-  if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
-    if (strstr(accept_encoding,"gzip") != NULL) {
-      snprintf(gz_path, sizeof(gz_path), "%s.gz", buf);
-      if (mg_stat(conn, gz_path, filep)) {
-        filep->gzipped = 1;
-        return;
-      }
-    }
-  }
-
-  // Support PATH_INFO for CGI scripts.
-  for (p = buf + strlen(buf); p > buf + 1; p--) {
-    if (*p == '/') {
-      *p = '\0';
-      if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
-                       strlen(conn->ctx->config[CGI_EXTENSIONS]), buf) > 0 &&
-          mg_stat(conn, buf, filep)) {
-        // Shift PATH_INFO block one character right, e.g.
-        //  "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
-        // conn->path_info is pointing to the local variable "path" declared
-        // in handle_request(), so PATH_INFO is not valid after
-        // handle_request returns.
-        conn->path_info = p + 1;
-        memmove(p + 2, p + 1, strlen(p + 1) + 1);  // +1 is for trailing \0
-        p[1] = '/';
-        break;
-      } else {
-        *p = '/';
-      }
-    }
-  }
-}
-
-// Check whether full request is buffered. Return:
-//   -1  if request is malformed
-//    0  if request is not yet fully buffered
-//   >0  actual request length, including last \r\n\r\n
-static int get_request_len(const char *buf, int buflen) {
-  const char *s, *e;
-  int len = 0;
-
-  for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
-    // Control characters are not allowed but >=128 is.
-    if (!isprint(* (const unsigned char *) s) && *s != '\r' &&
-        *s != '\n' && * (const unsigned char *) s < 128) {
-      len = -1;
-      break;  // [i_a] abort scan as soon as one malformed character is found;
-              // don't let subsequent \r\n\r\n win us over anyhow
-    } else if (s[0] == '\n' && s[1] == '\n') {
-      len = (int) (s - buf) + 2;
-    } else if (s[0] == '\n' && &s[1] < e &&
-        s[1] == '\r' && s[2] == '\n') {
-      len = (int) (s - buf) + 3;
-    }
-
-  return len;
-}
-
-// Convert month to the month number. Return -1 on error, or month number
-static int get_month_index(const char *s) {
-  size_t i;
-
-  for (i = 0; i < ARRAY_SIZE(month_names); i++)
-    if (!strcmp(s, month_names[i]))
-      return (int) i;
-
-  return -1;
-}
-
-static int num_leap_years(int year) {
-  return year / 4 - year / 100 + year / 400;
-}
-
-// Parse UTC date-time string, and return the corresponding time_t value.
-static time_t parse_date_string(const char *datetime) {
-  static const unsigned short days_before_month[] = {
-    0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
-  };
-  char month_str[32];
-  int second, minute, hour, day, month, year, leap_days, days;
-  time_t result = (time_t) 0;
-
-  if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d",
-               &day, month_str, &year, &hour, &minute, &second) == 6) ||
-       (sscanf(datetime, "%d %3s %d %d:%d:%d",
-               &day, month_str, &year, &hour, &minute, &second) == 6) ||
-       (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d",
-               &day, month_str, &year, &hour, &minute, &second) == 6) ||
-       (sscanf(datetime, "%d-%3s-%d %d:%d:%d",
-               &day, month_str, &year, &hour, &minute, &second) == 6)) &&
-      year > 1970 &&
-      (month = get_month_index(month_str)) != -1) {
-    leap_days = num_leap_years(year) - num_leap_years(1970);
-    year -= 1970;
-    days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
-    result = days * 24 * 3600 + hour * 3600 + minute * 60 + second;
-  }
-
-  return result;
-}
-
-// Protect against directory disclosure attack by removing '..',
-// excessive '/' and '\' characters
-static void remove_double_dots_and_double_slashes(char *s) {
-  char *p = s;
-
-  while (*s != '\0') {
-    *p++ = *s++;
-    if (s[-1] == '/' || s[-1] == '\\') {
-      // Skip all following slashes, backslashes and double-dots
-      while (s[0] != '\0') {
-        if (s[0] == '/' || s[0] == '\\') {
-          s++;
-        } else if (s[0] == '.' && s[1] == '.') {
-          s += 2;
-        } else {
-          break;
-        }
-      }
-    }
-  }
-  *p = '\0';
-}
-
-static const struct {
-  const char *extension;
-  size_t ext_len;
-  const char *mime_type;
-} builtin_mime_types[] = {
-  {".html", 5, "text/html"},
-  {".htm", 4, "text/html"},
-  {".shtm", 5, "text/html"},
-  {".shtml", 6, "text/html"},
-  {".css", 4, "text/css"},
-  {".js",  3, "application/x-javascript"},
-  {".ico", 4, "image/x-icon"},
-  {".gif", 4, "image/gif"},
-  {".jpg", 4, "image/jpeg"},
-  {".jpeg", 5, "image/jpeg"},
-  {".png", 4, "image/png"},
-  {".svg", 4, "image/svg+xml"},
-  {".txt", 4, "text/plain"},
-  {".torrent", 8, "application/x-bittorrent"},
-  {".wav", 4, "audio/x-wav"},
-  {".mp3", 4, "audio/x-mp3"},
-  {".mid", 4, "audio/mid"},
-  {".m3u", 4, "audio/x-mpegurl"},
-  {".ogg", 4, "audio/ogg"},
-  {".ram", 4, "audio/x-pn-realaudio"},
-  {".xml", 4, "text/xml"},
-  {".json",  5, "text/json"},
-  {".xslt", 5, "application/xml"},
-  {".xsl", 4, "application/xml"},
-  {".ra",  3, "audio/x-pn-realaudio"},
-  {".doc", 4, "application/msword"},
-  {".exe", 4, "application/octet-stream"},
-  {".zip", 4, "application/x-zip-compressed"},
-  {".xls", 4, "application/excel"},
-  {".tgz", 4, "application/x-tar-gz"},
-  {".tar", 4, "application/x-tar"},
-  {".gz",  3, "application/x-gunzip"},
-  {".arj", 4, "application/x-arj-compressed"},
-  {".rar", 4, "application/x-arj-compressed"},
-  {".rtf", 4, "application/rtf"},
-  {".pdf", 4, "application/pdf"},
-  {".swf", 4, "application/x-shockwave-flash"},
-  {".mpg", 4, "video/mpeg"},
-  {".webm", 5, "video/webm"},
-  {".mpeg", 5, "video/mpeg"},
-  {".mov", 4, "video/quicktime"},
-  {".mp4", 4, "video/mp4"},
-  {".m4v", 4, "video/x-m4v"},
-  {".asf", 4, "video/x-ms-asf"},
-  {".avi", 4, "video/x-msvideo"},
-  {".bmp", 4, "image/bmp"},
-  {".ttf", 4, "application/x-font-ttf"},
-  {NULL,  0, NULL}
-};
-
-const char *mg_get_builtin_mime_type(const char *path) {
-  const char *ext;
-  size_t i, path_len;
-
-  path_len = strlen(path);
-
-  for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
-    ext = path + (path_len - builtin_mime_types[i].ext_len);
-    if (path_len > builtin_mime_types[i].ext_len &&
-        mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
-      return builtin_mime_types[i].mime_type;
-    }
-  }
-
-  return "text/plain";
-}
-
-// Look at the "path" extension and figure what mime type it has.
-// Store mime type in the vector.
-static void get_mime_type(struct mg_context *ctx, const char *path,
-                          struct vec *vec) {
-  struct vec ext_vec, mime_vec;
-  const char *list, *ext;
-  size_t path_len;
-
-  path_len = strlen(path);
-
-  // Scan user-defined mime types first, in case user wants to
-  // override default mime types.
-  list = ctx->config[EXTRA_MIME_TYPES];
-  while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
-    // ext now points to the path suffix
-    ext = path + path_len - ext_vec.len;
-    if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
-      *vec = mime_vec;
-      return;
-    }
-  }
-
-  vec->ptr = mg_get_builtin_mime_type(path);
-  vec->len = strlen(vec->ptr);
-}
-
-static int is_big_endian(void) {
-  static const int n = 1;
-  return ((char *) &n)[0] == 0;
-}
-
-#ifndef HAVE_MD5
-typedef struct MD5Context {
-  uint32_t buf[4];
-  uint32_t bits[2];
-  unsigned char in[64];
-} MD5_CTX;
-
-static void byteReverse(unsigned char *buf, unsigned longs) {
-  uint32_t t;
-
-  // Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN
-  if (is_big_endian()) {
-    do {
-      t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
-        ((unsigned) buf[1] << 8 | buf[0]);
-      * (uint32_t *) buf = t;
-      buf += 4;
-    } while (--longs);
-  }
-}
-
-#define F1(x, y, z) (z ^ (x & (y ^ z)))
-#define F2(x, y, z) F1(z, x, y)
-#define F3(x, y, z) (x ^ y ^ z)
-#define F4(x, y, z) (y ^ (x | ~z))
-
-#define MD5STEP(f, w, x, y, z, data, s) \
-  ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
-
-// Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
-// initialization constants.
-static void MD5Init(MD5_CTX *ctx) {
-  ctx->buf[0] = 0x67452301;
-  ctx->buf[1] = 0xefcdab89;
-  ctx->buf[2] = 0x98badcfe;
-  ctx->buf[3] = 0x10325476;
-
-  ctx->bits[0] = 0;
-  ctx->bits[1] = 0;
-}
-
-static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) {
-  register uint32_t a, b, c, d;
-
-  a = buf[0];
-  b = buf[1];
-  c = buf[2];
-  d = buf[3];
-
-  MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
-  MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
-  MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
-  MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
-  MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
-  MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
-  MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
-  MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
-  MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
-  MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
-  MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
-  MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
-  MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
-  MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
-  MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
-  MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
-
-  MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
-  MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
-  MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
-  MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
-  MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
-  MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
-  MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
-  MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
-  MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
-  MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
-  MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
-  MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
-  MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
-  MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
-  MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
-  MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
-
-  MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
-  MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
-  MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
-  MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
-  MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
-  MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
-  MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
-  MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
-  MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
-  MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
-  MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
-  MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
-  MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
-  MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
-  MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
-  MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
-
-  MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
-  MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
-  MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
-  MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
-  MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
-  MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
-  MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
-  MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
-  MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
-  MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
-  MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
-  MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
-  MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
-  MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
-  MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
-  MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
-
-  buf[0] += a;
-  buf[1] += b;
-  buf[2] += c;
-  buf[3] += d;
-}
-
-static void MD5Update(MD5_CTX *ctx, unsigned char const *buf, unsigned len) {
-  uint32_t t;
-
-  t = ctx->bits[0];
-  if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t)
-    ctx->bits[1]++;
-  ctx->bits[1] += len >> 29;
-
-  t = (t >> 3) & 0x3f;
-
-  if (t) {
-    unsigned char *p = (unsigned char *) ctx->in + t;
-
-    t = 64 - t;
-    if (len < t) {
-      memcpy(p, buf, len);
-      return;
-    }
-    memcpy(p, buf, t);
-    byteReverse(ctx->in, 16);
-    MD5Transform(ctx->buf, (uint32_t *) ctx->in);
-    buf += t;
-    len -= t;
-  }
-
-  while (len >= 64) {
-    memcpy(ctx->in, buf, 64);
-    byteReverse(ctx->in, 16);
-    MD5Transform(ctx->buf, (uint32_t *) ctx->in);
-    buf += 64;
-    len -= 64;
-  }
-
-  memcpy(ctx->in, buf, len);
-}
-
-static void MD5Final(unsigned char digest[16], MD5_CTX *ctx) {
-  unsigned count;
-  unsigned char *p;
-  uint32_t *a;
-
-  count = (ctx->bits[0] >> 3) & 0x3F;
-
-  p = ctx->in + count;
-  *p++ = 0x80;
-  count = 64 - 1 - count;
-  if (count < 8) {
-    memset(p, 0, count);
-    byteReverse(ctx->in, 16);
-    MD5Transform(ctx->buf, (uint32_t *) ctx->in);
-    memset(ctx->in, 0, 56);
-  } else {
-    memset(p, 0, count - 8);
-  }
-  byteReverse(ctx->in, 14);
-
-  a = (uint32_t *)ctx->in;
-  a[14] = ctx->bits[0];
-  a[15] = ctx->bits[1];
-
-  MD5Transform(ctx->buf, (uint32_t *) ctx->in);
-  byteReverse((unsigned char *) ctx->buf, 4);
-  memcpy(digest, ctx->buf, 16);
-  memset((char *) ctx, 0, sizeof(*ctx));
-}
-#endif // !HAVE_MD5
-
-// Stringify binary data. Output buffer must be twice as big as input,
-// because each byte takes 2 bytes in string representation
-static void bin2str(char *to, const unsigned char *p, size_t len) {
-  static const char *hex = "0123456789abcdef";
-
-  for (; len--; p++) {
-    *to++ = hex[p[0] >> 4];
-    *to++ = hex[p[0] & 0x0f];
-  }
-  *to = '\0';
-}
-
-// Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
-char *mg_md5(char buf[33], ...) {
-  unsigned char hash[16];
-  const char *p;
-  va_list ap;
-  MD5_CTX ctx;
-
-  MD5Init(&ctx);
-
-  va_start(ap, buf);
-  while ((p = va_arg(ap, const char *)) != NULL) {
-    MD5Update(&ctx, (const unsigned char *) p, (unsigned) strlen(p));
-  }
-  va_end(ap);
-
-  MD5Final(hash, &ctx);
-  bin2str(buf, hash, sizeof(hash));
-  return buf;
-}
-
-// Check the user's password, return 1 if OK
-static int check_password(const char *method, const char *ha1, const char *uri,
-                          const char *nonce, const char *nc, const char *cnonce,
-                          const char *qop, const char *response) {
-  char ha2[32 + 1], expected_response[32 + 1];
-
-  // Some of the parameters may be NULL
-  if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL ||
-      qop == NULL || response == NULL) {
-    return 0;
-  }
-
-  // NOTE(lsm): due to a bug in MSIE, we do not compare the URI
-  // TODO(lsm): check for authentication timeout
-  if (// strcmp(dig->uri, c->ouri) != 0 ||
-      strlen(response) != 32
-      // || now - strtoul(dig->nonce, NULL, 10) > 3600
-      ) {
-    return 0;
-  }
-
-  mg_md5(ha2, method, ":", uri, NULL);
-  mg_md5(expected_response, ha1, ":", nonce, ":", nc,
-      ":", cnonce, ":", qop, ":", ha2, NULL);
-
-  return mg_strcasecmp(response, expected_response) == 0;
-}
-
-// Use the global passwords file, if specified by auth_gpass option,
-// or search for .htpasswd in the requested directory.
-static void open_auth_file(struct mg_connection *conn, const char *path,
-                           struct file *filep) {
-  char name[PATH_MAX];
-  const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
-  struct file file = STRUCT_FILE_INITIALIZER;
-
-  if (gpass != NULL) {
-    // Use global passwords file
-    if (!mg_fopen(conn, gpass, "r", filep)) {
-      cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
-    }
-    // Important: using local struct file to test path for is_directory flag.
-    // If filep is used, mg_stat() makes it appear as if auth file was opened.
-  } else if (mg_stat(conn, path, &file) && file.is_directory) {
-    mg_snprintf(conn, name, sizeof(name), "%s%c%s",
-                path, '/', PASSWORDS_FILE_NAME);
-    mg_fopen(conn, name, "r", filep);
-  } else {
-     // Try to find .htpasswd in requested directory.
-    for (p = path, e = p + strlen(p) - 1; e > p; e--)
-      if (e[0] == '/')
-        break;
-    mg_snprintf(conn, name, sizeof(name), "%.*s%c%s",
-                (int) (e - p), p, '/', PASSWORDS_FILE_NAME);
-    mg_fopen(conn, name, "r", filep);
-  }
-}
-
-// Parsed Authorization header
-struct ah {
-  char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
-};
-
-// Return 1 on success. Always initializes the ah structure.
-static int parse_auth_header(struct mg_connection *conn, char *buf,
-                             size_t buf_size, struct ah *ah) {
-  char *name, *value, *s;
-  const char *auth_header;
-
-  (void) memset(ah, 0, sizeof(*ah));
-  if ((auth_header = mg_get_header(conn, "Authorization")) == NULL ||
-      mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
-    return 0;
-  }
-
-  // Make modifiable copy of the auth header
-  (void) mg_strlcpy(buf, auth_header + 7, buf_size);
-  s = buf;
-
-  // Parse authorization header
-  for (;;) {
-    // Gobble initial spaces
-    while (isspace(* (unsigned char *) s)) {
-      s++;
-    }
-    name = skip_quoted(&s, "=", " ", 0);
-    // Value is either quote-delimited, or ends at first comma or space.
-    if (s[0] == '\"') {
-      s++;
-      value = skip_quoted(&s, "\"", " ", '\\');
-      if (s[0] == ',') {
-        s++;
-      }
-    } else {
-      value = skip_quoted(&s, ", ", " ", 0);  // IE uses commas, FF uses spaces
-    }
-    if (*name == '\0') {
-      break;
-    }
-
-    if (!strcmp(name, "username")) {
-      ah->user = value;
-    } else if (!strcmp(name, "cnonce")) {
-      ah->cnonce = value;
-    } else if (!strcmp(name, "response")) {
-      ah->response = value;
-    } else if (!strcmp(name, "uri")) {
-      ah->uri = value;
-    } else if (!strcmp(name, "qop")) {
-      ah->qop = value;
-    } else if (!strcmp(name, "nc")) {
-      ah->nc = value;
-    } else if (!strcmp(name, "nonce")) {
-      ah->nonce = value;
-    }
-  }
-
-  // CGI needs it as REMOTE_USER
-  if (ah->user != NULL) {
-    conn->request_info.remote_user = mg_strdup(ah->user);
-  } else {
-    return 0;
-  }
-
-  return 1;
-}
-
-static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p) {
-  char *eof;
-  size_t len;
-
-  if (filep->membuf != NULL && *p != NULL) {
-    eof = memchr(*p, '\n', &filep->membuf[filep->size] - *p);
-    len = (size_t) (eof - *p) > size - 1 ? size - 1 : (size_t) (eof - *p);
-    memcpy(buf, *p, len);
-    buf[len] = '\0';
-    *p = eof;
-    return eof;
-  } else if (filep->fp != NULL) {
-    return fgets(buf, size, filep->fp);
-  } else {
-    return NULL;
-  }
-}
-
-// Authorize against the opened passwords file. Return 1 if authorized.
-static int authorize(struct mg_connection *conn, struct file *filep) {
-  struct ah ah;
-  char line[256], f_user[256], ha1[256], f_domain[256], buf[MG_BUF_LEN], *p;
-
-  if (!parse_auth_header(conn, buf, sizeof(buf), &ah)) {
-    return 0;
-  }
-
-  // Loop over passwords file
-  p = (char *) filep->membuf;
-  while (mg_fgets(line, sizeof(line), filep, &p) != NULL) {
-    if (sscanf(line, "%[^:]:%[^:]:%s", f_user, f_domain, ha1) != 3) {
-      continue;
-    }
-
-    if (!strcmp(ah.user, f_user) &&
-        !strcmp(conn->ctx->config[AUTHENTICATION_DOMAIN], f_domain))
-      return check_password(conn->request_info.request_method, ha1, ah.uri,
-                            ah.nonce, ah.nc, ah.cnonce, ah.qop, ah.response);
-  }
-
-  return 0;
-}
-
-// Return 1 if request is authorised, 0 otherwise.
-static int check_authorization(struct mg_connection *conn, const char *path) {
-  char fname[PATH_MAX];
-  struct vec uri_vec, filename_vec;
-  const char *list;
-  struct file file = STRUCT_FILE_INITIALIZER;
-  int authorized = 1;
-
-  list = conn->ctx->config[PROTECT_URI];
-  while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
-    if (!memcmp(conn->request_info.uri, uri_vec.ptr, uri_vec.len)) {
-      mg_snprintf(conn, fname, sizeof(fname), "%.*s",
-                  (int) filename_vec.len, filename_vec.ptr);
-      if (!mg_fopen(conn, fname, "r", &file)) {
-        cry(conn, "%s: cannot open %s: %s", __func__, fname, strerror(errno));
-      }
-      break;
-    }
-  }
-
-  if (!is_file_opened(&file)) {
-    open_auth_file(conn, path, &file);
-  }
-
-  if (is_file_opened(&file)) {
-    authorized = authorize(conn, &file);
-    mg_fclose(&file);
-  }
-
-  return authorized;
-}
-
-static void send_authorization_request(struct mg_connection *conn) {
-  conn->status_code = 401;
-  mg_printf(conn,
-            "HTTP/1.1 401 Unauthorized\r\n"
-            "Content-Length: 0\r\n"
-            "WWW-Authenticate: Digest qop=\"auth\", "
-            "realm=\"%s\", nonce=\"%lu\"\r\n\r\n",
-            conn->ctx->config[AUTHENTICATION_DOMAIN],
-            (unsigned long) time(NULL));
-}
-
-static int is_authorized_for_put(struct mg_connection *conn) {
-  struct file file = STRUCT_FILE_INITIALIZER;
-  const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
-  int ret = 0;
-
-  if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
-    ret = authorize(conn, &file);
-    mg_fclose(&file);
-  }
-
-  return ret;
-}
-
-int mg_modify_passwords_file(const char *fname, const char *domain,
-                             const char *user, const char *pass) {
-  int found;
-  char line[512], u[512], d[512], ha1[33], tmp[PATH_MAX];
-  FILE *fp, *fp2;
-
-  found = 0;
-  fp = fp2 = NULL;
-
-  // Regard empty password as no password - remove user record.
-  if (pass != NULL && pass[0] == '\0') {
-    pass = NULL;
-  }
-
-  (void) snprintf(tmp, sizeof(tmp), "%s.tmp", fname);
-
-  // Create the file if does not exist
-  if ((fp = fopen(fname, "a+")) != NULL) {
-    (void) fclose(fp);
-  }
-
-  // Open the given file and temporary file
-  if ((fp = fopen(fname, "r")) == NULL) {
-    return 0;
-  } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
-    fclose(fp);
-    return 0;
-  }
-
-  // Copy the stuff to temporary file
-  while (fgets(line, sizeof(line), fp) != NULL) {
-    if (sscanf(line, "%[^:]:%[^:]:%*s", u, d) != 2) {
-      continue;
-    }
-
-    if (!strcmp(u, user) && !strcmp(d, domain)) {
-      found++;
-      if (pass != NULL) {
-        mg_md5(ha1, user, ":", domain, ":", pass, NULL);
-        fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
-      }
-    } else {
-      fprintf(fp2, "%s", line);
-    }
-  }
-
-  // If new user, just add it
-  if (!found && pass != NULL) {
-    mg_md5(ha1, user, ":", domain, ":", pass, NULL);
-    fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
-  }
-
-  // Close files
-  fclose(fp);
-  fclose(fp2);
-
-  // Put the temp file in place of real file
-  remove(fname);
-  rename(tmp, fname);
-
-  return 1;
-}
-
-static int conn2(const char *host, int port, int use_ssl,
-                 char *ebuf, size_t ebuf_len) {
-  struct sockaddr_in sin;
-  struct hostent *he;
-  SOCKET sock = INVALID_SOCKET;
-
-  if (host == NULL) {
-    snprintf(ebuf, ebuf_len, "%s", "NULL host");
-  } else if (use_ssl && SSLv23_client_method == NULL) {
-    snprintf(ebuf, ebuf_len, "%s", "SSL is not initialized");
-    // TODO(lsm): use something threadsafe instead of gethostbyname()
-  } else if ((he = gethostbyname(host)) == NULL) {
-    snprintf(ebuf, ebuf_len, "gethostbyname(%s): %s", host, strerror(ERRNO));
-  } else if ((sock = socket(PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
-    snprintf(ebuf, ebuf_len, "socket(): %s", strerror(ERRNO));
-  } else {
-    sin.sin_family = AF_INET;
-    sin.sin_port = htons((uint16_t) port);
-    sin.sin_addr = * (struct in_addr *) he->h_addr_list[0];
-    if (connect(sock, (struct sockaddr *) &sin, sizeof(sin)) != 0) {
-      snprintf(ebuf, ebuf_len, "connect(%s:%d): %s",
-               host, port, strerror(ERRNO));
-      closesocket(sock);
-      sock = INVALID_SOCKET;
-    }
-  }
-  return sock;
-}
-
-
-
-void mg_url_encode(const char *src, char *dst, size_t dst_len) {
-  static const char *dont_escape = "._-$,;~()";
-  static const char *hex = "0123456789abcdef";
-  const char *end = dst + dst_len - 1;
-
-  for (; *src != '\0' && dst < end; src++, dst++) {
-    if (isalnum(*(const unsigned char *) src) ||
-        strchr(dont_escape, * (const unsigned char *) src) != NULL) {
-      *dst = *src;
-    } else if (dst + 2 < end) {
-      dst[0] = '%';
-      dst[1] = hex[(* (const unsigned char *) src) >> 4];
-      dst[2] = hex[(* (const unsigned char *) src) & 0xf];
-      dst += 2;
-    }
-  }
-
-  *dst = '\0';
-}
-
-static void print_dir_entry(struct de *de) {
-  char size[64], mod[64], href[PATH_MAX];
-
-  if (de->file.is_directory) {
-    mg_snprintf(de->conn, size, sizeof(size), "%s", "[DIRECTORY]");
-  } else {
-     // We use (signed) cast below because MSVC 6 compiler cannot
-     // convert unsigned __int64 to double. Sigh.
-    if (de->file.size < 1024) {
-      mg_snprintf(de->conn, size, sizeof(size), "%d", (int) de->file.size);
-    } else if (de->file.size < 0x100000) {
-      mg_snprintf(de->conn, size, sizeof(size),
-                  "%.1fk", (double) de->file.size / 1024.0);
-    } else if (de->file.size < 0x40000000) {
-      mg_snprintf(de->conn, size, sizeof(size),
-                  "%.1fM", (double) de->file.size / 1048576);
-    } else {
-      mg_snprintf(de->conn, size, sizeof(size),
-                  "%.1fG", (double) de->file.size / 1073741824);
-    }
-  }
-  strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M",
-           localtime(&de->file.modification_time));
-  mg_url_encode(de->file_name, href, sizeof(href));
-  de->conn->num_bytes_sent += mg_printf(de->conn,
-      "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
-      "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
-      de->conn->request_info.uri, href, de->file.is_directory ? "/" : "",
-      de->file_name, de->file.is_directory ? "/" : "", mod, size);
-}
-
-// This function is called from send_directory() and used for
-// sorting directory entries by size, or name, or modification time.
-// On windows, __cdecl specification is needed in case if project is built
-// with __stdcall convention. qsort always requires __cdels callback.
-static int WINCDECL compare_dir_entries(const void *p1, const void *p2) {
-  const struct de *a = (const struct de *) p1, *b = (const struct de *) p2;
-  const char *query_string = a->conn->request_info.query_string;
-  int cmp_result = 0;
-
-  if (query_string == NULL) {
-    query_string = "na";
-  }
-
-  if (a->file.is_directory && !b->file.is_directory) {
-    return -1;  // Always put directories on top
-  } else if (!a->file.is_directory && b->file.is_directory) {
-    return 1;   // Always put directories on top
-  } else if (*query_string == 'n') {
-    cmp_result = strcmp(a->file_name, b->file_name);
-  } else if (*query_string == 's') {
-    cmp_result = a->file.size == b->file.size ? 0 :
-      a->file.size > b->file.size ? 1 : -1;
-  } else if (*query_string == 'd') {
-    cmp_result = a->file.modification_time == b->file.modification_time ? 0 :
-      a->file.modification_time > b->file.modification_time ? 1 : -1;
-  }
-
-  return query_string[1] == 'd' ? -cmp_result : cmp_result;
-}
-
-static int must_hide_file(struct mg_connection *conn, const char *path) {
-  const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
-  const char *pattern = conn->ctx->config[HIDE_FILES];
-  return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0 ||
-    (pattern != NULL && match_prefix(pattern, strlen(pattern), path) > 0);
-}
-
-static int scan_directory(struct mg_connection *conn, const char *dir,
-                          void *data, void (*cb)(struct de *, void *)) {
-  char path[PATH_MAX];
-  struct dirent *dp;
-  DIR *dirp;
-  struct de de;
-
-  if ((dirp = opendir(dir)) == NULL) {
-    return 0;
-  } else {
-    de.conn = conn;
-
-    while ((dp = readdir(dirp)) != NULL) {
-      // Do not show current dir and hidden files
-      if (!strcmp(dp->d_name, ".") ||
-          !strcmp(dp->d_name, "..") ||
-          must_hide_file(conn, dp->d_name)) {
-        continue;
-      }
-
-      mg_snprintf(conn, path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
-
-      // If we don't memset stat structure to zero, mtime will have
-      // garbage and strftime() will segfault later on in
-      // print_dir_entry(). memset is required only if mg_stat()
-      // fails. For more details, see
-      // http://code.google.com/p/mongoose/issues/detail?id=79
-      memset(&de.file, 0, sizeof(de.file));
-      mg_stat(conn, path, &de.file);
-
-      de.file_name = dp->d_name;
-      cb(&de, data);
-    }
-    (void) closedir(dirp);
-  }
-  return 1;
-}
-
-static int remove_directory(struct mg_connection *conn, const char *dir) {
-  char path[PATH_MAX];
-  struct dirent *dp;
-  DIR *dirp;
-  struct de de;
-
-  if ((dirp = opendir(dir)) == NULL) {
-    return 0;
-  } else {
-    de.conn = conn;
-
-    while ((dp = readdir(dirp)) != NULL) {
-      // Do not show current dir (but show hidden files as they will also be removed)
-      if (!strcmp(dp->d_name, ".") ||
-          !strcmp(dp->d_name, "..")) {
-        continue;
-      }
-
-      mg_snprintf(conn, path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
-
-      // If we don't memset stat structure to zero, mtime will have
-      // garbage and strftime() will segfault later on in
-      // print_dir_entry(). memset is required only if mg_stat()
-      // fails. For more details, see
-      // http://code.google.com/p/mongoose/issues/detail?id=79
-      memset(&de.file, 0, sizeof(de.file));
-      mg_stat(conn, path, &de.file);
-      if(de.file.modification_time) {
-          if(de.file.is_directory) {
-              remove_directory(conn, path);
-          } else {
-              mg_remove(path);
-          }
-      }
-
-    }
-    (void) closedir(dirp);
-
-    rmdir(dir);
-  }
-
-  return 1;
-}
-
-struct dir_scan_data {
-  struct de *entries;
-  int num_entries;
-  int arr_size;
-};
-
-// Behaves like realloc(), but frees original pointer on failure
-static void *realloc2(void *ptr, size_t size) {
-  void *new_ptr = realloc(ptr, size);
-  if (new_ptr == NULL) {
-    free(ptr);
-  }
-  return new_ptr;
-}
-
-static void dir_scan_callback(struct de *de, void *data) {
-  struct dir_scan_data *dsd = (struct dir_scan_data *) data;
-
-  if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
-    dsd->arr_size *= 2;
-    dsd->entries = (struct de *) realloc2(dsd->entries, dsd->arr_size *
-                                          sizeof(dsd->entries[0]));
-  }
-  if (dsd->entries == NULL) {
-    // TODO(lsm): propagate an error to the caller
-    dsd->num_entries = 0;
-  } else {
-    dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
-    dsd->entries[dsd->num_entries].file = de->file;
-    dsd->entries[dsd->num_entries].conn = de->conn;
-    dsd->num_entries++;
-  }
-}
-
-static void handle_directory_request(struct mg_connection *conn,
-                                     const char *dir) {
-  int i, sort_direction;
-  struct dir_scan_data data = { NULL, 0, 128 };
-
-  if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
-    send_http_error(conn, 500, "Cannot open directory",
-                    "Error: opendir(%s): %s", dir, strerror(ERRNO));
-    return;
-  }
-
-  sort_direction = conn->request_info.query_string != NULL &&
-    conn->request_info.query_string[1] == 'd' ? 'a' : 'd';
-
-  conn->must_close = 1;
-  mg_printf(conn, "%s",
-            "HTTP/1.1 200 OK\r\n"
-            "Connection: close\r\n"
-            "Content-Type: text/html; charset=utf-8\r\n\r\n");
-
-  conn->num_bytes_sent += mg_printf(conn,
-      "<html><head><title>Index of %s</title>"
-      "<style>th {text-align: left;}</style></head>"
-      "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
-      "<tr><th><a href=\"?n%c\">Name</a></th>"
-      "<th><a href=\"?d%c\">Modified</a></th>"
-      "<th><a href=\"?s%c\">Size</a></th></tr>"
-      "<tr><td colspan=\"3\"><hr></td></tr>",
-      conn->request_info.uri, conn->request_info.uri,
-      sort_direction, sort_direction, sort_direction);
-
-  // Print first entry - link to a parent directory
-  conn->num_bytes_sent += mg_printf(conn,
-      "<tr><td><a href=\"%s%s\">%s</a></td>"
-      "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
-      conn->request_info.uri, "..", "Parent directory", "-", "-");
-
-  // Sort and print directory entries
-  qsort(data.entries, (size_t) data.num_entries, sizeof(data.entries[0]),
-        compare_dir_entries);
-  for (i = 0; i < data.num_entries; i++) {
-    print_dir_entry(&data.entries[i]);
-    free(data.entries[i].file_name);
-  }
-  free(data.entries);
-
-  conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
-  conn->status_code = 200;
-}
-
-// Send len bytes from the opened file to the client.
-static void send_file_data(struct mg_connection *conn, struct file *filep,
-                           int64_t offset, int64_t len) {
-  char buf[MG_BUF_LEN];
-  int to_read, num_read, num_written;
-
-  // Sanity check the offset
-  offset = offset < 0 ? 0 : offset > filep->size ? filep->size : offset;
-
-  if (len > 0 && filep->membuf != NULL && filep->size > 0) {
-    if (len > filep->size - offset) {
-      len = filep->size - offset;
-    }
-    mg_write(conn, filep->membuf + offset, (size_t) len);
-  } else if (len > 0 && filep->fp != NULL) {
-    fseeko(filep->fp, offset, SEEK_SET);
-    while (len > 0) {
-      // Calculate how much to read from the file in the buffer
-      to_read = sizeof(buf);
-      if ((int64_t) to_read > len) {
-        to_read = (int) len;
-      }
-
-      // Read from file, exit the loop on error
-      if ((num_read = fread(buf, 1, (size_t) to_read, filep->fp)) <= 0) {
-        break;
-      }
-
-      // Send read bytes to the client, exit the loop on error
-      if ((num_written = mg_write(conn, buf, (size_t) num_read)) != num_read) {
-        break;
-      }
-
-      // Both read and were successful, adjust counters
-      conn->num_bytes_sent += num_written;
-      len -= num_written;
-    }
-  }
-}
-
-static int parse_range_header(const char *header, int64_t *a, int64_t *b) {
-  return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
-}
-
-static void gmt_time_string(char *buf, size_t buf_len, time_t *t) {
-  strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t));
-}
-
-static void construct_etag(char *buf, size_t buf_len,
-                           const struct file *filep) {
-  snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"",
-           (unsigned long) filep->modification_time, filep->size);
-}
-
-static void fclose_on_exec(struct file *filep) {
-  if (filep != NULL && filep->fp != NULL) {
-#ifndef _WIN32
-    fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC);
-#endif
-  }
-}
-
-static void handle_file_request(struct mg_connection *conn, const char *path,
-                                struct file *filep) {
-  char date[64], lm[64], etag[64], range[64];
-  const char *msg = "OK", *hdr;
-  time_t curtime = time(NULL);
-  int64_t cl, r1, r2;
-  struct vec mime_vec;
-  int n;
-  char gz_path[PATH_MAX];
-  char const* encoding = "";
-
-  get_mime_type(conn->ctx, path, &mime_vec);
-  cl = filep->size;
-  conn->status_code = 200;
-  range[0] = '\0';
-
-  // if this file is in fact a pre-gzipped file, rewrite its filename
-  // it's important to rewrite the filename after resolving
-  // the mime type from it, to preserve the actual file's type
-  if (filep->gzipped) {
-    snprintf(gz_path, sizeof(gz_path), "%s.gz", path);
-    path = gz_path;
-    encoding = "Content-Encoding: gzip\r\n";
-  }
-
-  if (!mg_fopen(conn, path, "rb", filep)) {
-    send_http_error(conn, 500, http_500_error,
-                    "fopen(%s): %s", path, strerror(ERRNO));
-    return;
-  }
-
-  fclose_on_exec(filep);
-
-  // If Range: header specified, act accordingly
-  r1 = r2 = 0;
-  hdr = mg_get_header(conn, "Range");
-  if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 &&
-      r1 >= 0 && r2 >= 0) {
-    // actually, range requests don't play well with a pre-gzipped
-    // file (since the range is specified in the uncmpressed space)
-    if (filep->gzipped) {
-      send_http_error(conn, 501, "Not Implemented", "range requests in gzipped files are not supported");
-      return;
-    }
-    conn->status_code = 206;
-    cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1: cl - r1;
-    mg_snprintf(conn, range, sizeof(range),
-                "Content-Range: bytes "
-                "%" INT64_FMT "-%"
-                INT64_FMT "/%" INT64_FMT "\r\n",
-                r1, r1 + cl - 1, filep->size);
-    msg = "Partial Content";
-  }
-
-  // Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
-  // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3
-  gmt_time_string(date, sizeof(date), &curtime);
-  gmt_time_string(lm, sizeof(lm), &filep->modification_time);
-  construct_etag(etag, sizeof(etag), filep);
-
-  (void) mg_printf(conn,
-      "HTTP/1.1 %d %s\r\n"
-      "Date: %s\r\n"
-      "Last-Modified: %s\r\n"
-      "Etag: %s\r\n"
-      "Content-Type: %.*s\r\n"
-      "Content-Length: %" INT64_FMT "\r\n"
-      "Connection: %s\r\n"
-      "Accept-Ranges: bytes\r\n"
-      "%s%s\r\n",
-      conn->status_code, msg, date, lm, etag, (int) mime_vec.len,
-      mime_vec.ptr, cl, suggest_connection_header(conn), range, encoding);
-
-  if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
-    send_file_data(conn, filep, r1, cl);
-  }
-  mg_fclose(filep);
-}
-
-void mg_send_file(struct mg_connection *conn, const char *path) {
-  struct file file = STRUCT_FILE_INITIALIZER;
-  if (mg_stat(conn, path, &file)) {
-    handle_file_request(conn, path, &file);
-  } else {
-    send_http_error(conn, 404, "Not Found", "%s", "File not found");
-  }
-}
-
-
-// Parse HTTP headers from the given buffer, advance buffer to the point
-// where parsing stopped.
-static void parse_http_headers(char **buf, struct mg_request_info *ri) {
-  int i;
-
-  for (i = 0; i < (int) ARRAY_SIZE(ri->http_headers); i++) {
-    ri->http_headers[i].name = skip_quoted(buf, ":", " ", 0);
-    ri->http_headers[i].value = skip(buf, "\r\n");
-    if (ri->http_headers[i].name[0] == '\0')
-      break;
-    ri->num_headers = i + 1;
-  }
-}
-
-static int is_valid_http_method(const char *method) {
-  return !strcmp(method, "GET") || !strcmp(method, "POST") ||
-    !strcmp(method, "HEAD") || !strcmp(method, "CONNECT") ||
-    !strcmp(method, "PUT") || !strcmp(method, "DELETE") ||
-    !strcmp(method, "OPTIONS") || !strcmp(method, "PROPFIND")
-    || !strcmp(method, "MKCOL")
-          ;
-}
-
-// Parse HTTP request, fill in mg_request_info structure.
-// This function modifies the buffer by NUL-terminating
-// HTTP request components, header names and header values.
-static int parse_http_message(char *buf, int len, struct mg_request_info *ri) {
-  int is_request, request_length = get_request_len(buf, len);
-  if (request_length > 0) {
-    // Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_port
-    ri->remote_user = ri->request_method = ri->uri = ri->http_version = NULL;
-    ri->num_headers = 0;
-
-    buf[request_length - 1] = '\0';
-
-    // RFC says that all initial whitespaces should be ingored
-    while (*buf != '\0' && isspace(* (unsigned char *) buf)) {
-      buf++;
-    }
-    ri->request_method = skip(&buf, " ");
-    ri->uri = skip(&buf, " ");
-    ri->http_version = skip(&buf, "\r\n");
-    if (((is_request = is_valid_http_method(ri->request_method)) &&
-         memcmp(ri->http_version, "HTTP/", 5) != 0) ||
-        (!is_request && memcmp(ri->request_method, "HTTP/", 5)) != 0) {
-      request_length = -1;
-    } else {
-      if (is_request) {
-        ri->http_version += 5;
-      }
-      parse_http_headers(&buf, ri);
-    }
-  }
-  return request_length;
-}
-
-// Keep reading the input (either opened file descriptor fd, or socket sock,
-// or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
-// buffer (which marks the end of HTTP request). Buffer buf may already
-// have some data. The length of the data is stored in nread.
-// Upon every read operation, increase nread by the number of bytes read.
-static int read_request(FILE *fp, struct mg_connection *conn,
-                        char *buf, int bufsiz, int *nread) {
-  int request_len, n = 0;
-
-  request_len = get_request_len(buf, *nread);
-  while (*nread < bufsiz && request_len == 0 &&
-         (n = pull(fp, conn, buf + *nread, bufsiz - *nread)) > 0) {
-    *nread += n;
-    assert(*nread <= bufsiz);
-    request_len = get_request_len(buf, *nread);
-  }
-
-  return request_len <= 0 && n <= 0 ? -1 : request_len;
-}
-
-// For given directory path, substitute it to valid index file.
-// Return 0 if index file has been found, -1 if not found.
-// If the file is found, it's stats is returned in stp.
-static int substitute_index_file(struct mg_connection *conn, char *path,
-                                 size_t path_len, struct file *filep) {
-  const char *list = conn->ctx->config[INDEX_FILES];
-  struct file file = STRUCT_FILE_INITIALIZER;
-  struct vec filename_vec;
-  size_t n = strlen(path);
-  int found = 0;
-
-  // The 'path' given to us points to the directory. Remove all trailing
-  // directory separator characters from the end of the path, and
-  // then append single directory separator character.
-  while (n > 0 && path[n - 1] == '/') {
-    n--;
-  }
-  path[n] = '/';
-
-  // Traverse index files list. For each entry, append it to the given
-  // path and see if the file exists. If it exists, break the loop
-  while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
-
-    // Ignore too long entries that may overflow path buffer
-    if (filename_vec.len > path_len - (n + 2))
-      continue;
-
-    // Prepare full path to the index file
-    mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
-
-    // Does it exist?
-    if (mg_stat(conn, path, &file)) {
-      // Yes it does, break the loop
-      *filep = file;
-      found = 1;
-      break;
-    }
-  }
-
-  // If no index file exists, restore directory path
-  if (!found) {
-    path[n] = '\0';
-  }
-
-  return found;
-}
-
-// Return True if we should reply 304 Not Modified.
-static int is_not_modified(const struct mg_connection *conn,
-                           const struct file *filep) {
-  char etag[64];
-  const char *ims = mg_get_header(conn, "If-Modified-Since");
-  const char *inm = mg_get_header(conn, "If-None-Match");
-  construct_etag(etag, sizeof(etag), filep);
-  return (inm != NULL && !mg_strcasecmp(etag, inm)) ||
-    (ims != NULL && filep->modification_time <= parse_date_string(ims));
-}
-
-static int forward_body_data(struct mg_connection *conn, FILE *fp,
-                             SOCKET sock, SSL *ssl) {
-  const char *expect, *body;
-  char buf[MG_BUF_LEN];
-  int to_read, nread, buffered_len, success = 0;
-
-  expect = mg_get_header(conn, "Expect");
-  assert(fp != NULL);
-
-  if (conn->content_len == -1) {
-    send_http_error(conn, 411, "Length Required", "%s", "");
-  } else if (expect != NULL && mg_strcasecmp(expect, "100-continue")) {
-    send_http_error(conn, 417, "Expectation Failed", "%s", "");
-  } else {
-    if (expect != NULL) {
-      (void) mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
-    }
-
-    body = conn->buf + conn->request_len + conn->consumed_content;
-    buffered_len = &conn->buf[conn->data_len] - body;
-    assert(buffered_len >= 0);
-    assert(conn->consumed_content == 0);
-
-    if (buffered_len > 0) {
-      if ((int64_t) buffered_len > conn->content_len) {
-        buffered_len = (int) conn->content_len;
-      }
-      push(fp, sock, ssl, body, (int64_t) buffered_len);
-      conn->consumed_content += buffered_len;
-    }
-
-    nread = 0;
-    while (conn->consumed_content < conn->content_len) {
-      to_read = sizeof(buf);
-      if ((int64_t) to_read > conn->content_len - conn->consumed_content) {
-        to_read = (int) (conn->content_len - conn->consumed_content);
-      }
-      nread = pull(NULL, conn, buf, to_read);
-      if (nread <= 0 || push(fp, sock, ssl, buf, nread) != nread) {
-        break;
-      }
-      conn->consumed_content += nread;
-    }
-
-    if (conn->consumed_content == conn->content_len) {
-      success = nread >= 0;
-    }
-
-    // Each error code path in this function must send an error
-    if (!success) {
-      send_http_error(conn, 577, http_500_error, "%s", "");
-    }
-  }
-
-  return success;
-}
-
-#if !defined(NO_CGI)
-// This structure helps to create an environment for the spawned CGI program.
-// Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
-// last element must be NULL.
-// However, on Windows there is a requirement that all these VARIABLE=VALUE\0
-// strings must reside in a contiguous buffer. The end of the buffer is
-// marked by two '\0' characters.
-// We satisfy both worlds: we create an envp array (which is vars), all
-// entries are actually pointers inside buf.
-struct cgi_env_block {
-  struct mg_connection *conn;
-  char buf[CGI_ENVIRONMENT_SIZE]; // Environment buffer
-  int len; // Space taken
-  char *vars[MAX_CGI_ENVIR_VARS]; // char **envp
-  int nvars; // Number of variables
-};
-
-static char *addenv(struct cgi_env_block *block,
-                    PRINTF_FORMAT_STRING(const char *fmt), ...)
-  PRINTF_ARGS(2, 3);
-
-// Append VARIABLE=VALUE\0 string to the buffer, and add a respective
-// pointer into the vars array.
-static char *addenv(struct cgi_env_block *block, const char *fmt, ...) {
-  int n, space;
-  char *added;
-  va_list ap;
-
-  // Calculate how much space is left in the buffer
-  space = sizeof(block->buf) - block->len - 2;
-  assert(space >= 0);
-
-  // Make a pointer to the free space int the buffer
-  added = block->buf + block->len;
-
-  // Copy VARIABLE=VALUE\0 string into the free space
-  va_start(ap, fmt);
-  n = mg_vsnprintf(block->conn, added, (size_t) space, fmt, ap);
-  va_end(ap);
-
-  // Make sure we do not overflow buffer and the envp array
-  if (n > 0 && n + 1 < space &&
-      block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
-    // Append a pointer to the added string into the envp array
-    block->vars[block->nvars++] = added;
-    // Bump up used length counter. Include \0 terminator
-    block->len += n + 1;
-  } else {
-    cry(block->conn, "%s: CGI env buffer truncated for [%s]", __func__, fmt);
-  }
-
-  return added;
-}
-
-static void prepare_cgi_environment(struct mg_connection *conn,
-                                    const char *prog,
-                                    struct cgi_env_block *blk) {
-  const char *s, *slash;
-  struct vec var_vec;
-  char *p, src_addr[IP_ADDR_STR_LEN];
-  int  i;
-
-  blk->len = blk->nvars = 0;
-  blk->conn = conn;
-  sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
-
-  addenv(blk, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
-  addenv(blk, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
-  addenv(blk, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
-
-  // Prepare the environment block
-  addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
-  addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
-  addenv(blk, "%s", "REDIRECT_STATUS=200"); // For PHP
-
-  // TODO(lsm): fix this for IPv6 case
-  addenv(blk, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
-
-  addenv(blk, "REQUEST_METHOD=%s", conn->request_info.request_method);
-  addenv(blk, "REMOTE_ADDR=%s", src_addr);
-  addenv(blk, "REMOTE_PORT=%d", conn->request_info.remote_port);
-  addenv(blk, "REQUEST_URI=%s", conn->request_info.uri);
-
-  // SCRIPT_NAME
-  assert(conn->request_info.uri[0] == '/');
-  slash = strrchr(conn->request_info.uri, '/');
-  if ((s = strrchr(prog, '/')) == NULL)
-    s = prog;
-  addenv(blk, "SCRIPT_NAME=%.*s%s", (int) (slash - conn->request_info.uri),
-         conn->request_info.uri, s);
-
-  addenv(blk, "SCRIPT_FILENAME=%s", prog);
-  addenv(blk, "PATH_TRANSLATED=%s", prog);
-  addenv(blk, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
-
-  if ((s = mg_get_header(conn, "Content-Type")) != NULL)
-    addenv(blk, "CONTENT_TYPE=%s", s);
-
-  if (conn->request_info.query_string != NULL)
-    addenv(blk, "QUERY_STRING=%s", conn->request_info.query_string);
-
-  if ((s = mg_get_header(conn, "Content-Length")) != NULL)
-    addenv(blk, "CONTENT_LENGTH=%s", s);
-
-  if ((s = getenv("PATH")) != NULL)
-    addenv(blk, "PATH=%s", s);
-
-  if (conn->path_info != NULL) {
-    addenv(blk, "PATH_INFO=%s", conn->path_info);
-  }
-
-#if defined(_WIN32)
-  if ((s = getenv("COMSPEC")) != NULL) {
-    addenv(blk, "COMSPEC=%s", s);
-  }
-  if ((s = getenv("SYSTEMROOT")) != NULL) {
-    addenv(blk, "SYSTEMROOT=%s", s);
-  }
-  if ((s = getenv("SystemDrive")) != NULL) {
-    addenv(blk, "SystemDrive=%s", s);
-  }
-  if ((s = getenv("ProgramFiles")) != NULL) {
-    addenv(blk, "ProgramFiles=%s", s);
-  }
-  if ((s = getenv("ProgramFiles(x86)")) != NULL) {
-    addenv(blk, "ProgramFiles(x86)=%s", s);
-  }
-#else
-  if ((s = getenv("LD_LIBRARY_PATH")) != NULL)
-    addenv(blk, "LD_LIBRARY_PATH=%s", s);
-#endif // _WIN32
-
-  if ((s = getenv("PERLLIB")) != NULL)
-    addenv(blk, "PERLLIB=%s", s);
-
-  if (conn->request_info.remote_user != NULL) {
-    addenv(blk, "REMOTE_USER=%s", conn->request_info.remote_user);
-    addenv(blk, "%s", "AUTH_TYPE=Digest");
-  }
-
-  // Add all headers as HTTP_* variables
-  for (i = 0; i < conn->request_info.num_headers; i++) {
-    p = addenv(blk, "HTTP_%s=%s",
-        conn->request_info.http_headers[i].name,
-        conn->request_info.http_headers[i].value);
-
-    // Convert variable name into uppercase, and change - to _
-    for (; *p != '=' && *p != '\0'; p++) {
-      if (*p == '-')
-        *p = '_';
-      *p = (char) toupper(* (unsigned char *) p);
-    }
-  }
-
-  // Add user-specified variables
-  s = conn->ctx->config[CGI_ENVIRONMENT];
-  while ((s = next_option(s, &var_vec, NULL)) != NULL) {
-    addenv(blk, "%.*s", (int) var_vec.len, var_vec.ptr);
-  }
-
-  blk->vars[blk->nvars++] = NULL;
-  blk->buf[blk->len++] = '\0';
-
-  assert(blk->nvars < (int) ARRAY_SIZE(blk->vars));
-  assert(blk->len > 0);
-  assert(blk->len < (int) sizeof(blk->buf));
-}
-
-static void handle_cgi_request(struct mg_connection *conn, const char *prog) {
-  int headers_len, data_len, i, fd_stdin[2], fd_stdout[2];
-  const char *status, *status_text;
-  char buf[16384], *pbuf, dir[PATH_MAX], *p;
-  struct mg_request_info ri;
-  struct cgi_env_block blk;
-  FILE *in, *out;
-  struct file fout = STRUCT_FILE_INITIALIZER;
-  pid_t pid;
-
-  prepare_cgi_environment(conn, prog, &blk);
-
-  // CGI must be executed in its own directory. 'dir' must point to the
-  // directory containing executable program, 'p' must point to the
-  // executable program name relative to 'dir'.
-  (void) mg_snprintf(conn, dir, sizeof(dir), "%s", prog);
-  if ((p = strrchr(dir, '/')) != NULL) {
-    *p++ = '\0';
-  } else {
-    dir[0] = '.', dir[1] = '\0';
-    p = (char *) prog;
-  }
-
-  pid = (pid_t) -1;
-  fd_stdin[0] = fd_stdin[1] = fd_stdout[0] = fd_stdout[1] = -1;
-  in = out = NULL;
-
-  if (pipe(fd_stdin) != 0 || pipe(fd_stdout) != 0) {
-    send_http_error(conn, 500, http_500_error,
-        "Cannot create CGI pipe: %s", strerror(ERRNO));
-    goto done;
-  }
-
-  pid = spawn_process(conn, p, blk.buf, blk.vars, fd_stdin[0], fd_stdout[1],
-                      dir);
-  // spawn_process() must close those!
-  // If we don't mark them as closed, close() attempt before
-  // return from this function throws an exception on Windows.
-  // Windows does not like when closed descriptor is closed again.
-  fd_stdin[0] = fd_stdout[1] = -1;
-
-  if (pid == (pid_t) -1) {
-    send_http_error(conn, 500, http_500_error,
-        "Cannot spawn CGI process [%s]: %s", prog, strerror(ERRNO));
-    goto done;
-  }
-
-  if ((in = fdopen(fd_stdin[1], "wb")) == NULL ||
-      (out = fdopen(fd_stdout[0], "rb")) == NULL) {
-    send_http_error(conn, 500, http_500_error,
-        "fopen: %s", strerror(ERRNO));
-    goto done;
-  }
-
-  setbuf(in, NULL);
-  setbuf(out, NULL);
-  fout.fp = out;
-
-  // Send POST data to the CGI process if needed
-  if (!strcmp(conn->request_info.request_method, "POST") &&
-      !forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
-    goto done;
-  }
-
-  // Close so child gets an EOF.
-  fclose(in);
-  in = NULL;
-  fd_stdin[1] = -1;
-
-  // Now read CGI reply into a buffer. We need to set correct
-  // status code, thus we need to see all HTTP headers first.
-  // Do not send anything back to client, until we buffer in all
-  // HTTP headers.
-  data_len = 0;
-  headers_len = read_request(out, conn, buf, sizeof(buf), &data_len);
-  if (headers_len <= 0) {
-    send_http_error(conn, 500, http_500_error,
-                    "CGI program sent malformed or too big (>%u bytes) "
-                    "HTTP headers: [%.*s]",
-                    (unsigned) sizeof(buf), data_len, buf);
-    goto done;
-  }
-  pbuf = buf;
-  buf[headers_len - 1] = '\0';
-  parse_http_headers(&pbuf, &ri);
-
-  // Make up and send the status line
-  status_text = "OK";
-  if ((status = get_header(&ri, "Status")) != NULL) {
-    conn->status_code = atoi(status);
-    status_text = status;
-    while (isdigit(* (unsigned char *) status_text) || *status_text == ' ') {
-      status_text++;
-    }
-  } else if (get_header(&ri, "Location") != NULL) {
-    conn->status_code = 302;
-  } else {
-    conn->status_code = 200;
-  }
-  if (get_header(&ri, "Connection") != NULL &&
-      !mg_strcasecmp(get_header(&ri, "Connection"), "keep-alive")) {
-    conn->must_close = 1;
-  }
-  (void) mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code,
-                   status_text);
-
-  // Send headers
-  for (i = 0; i < ri.num_headers; i++) {
-    mg_printf(conn, "%s: %s\r\n",
-              ri.http_headers[i].name, ri.http_headers[i].value);
-  }
-  mg_write(conn, "\r\n", 2);
-
-  // Send chunk of data that may have been read after the headers
-  conn->num_bytes_sent += mg_write(conn, buf + headers_len,
-                                   (size_t)(data_len - headers_len));
-
-  // Read the rest of CGI output and send to the client
-  send_file_data(conn, &fout, 0, INT64_MAX);
-
-done:
-  if (pid != (pid_t) -1) {
-    kill(pid, SIGKILL);
-  }
-  if (fd_stdin[0] != -1) {
-    close(fd_stdin[0]);
-  }
-  if (fd_stdout[1] != -1) {
-    close(fd_stdout[1]);
-  }
-
-  if (in != NULL) {
-    fclose(in);
-  } else if (fd_stdin[1] != -1) {
-    close(fd_stdin[1]);
-  }
-
-  if (out != NULL) {
-    fclose(out);
-  } else if (fd_stdout[0] != -1) {
-    close(fd_stdout[0]);
-  }
-}
-#endif // !NO_CGI
-
-// For a given PUT path, create all intermediate subdirectories
-// for given path. Return 0 if the path itself is a directory,
-// or -1 on error, 1 if OK.
-static int put_dir(struct mg_connection *conn, const char *path) {
-  char buf[PATH_MAX];
-  const char *s, *p;
-  struct file file = STRUCT_FILE_INITIALIZER;
-  int len, res = 1;
-
-  for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
-    len = p - path;
-    if (len >= (int) sizeof(buf)) {
-      res = -1;
-      break;
-    }
-    memcpy(buf, path, len);
-    buf[len] = '\0';
-
-    // Try to create intermediate directory
-    DEBUG_TRACE(("mkdir(%s)", buf));
-    if (!mg_stat(conn, buf, &file) && mg_mkdir(buf, 0755) != 0) {
-      res = -1;
-      break;
-    }
-
-    // Is path itself a directory?
-    if (p[1] == '\0') {
-      res = 0;
-    }
-  }
-
-  return res;
-}
-
-static void mkcol(struct mg_connection *conn, const char *path) {
-  int rc, body_len;
-  struct de de;
-  memset(&de.file, 0, sizeof(de.file));
-  mg_stat(conn, path, &de.file);
-
-  if(de.file.modification_time) {
-      send_http_error(conn, 405, "Method Not Allowed",
-                      "mkcol(%s): %s", path, strerror(ERRNO));
-      return;
-  }
-
-  body_len = conn->data_len - conn->request_len;
-  if(body_len > 0) {
-      send_http_error(conn, 415, "Unsupported media type",
-                      "mkcol(%s): %s", path, strerror(ERRNO));
-      return;
-  }
-
-  rc = mg_mkdir(path, 0755);
-
-  if (rc == 0) {
-    conn->status_code = 201;
-    mg_printf(conn, "HTTP/1.1 %d Created\r\n\r\n", conn->status_code);
-  } else if (rc == -1) {
-      if(errno == EEXIST)
-        send_http_error(conn, 405, "Method Not Allowed",
-                      "mkcol(%s): %s", path, strerror(ERRNO));
-      else if(errno == EACCES)
-          send_http_error(conn, 403, "Forbidden",
-                        "mkcol(%s): %s", path, strerror(ERRNO));
-      else if(errno == ENOENT)
-          send_http_error(conn, 409, "Conflict",
-                        "mkcol(%s): %s", path, strerror(ERRNO));
-      else
-          send_http_error(conn, 500, http_500_error,
-                          "fopen(%s): %s", path, strerror(ERRNO));
-  }
-}
-
-static void put_file(struct mg_connection *conn, const char *path) {
-  struct file file = STRUCT_FILE_INITIALIZER;
-  const char *range;
-  int64_t r1, r2;
-  int rc;
-
-  conn->status_code = mg_stat(conn, path, &file) ? 200 : 201;
-
-  if ((rc = put_dir(conn, path)) == 0) {
-    mg_printf(conn, "HTTP/1.1 %d OK\r\n\r\n", conn->status_code);
-  } else if (rc == -1) {
-    send_http_error(conn, 500, http_500_error,
-                    "put_dir(%s): %s", path, strerror(ERRNO));
-  } else if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
-    mg_fclose(&file);
-    send_http_error(conn, 500, http_500_error,
-                    "fopen(%s): %s", path, strerror(ERRNO));
-  } else {
-    fclose_on_exec(&file);
-    range = mg_get_header(conn, "Content-Range");
-    r1 = r2 = 0;
-    if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
-      conn->status_code = 206;
-      fseeko(file.fp, r1, SEEK_SET);
-    }
-    if (forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
-      mg_printf(conn, "HTTP/1.1 %d OK\r\n\r\n", conn->status_code);
-    }
-    mg_fclose(&file);
-  }
-}
-
-static void send_ssi_file(struct mg_connection *, const char *,
-                          struct file *, int);
-
-static void do_ssi_include(struct mg_connection *conn, const char *ssi,
-                           char *tag, int include_level) {
-  char file_name[MG_BUF_LEN], path[PATH_MAX], *p;
-  struct file file = STRUCT_FILE_INITIALIZER;
-
-  // sscanf() is safe here, since send_ssi_file() also uses buffer
-  // of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN.
-  if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
-    // File name is relative to the webserver root
-    (void) mg_snprintf(conn, path, sizeof(path), "%s%c%s",
-        conn->ctx->config[DOCUMENT_ROOT], '/', file_name);
-  } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1) {
-    // File name is relative to the webserver working directory
-    // or it is absolute system path
-    (void) mg_snprintf(conn, path, sizeof(path), "%s", file_name);
-  } else if (sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
-    // File name is relative to the currect document
-    (void) mg_snprintf(conn, path, sizeof(path), "%s", ssi);
-    if ((p = strrchr(path, '/')) != NULL) {
-      p[1] = '\0';
-    }
-    (void) mg_snprintf(conn, path + strlen(path),
-        sizeof(path) - strlen(path), "%s", file_name);
-  } else {
-    cry(conn, "Bad SSI #include: [%s]", tag);
-    return;
-  }
-
-  if (!mg_fopen(conn, path, "rb", &file)) {
-    cry(conn, "Cannot open SSI #include: [%s]: fopen(%s): %s",
-        tag, path, strerror(ERRNO));
-  } else {
-    fclose_on_exec(&file);
-    if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
-                     strlen(conn->ctx->config[SSI_EXTENSIONS]), path) > 0) {
-      send_ssi_file(conn, path, &file, include_level + 1);
-    } else {
-      send_file_data(conn, &file, 0, INT64_MAX);
-    }
-    mg_fclose(&file);
-  }
-}
-
-#if !defined(NO_POPEN)
-static void do_ssi_exec(struct mg_connection *conn, char *tag) {
-  char cmd[MG_BUF_LEN];
-  struct file file = STRUCT_FILE_INITIALIZER;
-
-  if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
-    cry(conn, "Bad SSI #exec: [%s]", tag);
-  } else if ((file.fp = popen(cmd, "r")) == NULL) {
-    cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
-  } else {
-    send_file_data(conn, &file, 0, INT64_MAX);
-    pclose(file.fp);
-  }
-}
-#endif // !NO_POPEN
-
-static int mg_fgetc(struct file *filep, int offset) {
-  if (filep->membuf != NULL && offset >=0 && offset < filep->size) {
-    return ((unsigned char *) filep->membuf)[offset];
-  } else if (filep->fp != NULL) {
-    return fgetc(filep->fp);
-  } else {
-    return EOF;
-  }
-}
-
-static void send_ssi_file(struct mg_connection *conn, const char *path,
-                          struct file *filep, int include_level) {
-  char buf[MG_BUF_LEN];
-  int ch, offset, len, in_ssi_tag;
-
-  if (include_level > 10) {
-    cry(conn, "SSI #include level is too deep (%s)", path);
-    return;
-  }
-
-  in_ssi_tag = len = offset = 0;
-  while ((ch = mg_fgetc(filep, offset)) != EOF) {
-    if (in_ssi_tag && ch == '>') {
-      in_ssi_tag = 0;
-      buf[len++] = (char) ch;
-      buf[len] = '\0';
-      assert(len <= (int) sizeof(buf));
-      if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
-        // Not an SSI tag, pass it
-        (void) mg_write(conn, buf, (size_t) len);
-      } else {
-        if (!memcmp(buf + 5, "include", 7)) {
-          do_ssi_include(conn, path, buf + 12, include_level);
-#if !defined(NO_POPEN)
-        } else if (!memcmp(buf + 5, "exec", 4)) {
-          do_ssi_exec(conn, buf + 9);
-#endif // !NO_POPEN
-        } else {
-          cry(conn, "%s: unknown SSI " "command: \"%s\"", path, buf);
-        }
-      }
-      len = 0;
-    } else if (in_ssi_tag) {
-      if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
-        // Not an SSI tag
-        in_ssi_tag = 0;
-      } else if (len == (int) sizeof(buf) - 2) {
-        cry(conn, "%s: SSI tag is too large", path);
-        len = 0;
-      }
-      buf[len++] = ch & 0xff;
-    } else if (ch == '<') {
-      in_ssi_tag = 1;
-      if (len > 0) {
-        mg_write(conn, buf, (size_t) len);
-      }
-      len = 0;
-      buf[len++] = ch & 0xff;
-    } else {
-      buf[len++] = ch & 0xff;
-      if (len == (int) sizeof(buf)) {
-        mg_write(conn, buf, (size_t) len);
-        len = 0;
-      }
-    }
-  }
-
-  // Send the rest of buffered data
-  if (len > 0) {
-    mg_write(conn, buf, (size_t) len);
-  }
-}
-
-static void handle_ssi_file_request(struct mg_connection *conn,
-                                    const char *path) {
-  struct file file = STRUCT_FILE_INITIALIZER;
-
-  if (!mg_fopen(conn, path, "rb", &file)) {
-    send_http_error(conn, 500, http_500_error, "fopen(%s): %s", path,
-                    strerror(ERRNO));
-  } else {
-    conn->must_close = 1;
-    fclose_on_exec(&file);
-    mg_printf(conn, "HTTP/1.1 200 OK\r\n"
-              "Content-Type: text/html\r\nConnection: %s\r\n\r\n",
-              suggest_connection_header(conn));
-    send_ssi_file(conn, path, &file, 0);
-    mg_fclose(&file);
-  }
-}
-
-static void send_options(struct mg_connection *conn) {
-  conn->status_code = 200;
-
-  mg_printf(conn, "%s", "HTTP/1.1 200 OK\r\n"
-            "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, PROPFIND, MKCOL\r\n"
-            "DAV: 1\r\n\r\n");
-}
-
-// Writes PROPFIND properties for a collection element
-static void print_props(struct mg_connection *conn, const char* uri,
-                        struct file *filep) {
-  char mtime[64];
-  gmt_time_string(mtime, sizeof(mtime), &filep->modification_time);
-  conn->num_bytes_sent += mg_printf(conn,
-      "<d:response>"
-       "<d:href>%s</d:href>"
-       "<d:propstat>"
-        "<d:prop>"
-         "<d:resourcetype>%s</d:resourcetype>"
-         "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
-         "<d:getlastmodified>%s</d:getlastmodified>"
-        "</d:prop>"
-        "<d:status>HTTP/1.1 200 OK</d:status>"
-       "</d:propstat>"
-      "</d:response>\n",
-      uri,
-      filep->is_directory ? "<d:collection/>" : "",
-      filep->size,
-      mtime);
-}
-
-static void print_dav_dir_entry(struct de *de, void *data) {
-  char href[PATH_MAX];
-  char href_encoded[PATH_MAX];
-  struct mg_connection *conn = (struct mg_connection *) data;
-  mg_snprintf(conn, href, sizeof(href), "%s%s",
-              conn->request_info.uri, de->file_name);
-  mg_url_encode(href, href_encoded, PATH_MAX-1);
-  print_props(conn, href_encoded, &de->file);
-}
-
-static void handle_propfind(struct mg_connection *conn, const char *path,
-                            struct file *filep) {
-  const char *depth = mg_get_header(conn, "Depth");
-
-  conn->must_close = 1;
-  conn->status_code = 207;
-  mg_printf(conn, "HTTP/1.1 207 Multi-Status\r\n"
-            "Connection: close\r\n"
-            "Content-Type: text/xml; charset=utf-8\r\n\r\n");
-
-  conn->num_bytes_sent += mg_printf(conn,
-      "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
-      "<d:multistatus xmlns:d='DAV:'>\n");
-
-  // Print properties for the requested resource itself
-  print_props(conn, conn->request_info.uri, filep);
-
-  // If it is a directory, print directory entries too if Depth is not 0
-  if (filep->is_directory &&
-      !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes") &&
-      (depth == NULL || strcmp(depth, "0") != 0)) {
-    scan_directory(conn, path, conn, &print_dav_dir_entry);
-  }
-
-  conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
-}
-
-#if defined(USE_WEBSOCKET)
-
-// START OF SHA-1 code
-// Copyright(c) By Steve Reid <steve@edmweb.com>
-#define SHA1HANDSOFF
-#if defined(__sun)
-#include "solarisfixes.h"
-#endif
-
-union char64long16 { unsigned char c[64]; uint32_t l[16]; };
-
-#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
-
-static uint32_t blk0(union char64long16 *block, int i) {
-  // Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN
-  if (!is_big_endian()) {
-    block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
-      (rol(block->l[i], 8) & 0x00FF00FF);
-  }
-  return block->l[i];
-}
-
-#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
-    ^block->l[(i+2)&15]^block->l[i&15],1))
-#define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(block, i)+0x5A827999+rol(v,5);w=rol(w,30);
-#define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
-#define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
-#define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
-#define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
-
-typedef struct {
-    uint32_t state[5];
-    uint32_t count[2];
-    unsigned char buffer[64];
-} SHA1_CTX;
-
-static void SHA1Transform(uint32_t state[5], const unsigned char buffer[64]) {
-  uint32_t a, b, c, d, e;
-  union char64long16 block[1];
-
-  memcpy(block, buffer, 64);
-  a = state[0];
-  b = state[1];
-  c = state[2];
-  d = state[3];
-  e = state[4];
-  R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3);
-  R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7);
-  R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11);
-  R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15);
-  R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19);
-  R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23);
-  R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27);
-  R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31);
-  R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35);
-  R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39);
-  R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43);
-  R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47);
-  R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51);
-  R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55);
-  R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59);
-  R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63);
-  R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67);
-  R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71);
-  R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75);
-  R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79);
-  state[0] += a;
-  state[1] += b;
-  state[2] += c;
-  state[3] += d;
-  state[4] += e;
-  a = b = c = d = e = 0;
-  memset(block, '\0', sizeof(block));
-}
-
-static void SHA1Init(SHA1_CTX* context) {
-  context->state[0] = 0x67452301;
-  context->state[1] = 0xEFCDAB89;
-  context->state[2] = 0x98BADCFE;
-  context->state[3] = 0x10325476;
-  context->state[4] = 0xC3D2E1F0;
-  context->count[0] = context->count[1] = 0;
-}
-
-static void SHA1Update(SHA1_CTX* context, const unsigned char* data,
-                       uint32_t len) {
-  uint32_t i, j;
-
-  j = context->count[0];
-  if ((context->count[0] += len << 3) < j)
-    context->count[1]++;
-  context->count[1] += (len>>29);
-  j = (j >> 3) & 63;
-  if ((j + len) > 63) {
-    memcpy(&context->buffer[j], data, (i = 64-j));
-    SHA1Transform(context->state, context->buffer);
-    for ( ; i + 63 < len; i += 64) {
-      SHA1Transform(context->state, &data[i]);
-    }
-    j = 0;
-  }
-  else i = 0;
-  memcpy(&context->buffer[j], &data[i], len - i);
-}
-
-static void SHA1Final(unsigned char digest[20], SHA1_CTX* context) {
-  unsigned i;
-  unsigned char finalcount[8], c;
-
-  for (i = 0; i < 8; i++) {
-    finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
-                                     >> ((3-(i & 3)) * 8) ) & 255);
-  }
-  c = 0200;
-  SHA1Update(context, &c, 1);
-  while ((context->count[0] & 504) != 448) {
-    c = 0000;
-    SHA1Update(context, &c, 1);
-  }
-  SHA1Update(context, finalcount, 8);
-  for (i = 0; i < 20; i++) {
-    digest[i] = (unsigned char)
-      ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
-  }
-  memset(context, '\0', sizeof(*context));
-  memset(&finalcount, '\0', sizeof(finalcount));
-}
-// END OF SHA1 CODE
-
-static void base64_encode(const unsigned char *src, int src_len, char *dst) {
-  static const char *b64 =
-    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
-  int i, j, a, b, c;
-
-  for (i = j = 0; i < src_len; i += 3) {
-    a = src[i];
-    b = i + 1 >= src_len ? 0 : src[i + 1];
-    c = i + 2 >= src_len ? 0 : src[i + 2];
-
-    dst[j++] = b64[a >> 2];
-    dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
-    if (i + 1 < src_len) {
-      dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
-    }
-    if (i + 2 < src_len) {
-      dst[j++] = b64[c & 63];
-    }
-  }
-  while (j % 4 != 0) {
-    dst[j++] = '=';
-  }
-  dst[j++] = '\0';
-}
-
-static void send_websocket_handshake(struct mg_connection *conn) {
-  static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
-  char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
-  SHA1_CTX sha_ctx;
-
-  mg_snprintf(conn, buf, sizeof(buf), "%s%s",
-              mg_get_header(conn, "Sec-WebSocket-Key"), magic);
-  SHA1Init(&sha_ctx);
-  SHA1Update(&sha_ctx, (unsigned char *) buf, strlen(buf));
-  SHA1Final((unsigned char *) sha, &sha_ctx);
-  base64_encode((unsigned char *) sha, sizeof(sha), b64_sha);
-  mg_printf(conn, "%s%s%s",
-            "HTTP/1.1 101 Switching Protocols\r\n"
-            "Upgrade: websocket\r\n"
-            "Connection: Upgrade\r\n"
-            "Sec-WebSocket-Accept: ", b64_sha, "\r\n\r\n");
-}
-
-static void read_websocket(struct mg_connection *conn) {
-  // Pointer to the beginning of the portion of the incoming websocket message
-  // queue. The original websocket upgrade request is never removed,
-  // so the queue begins after it.
-  unsigned char *buf = (unsigned char *) conn->buf + conn->request_len;
-  int bits, n, stop = 0;
-  size_t i, len, mask_len, data_len, header_len, body_len;
-  // data points to the place where the message is stored when passed to the
-  // websocket_data callback. This is either mem on the stack,
-  // or a dynamically allocated buffer if it is too large.
-  char mem[4 * 1024], mask[4], *data;
-
-  assert(conn->content_len == 0);
-
-  // Loop continuously, reading messages from the socket, invoking the callback,
-  // and waiting repeatedly until an error occurs.
-  while (!stop) {
-    header_len = 0;
-    // body_len is the length of the entire queue in bytes
-    // len is the length of the current message
-    // data_len is the length of the current message's data payload
-    // header_len is the length of the current message's header
-    if ((body_len = conn->data_len - conn->request_len) >= 2) {
-      len = buf[1] & 127;
-      mask_len = buf[1] & 128 ? 4 : 0;
-      if (len < 126 && body_len >= mask_len) {
-        data_len = len;
-        header_len = 2 + mask_len;
-      } else if (len == 126 && body_len >= 4 + mask_len) {
-        header_len = 4 + mask_len;
-        data_len = ((((int) buf[2]) << 8) + buf[3]);
-      } else if (body_len >= 10 + mask_len) {
-        header_len = 10 + mask_len;
-        data_len = (((uint64_t) htonl(* (uint32_t *) &buf[2])) << 32) +
-          htonl(* (uint32_t *) &buf[6]);
-      }
-    }
-
-    // Data layout is as follows:
-    //  conn->buf               buf
-    //     v                     v              frame1           | frame2
-    //     |---------------------|----------------|--------------|-------
-    //     |                     |<--header_len-->|<--data_len-->|
-    //     |<-conn->request_len->|<-----body_len----------->|
-    //     |<-------------------conn->data_len------------->|
-
-    if (header_len > 0) {
-      // Allocate space to hold websocket payload
-      data = mem;
-      if (data_len > sizeof(mem) && (data = malloc(data_len)) == NULL) {
-        // Allocation failed, exit the loop and then close the connection
-        // TODO: notify user about the failure
-        break;
-      }
-
-      // Save mask and bits, otherwise it may be clobbered by memmove below
-      bits = buf[0];
-      memcpy(mask, buf + header_len - mask_len, mask_len);
-
-      // Read frame payload into the allocated buffer.
-      assert(body_len >= header_len);
-      if (data_len + header_len > body_len) {
-        len = body_len - header_len;
-        memcpy(data, buf + header_len, len);
-        // TODO: handle pull error
-        pull_all(NULL, conn, data + len, data_len - len);
-        conn->data_len = conn->request_len;
-      } else {
-        len = data_len + header_len;
-        memcpy(data, buf + header_len, data_len);
-        memmove(buf, buf + len, body_len - len);
-        conn->data_len -= len;
-      }
-
-      // Apply mask if necessary
-      if (mask_len > 0) {
-        for (i = 0; i < data_len; i++) {
-          data[i] ^= mask[i % 4];
-        }
-      }
-
-      // Exit the loop if callback signalled to exit,
-      // or "connection close" opcode received.
-      if ((conn->ctx->callbacks.websocket_data != NULL &&
-          !conn->ctx->callbacks.websocket_data(conn, bits, data, data_len)) ||
-          (bits & 0xf) == 8) {  // Opcode == 8, connection close
-        stop = 1;
-      }
-
-      if (data != mem) {
-        free(data);
-      }
-      // Not breaking the loop, process next websocket frame.
-    } else {
-      // Buffering websocket request
-      if ((n = pull(NULL, conn, conn->buf + conn->data_len,
-                    conn->buf_size - conn->data_len)) <= 0) {
-        break;
-      }
-      conn->data_len += n;
-    }
-  }
-}
-
-int mg_websocket_write(struct mg_connection* conn, int opcode,
-                       const char *data, size_t data_len) {
-    unsigned char *copy;
-    size_t copy_len = 0;
-    int retval = -1;
-
-    if ((copy = (unsigned char *) malloc(data_len + 10)) == NULL) {
-      return -1;
-    }
-
-    copy[0] = 0x80 + (opcode & 0x0f);
-
-    // Frame format: http://tools.ietf.org/html/rfc6455#section-5.2
-    if (data_len < 126) {
-      // Inline 7-bit length field
-      copy[1] = data_len;
-      memcpy(copy + 2, data, data_len);
-      copy_len = 2 + data_len;
-    } else if (data_len <= 0xFFFF) {
-      // 16-bit length field
-      copy[1] = 126;
-      * (uint16_t *) (copy + 2) = htons(data_len);
-      memcpy(copy + 4, data, data_len);
-      copy_len = 4 + data_len;
-    } else {
-      // 64-bit length field
-      copy[1] = 127;
-      * (uint32_t *) (copy + 2) = htonl((uint64_t) data_len >> 32);
-      * (uint32_t *) (copy + 6) = htonl(data_len & 0xffffffff);
-      memcpy(copy + 10, data, data_len);
-      copy_len = 10 + data_len;
-    }
-
-    // Not thread safe
-    if (copy_len > 0) {
-      retval = mg_write(conn, copy, copy_len);
-    }
-    free(copy);
-
-    return retval;
-}
-
-static void handle_websocket_request(struct mg_connection *conn) {
-  const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
-  if (version == NULL || strcmp(version, "13") != 0) {
-    send_http_error(conn, 426, "Upgrade Required", "%s", "Upgrade Required");
-  } else if (conn->ctx->callbacks.websocket_connect != NULL &&
-             conn->ctx->callbacks.websocket_connect(conn) != 0) {
-    // Callback has returned non-zero, do not proceed with handshake
-  } else {
-    send_websocket_handshake(conn);
-    if (conn->ctx->callbacks.websocket_ready != NULL) {
-      conn->ctx->callbacks.websocket_ready(conn);
-    }
-    read_websocket(conn);
-  }
-}
-
-static int is_websocket_request(const struct mg_connection *conn) {
-  const char *host, *upgrade, *connection, *version, *key;
-
-  host = mg_get_header(conn, "Host");
-  upgrade = mg_get_header(conn, "Upgrade");
-  connection = mg_get_header(conn, "Connection");
-  key = mg_get_header(conn, "Sec-WebSocket-Key");
-  version = mg_get_header(conn, "Sec-WebSocket-Version");
-
-  return host != NULL && upgrade != NULL && connection != NULL &&
-    key != NULL && version != NULL &&
-    mg_strcasestr(upgrade, "websocket") != NULL &&
-    mg_strcasestr(connection, "Upgrade") != NULL;
-}
-#endif // !USE_WEBSOCKET
-
-static int isbyte(int n) {
-  return n >= 0 && n <= 255;
-}
-
-static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
-  int n, a, b, c, d, slash = 32, len = 0;
-
-  if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
-      sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
-      isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) &&
-      slash >= 0 && slash < 33) {
-    len = n;
-    *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | d;
-    *mask = slash ? 0xffffffffU << (32 - slash) : 0;
-  }
-
-  return len;
-}
-
-static int set_throttle(const char *spec, uint32_t remote_ip, const char *uri) {
-  int throttle = 0;
-  struct vec vec, val;
-  uint32_t net, mask;
-  char mult;
-  double v;
-
-  while ((spec = next_option(spec, &vec, &val)) != NULL) {
-    mult = ',';
-    if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0 ||
-        (lowercase(&mult) != 'k' && lowercase(&mult) != 'm' && mult != ',')) {
-      continue;
-    }
-    v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576 : 1;
-    if (vec.len == 1 && vec.ptr[0] == '*') {
-      throttle = (int) v;
-    } else if (parse_net(vec.ptr, &net, &mask) > 0) {
-      if ((remote_ip & mask) == net) {
-        throttle = (int) v;
-      }
-    } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
-      throttle = (int) v;
-    }
-  }
-
-  return throttle;
-}
-
-static uint32_t get_remote_ip(const struct mg_connection *conn) {
-  return ntohl(* (uint32_t *) &conn->client.rsa.sin.sin_addr);
-}
-
-#ifdef USE_LUA
-#include "mod_lua.c"
-#endif // USE_LUA
-
-int mg_upload(struct mg_connection *conn, const char *destination_dir) {
-  const char *content_type_header, *boundary_start;
-  char buf[MG_BUF_LEN], path[PATH_MAX], fname[1024], boundary[100], *s;
-  FILE *fp;
-  int bl, n, i, j, headers_len, boundary_len, eof,
-      len = 0, num_uploaded_files = 0;
-
-  // Request looks like this:
-  //
-  // POST /upload HTTP/1.1
-  // Host: 127.0.0.1:8080
-  // Content-Length: 244894
-  // Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryRVr
-  //
-  // ------WebKitFormBoundaryRVr
-  // Content-Disposition: form-data; name="file"; filename="accum.png"
-  // Content-Type: image/png
-  //
-  //  <89>PNG
-  //  <PNG DATA>
-  // ------WebKitFormBoundaryRVr
-
-  // Extract boundary string from the Content-Type header
-  if ((content_type_header = mg_get_header(conn, "Content-Type")) == NULL ||
-      (boundary_start = mg_strcasestr(content_type_header,
-                                      "boundary=")) == NULL ||
-      (sscanf(boundary_start, "boundary=\"%99[^\"]\"", boundary) == 0 &&
-       sscanf(boundary_start, "boundary=%99s", boundary) == 0) ||
-      boundary[0] == '\0') {
-    return num_uploaded_files;
-  }
-
-  boundary_len = strlen(boundary);
-  bl = boundary_len + 4;  // \r\n--<boundary>
-  for (;;) {
-    // Pull in headers
-    assert(len >= 0 && len <= (int) sizeof(buf));
-    while ((n = mg_read(conn, buf + len, sizeof(buf) - len)) > 0) {
-      len += n;
-    }
-    if ((headers_len = get_request_len(buf, len)) <= 0) {
-      break;
-    }
-
-    // Fetch file name.
-    fname[0] = '\0';
-    for (i = j = 0; i < headers_len; i++) {
-      if (buf[i] == '\r' && buf[i + 1] == '\n') {
-        buf[i] = buf[i + 1] = '\0';
-        // TODO(lsm): don't expect filename to be the 3rd field,
-        // parse the header properly instead.
-        sscanf(&buf[j], "Content-Disposition: %*s %*s filename=\"%1023[^\"]",
-               fname);
-        j = i + 2;
-      }
-    }
-
-    // Give up if the headers are not what we expect
-    if (fname[0] == '\0') {
-      break;
-    }
-
-    // Move data to the beginning of the buffer
-    assert(len >= headers_len);
-    memmove(buf, &buf[headers_len], len - headers_len);
-    len -= headers_len;
-
-    // We open the file with exclusive lock held. This guarantee us
-    // there is no other thread can save into the same file simultaneously.
-    fp = NULL;
-    // Construct destination file name. Do not allow paths to have slashes.
-    if ((s = strrchr(fname, '/')) == NULL && 
-		(s = strrchr(fname, '\\')) == NULL) {
-            s = fname;
-    }
-    
-    // Open file in binary mode. TODO: set an exclusive lock.
-    snprintf(path, sizeof(path), "%s/%s", destination_dir, s);
-    if ((fp = fopen(path, "wb")) == NULL) {
-      break;
-    }
-
-    // Read POST data, write into file until boundary is found.
-    eof = n = 0;
-    do {
-      len += n;
-      for (i = 0; i < len - bl; i++) {
-        if (!memcmp(&buf[i], "\r\n--", 4) &&
-            !memcmp(&buf[i + 4], boundary, boundary_len)) {
-          // Found boundary, that's the end of file data.
-          fwrite(buf, 1, i, fp);
-          eof = 1;
-          memmove(buf, &buf[i + bl], len - (i + bl));
-          len -= i + bl;
-          break;
-        }
-      }
-      if (!eof && len > bl) {
-        fwrite(buf, 1, len - bl, fp);
-        memmove(buf, &buf[len - bl], bl);
-        len = bl;
-      }
-    } while (!eof && (n = mg_read(conn, buf + len, sizeof(buf) - len)) > 0);
-    fclose(fp);
-    if (eof) {
-      num_uploaded_files++;
-      if (conn->ctx->callbacks.upload != NULL) {
-        conn->ctx->callbacks.upload(conn, path);
-      }
-    }
-  }
-
-  return num_uploaded_files;
-}
-
-static int is_put_or_delete_request(const struct mg_connection *conn) {
-  const char *s = conn->request_info.request_method;
-  return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE") || !strcmp(s, "MKCOL"));
-}
-
-static int get_first_ssl_listener_index(const struct mg_context *ctx) {
-  int i, index = -1;
-  for (i = 0; index == -1 && i < ctx->num_listening_sockets; i++) {
-    index = ctx->listening_sockets[i].is_ssl ? i : -1;
-  }
-  return index;
-}
-
-static void redirect_to_https_port(struct mg_connection *conn, int ssl_index) {
-  char host[1025];
-  const char *host_header;
-
-  if ((host_header = mg_get_header(conn, "Host")) == NULL ||
-      sscanf(host_header, "%1024[^:]", host) == 0) {
-    // Cannot get host from the Host: header. Fallback to our IP address.
-    sockaddr_to_string(host, sizeof(host), &conn->client.lsa);
-  }
-
-  mg_printf(conn, "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s\r\n\r\n",
-            host, (int) ntohs(conn->ctx->listening_sockets[ssl_index].
-                              lsa.sin.sin_port), conn->request_info.uri);
-}
-
-// This is the heart of the Mongoose's logic.
-// This function is called when the request is read, parsed and validated,
-// and Mongoose must decide what action to take: serve a file, or
-// a directory, or call embedded function, etcetera.
-static void handle_request(struct mg_connection *conn) {
-  struct mg_request_info *ri = &conn->request_info;
-  char path[PATH_MAX];
-  int uri_len, ssl_index;
-  struct file file = STRUCT_FILE_INITIALIZER;
-
-  if ((conn->request_info.query_string = strchr(ri->uri, '?')) != NULL) {
-    * ((char *) conn->request_info.query_string++) = '\0';
-  }
-  uri_len = (int) strlen(ri->uri);
-  mg_url_decode(ri->uri, uri_len, (char *) ri->uri, uri_len + 1, 0);
-  remove_double_dots_and_double_slashes((char *) ri->uri);
-  convert_uri_to_file_name(conn, path, sizeof(path), &file);
-  conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
-                                get_remote_ip(conn), ri->uri);
-
-  DEBUG_TRACE(("%s", ri->uri));
-  // Perform redirect and auth checks before calling begin_request() handler.
-  // Otherwise, begin_request() would need to perform auth checks and redirects.
-  if (!conn->client.is_ssl && conn->client.ssl_redir &&
-      (ssl_index = get_first_ssl_listener_index(conn->ctx)) > -1) {
-    redirect_to_https_port(conn, ssl_index);
-  } else if (!is_put_or_delete_request(conn) &&
-             !check_authorization(conn, path)) {
-    send_authorization_request(conn);
-  } else if (conn->ctx->callbacks.begin_request != NULL &&
-      conn->ctx->callbacks.begin_request(conn)) {
-    // Do nothing, callback has served the request
-#if defined(USE_WEBSOCKET)
-  } else if (is_websocket_request(conn)) {
-    handle_websocket_request(conn);
-#endif
-  } else if (!strcmp(ri->request_method, "OPTIONS")) {
-    send_options(conn);
-  } else if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
-    send_http_error(conn, 404, "Not Found", "Not Found");
-  } else if (is_put_or_delete_request(conn) &&
-             (is_authorized_for_put(conn) != 1)) {
-    send_authorization_request(conn);
-  } else if (!strcmp(ri->request_method, "PUT")) {
-    put_file(conn, path);
-  } else if (!strcmp(ri->request_method, "MKCOL")) {
-    mkcol(conn, path);
-  } else if (!strcmp(ri->request_method, "DELETE")) {
-      struct de de;
-      memset(&de.file, 0, sizeof(de.file));
-      if(!mg_stat(conn, path, &de.file)) {
-          send_http_error(conn, 404, "Not Found", "%s", "File not found");
-      } else {
-          if(de.file.modification_time) {
-              if(de.file.is_directory) {
-                  remove_directory(conn, path);
-                  send_http_error(conn, 204, "No Content", "%s", "");
-              } else if (mg_remove(path) == 0) {
-                  send_http_error(conn, 204, "No Content", "%s", "");
-              } else {
-                  send_http_error(conn, 423, "Locked", "remove(%s): %s", path,
-                          strerror(ERRNO));
-              }
-          }
-          else {
-              send_http_error(conn, 500, http_500_error, "remove(%s): %s", path,
-                    strerror(ERRNO));
-          }
-      }
-  } else if ((file.membuf == NULL && file.modification_time == (time_t) 0) ||
-             must_hide_file(conn, path)) {
-    send_http_error(conn, 404, "Not Found", "%s", "File not found");
-  } else if (file.is_directory && ri->uri[uri_len - 1] != '/') {
-    mg_printf(conn, "HTTP/1.1 301 Moved Permanently\r\n"
-              "Location: %s/\r\n\r\n", ri->uri);
-  } else if (!strcmp(ri->request_method, "PROPFIND")) {
-    handle_propfind(conn, path, &file);
-  } else if (file.is_directory &&
-             !substitute_index_file(conn, path, sizeof(path), &file)) {
-    if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")) {
-      handle_directory_request(conn, path);
-    } else {
-      send_http_error(conn, 403, "Directory Listing Denied",
-          "Directory listing denied");
-    }
-#ifdef USE_LUA
-  } else if (match_prefix("**.lp$", 6, path) > 0) {
-    handle_lsp_request(conn, path, &file, NULL);
-#endif
-#if !defined(NO_CGI)
-  } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
-                          strlen(conn->ctx->config[CGI_EXTENSIONS]),
-                          path) > 0) {
-    if (strcmp(ri->request_method, "POST") &&
-        strcmp(ri->request_method, "HEAD") &&
-        strcmp(ri->request_method, "GET")) {
-      send_http_error(conn, 501, "Not Implemented",
-                      "Method %s is not implemented", ri->request_method);
-    } else {
-      handle_cgi_request(conn, path);
-    }
-#endif // !NO_CGI
-  } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
-                          strlen(conn->ctx->config[SSI_EXTENSIONS]),
-                          path) > 0) {
-    handle_ssi_file_request(conn, path);
-  } else if (is_not_modified(conn, &file)) {
-    send_http_error(conn, 304, "Not Modified", "%s", "");
-  } else {
-    handle_file_request(conn, path, &file);
-  }
-}
-
-static void close_all_listening_sockets(struct mg_context *ctx) {
-  int i;
-  for (i = 0; i < ctx->num_listening_sockets; i++) {
-    closesocket(ctx->listening_sockets[i].sock);
-  }
-  free(ctx->listening_sockets);
-}
-
-// Valid listening port specification is: [ip_address:]port[s]
-// Examples: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
-// TODO(lsm): add parsing of the IPv6 address
-static int parse_port_string(const struct vec *vec, struct socket *so) {
-  int a, b, c, d, port, len;
-
-  // MacOS needs that. If we do not zero it, subsequent bind() will fail.
-  // Also, all-zeroes in the socket address means binding to all addresses
-  // for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).
-  memset(so, 0, sizeof(*so));
-
-  if (sscanf(vec->ptr, "%d.%d.%d.%d:%d%n", &a, &b, &c, &d, &port, &len) == 5) {
-    // Bind to a specific IPv4 address
-    so->lsa.sin.sin_addr.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
-  } else if (sscanf(vec->ptr, "%d%n", &port, &len) != 1 ||
-             len <= 0 ||
-             len > (int) vec->len ||
-             port < 1 ||
-             port > 65535 ||
-             (vec->ptr[len] && vec->ptr[len] != 's' &&
-              vec->ptr[len] != 'r' && vec->ptr[len] != ',')) {
-    return 0;
-  }
-
-  so->is_ssl = vec->ptr[len] == 's';
-  so->ssl_redir = vec->ptr[len] == 'r';
-#if defined(USE_IPV6)
-  so->lsa.sin6.sin6_family = AF_INET6;
-  so->lsa.sin6.sin6_port = htons((uint16_t) port);
-#else
-  so->lsa.sin.sin_family = AF_INET;
-  so->lsa.sin.sin_port = htons((uint16_t) port);
-#endif
-
-  return 1;
-}
-
-static int set_ports_option(struct mg_context *ctx) {
-  const char *list = ctx->config[LISTENING_PORTS];
-  int on = 1, success = 1;
-#if defined(USE_IPV6)
-  int off = 0;
-#endif
-  struct vec vec;
-  struct socket so, *ptr;
-
-  while (success && (list = next_option(list, &vec, NULL)) != NULL) {
-    if (!parse_port_string(&vec, &so)) {
-      cry(fc(ctx), "%s: %.*s: invalid port spec. Expecting list of: %s",
-          __func__, (int) vec.len, vec.ptr, "[IP_ADDRESS:]PORT[s|p]");
-      success = 0;
-    } else if (so.is_ssl && ctx->ssl_ctx == NULL) {
-      cry(fc(ctx), "Cannot add SSL socket, is -ssl_certificate option set?");
-      success = 0;
-    } else if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6)) ==
-               INVALID_SOCKET ||
-               // On Windows, SO_REUSEADDR is recommended only for
-               // broadcast UDP sockets
-               setsockopt(so.sock, SOL_SOCKET, SO_REUSEADDR,
-                          (void *) &on, sizeof(on)) != 0 ||
-#if defined(USE_IPV6)
-               setsockopt(so.sock, IPPROTO_IPV6, IPV6_V6ONLY, (void *) &off,
-                          sizeof(off)) != 0 ||
-#endif
-               bind(so.sock, &so.lsa.sa, sizeof(so.lsa)) != 0 ||
-               listen(so.sock, SOMAXCONN) != 0) {
-      cry(fc(ctx), "%s: cannot bind to %.*s: %s", __func__,
-          (int) vec.len, vec.ptr, strerror(ERRNO));
-      closesocket(so.sock);
-      success = 0;
-    } else if ((ptr = realloc(ctx->listening_sockets,
-                              (ctx->num_listening_sockets + 1) *
-                              sizeof(ctx->listening_sockets[0]))) == NULL) {
-      closesocket(so.sock);
-      success = 0;
-    } else {
-      set_close_on_exec(so.sock);
-      ctx->listening_sockets = ptr;
-      ctx->listening_sockets[ctx->num_listening_sockets] = so;
-      ctx->num_listening_sockets++;
-    }
-  }
-
-  if (!success) {
-    close_all_listening_sockets(ctx);
-  }
-
-  return success;
-}
-
-static void log_header(const struct mg_connection *conn, const char *header,
-                       FILE *fp) {
-  const char *header_value;
-
-  if ((header_value = mg_get_header(conn, header)) == NULL) {
-    (void) fprintf(fp, "%s", " -");
-  } else {
-    (void) fprintf(fp, " \"%s\"", header_value);
-  }
-}
-
-static void log_access(const struct mg_connection *conn) {
-  const struct mg_request_info *ri;
-  FILE *fp;
-  char date[64], src_addr[IP_ADDR_STR_LEN];
-
-  fp = conn->ctx->config[ACCESS_LOG_FILE] == NULL ?  NULL :
-    fopen(conn->ctx->config[ACCESS_LOG_FILE], "a+");
-
-  if (fp == NULL)
-    return;
-
-  strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z",
-           localtime(&conn->birth_time));
-
-  ri = &conn->request_info;
-  flockfile(fp);
-
-  sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
-  fprintf(fp, "%s - %s [%s] \"%s %s HTTP/%s\" %d %" INT64_FMT,
-          src_addr, ri->remote_user == NULL ? "-" : ri->remote_user, date,
-          ri->request_method ? ri->request_method : "-",
-          ri->uri ? ri->uri : "-", ri->http_version,
-          conn->status_code, conn->num_bytes_sent);
-  log_header(conn, "Referer", fp);
-  log_header(conn, "User-Agent", fp);
-  fputc('\n', fp);
-  fflush(fp);
-
-  funlockfile(fp);
-  fclose(fp);
-}
-
-// Verify given socket address against the ACL.
-// Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
-static int check_acl(struct mg_context *ctx, uint32_t remote_ip) {
-  int allowed, flag;
-  uint32_t net, mask;
-  struct vec vec;
-  const char *list = ctx->config[ACCESS_CONTROL_LIST];
-
-  // If any ACL is set, deny by default
-  allowed = list == NULL ? '+' : '-';
-
-  while ((list = next_option(list, &vec, NULL)) != NULL) {
-    flag = vec.ptr[0];
-    if ((flag != '+' && flag != '-') ||
-        parse_net(&vec.ptr[1], &net, &mask) == 0) {
-      cry(fc(ctx), "%s: subnet must be [+|-]x.x.x.x[/x]", __func__);
-      return -1;
-    }
-
-    if (net == (remote_ip & mask)) {
-      allowed = flag;
-    }
-  }
-
-  return allowed == '+';
-}
-
-#if !defined(_WIN32)
-static int set_uid_option(struct mg_context *ctx) {
-  struct passwd *pw;
-  const char *uid = ctx->config[RUN_AS_USER];
-  int success = 0;
-
-  if (uid == NULL) {
-    success = 1;
-  } else {
-    if ((pw = getpwnam(uid)) == NULL) {
-      cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
-    } else if (setgid(pw->pw_gid) == -1) {
-      cry(fc(ctx), "%s: setgid(%s): %s", __func__, uid, strerror(errno));
-    } else if (setuid(pw->pw_uid) == -1) {
-      cry(fc(ctx), "%s: setuid(%s): %s", __func__, uid, strerror(errno));
-    } else {
-      success = 1;
-    }
-  }
-
-  return success;
-}
-#endif // !_WIN32
-
-#if !defined(NO_SSL)
-static pthread_mutex_t *ssl_mutexes;
-
-static int sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *)) {
-  return (conn->ssl = SSL_new(s)) != NULL &&
-    SSL_set_fd(conn->ssl, conn->client.sock) == 1 &&
-    func(conn->ssl) == 1;
-}
-
-// Return OpenSSL error message
-static const char *ssl_error(void) {
-  unsigned long err;
-  err = ERR_get_error();
-  return err == 0 ? "" : ERR_error_string(err, NULL);
-}
-
-static void ssl_locking_callback(int mode, int mutex_num, const char *file,
-                                 int line) {
-  (void) line;
-  (void) file;
-
-  if (mode & 1) {  // 1 is CRYPTO_LOCK
-    (void) pthread_mutex_lock(&ssl_mutexes[mutex_num]);
-  } else {
-    (void) pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
-  }
-}
-
-static unsigned long ssl_id_callback(void) {
-  return (unsigned long) pthread_self();
-}
-
-#if !defined(NO_SSL_DL)
-static int load_dll(struct mg_context *ctx, const char *dll_name,
-                    struct ssl_func *sw) {
-  union {void *p; void (*fp)(void);} u;
-  void  *dll_handle;
-  struct ssl_func *fp;
-
-  if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
-    cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
-    return 0;
-  }
-
-  for (fp = sw; fp->name != NULL; fp++) {
-#ifdef _WIN32
-    // GetProcAddress() returns pointer to function
-    u.fp = (void (*)(void)) dlsym(dll_handle, fp->name);
-#else
-    // dlsym() on UNIX returns void *. ISO C forbids casts of data pointers to
-    // function pointers. We need to use a union to make a cast.
-    u.p = dlsym(dll_handle, fp->name);
-#endif // _WIN32
-    if (u.fp == NULL) {
-      cry(fc(ctx), "%s: %s: cannot find %s", __func__, dll_name, fp->name);
-      return 0;
-    } else {
-      fp->ptr = u.fp;
-    }
-  }
-
-  return 1;
-}
-#endif // NO_SSL_DL
-
-// Dynamically load SSL library. Set up ctx->ssl_ctx pointer.
-static int set_ssl_option(struct mg_context *ctx) {
-  int i, size;
-  const char *pem;
-
-  // If PEM file is not specified, skip SSL initialization.
-  if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL) {
-    return 1;
-  }
-
-#if !defined(NO_SSL_DL)
-  if (!load_dll(ctx, SSL_LIB, ssl_sw) ||
-      !load_dll(ctx, CRYPTO_LIB, crypto_sw)) {
-    return 0;
-  }
-#endif // NO_SSL_DL
-
-  // Initialize SSL library
-  SSL_library_init();
-  SSL_load_error_strings();
-
-  if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
-    cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
-    return 0;
-  }
-
-  // If user callback returned non-NULL, that means that user callback has
-  // set up certificate itself. In this case, skip sertificate setting.
-  if ((ctx->callbacks.init_ssl == NULL ||
-       !ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data)) &&
-      (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0 ||
-       SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0)) {
-    cry(fc(ctx), "%s: cannot open %s: %s", __func__, pem, ssl_error());
-    return 0;
-  }
-
-  if (pem != NULL) {
-    (void) SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
-  }
-
-  // Initialize locking callbacks, needed for thread safety.
-  // http://www.openssl.org/support/faq.html#PROG1
-  size = sizeof(pthread_mutex_t) * CRYPTO_num_locks();
-  if ((ssl_mutexes = (pthread_mutex_t *) malloc((size_t)size)) == NULL) {
-    cry(fc(ctx), "%s: cannot allocate mutexes: %s", __func__, ssl_error());
-    return 0;
-  }
-
-  for (i = 0; i < CRYPTO_num_locks(); i++) {
-    pthread_mutex_init(&ssl_mutexes[i], NULL);
-  }
-
-  CRYPTO_set_locking_callback(&ssl_locking_callback);
-  CRYPTO_set_id_callback(&ssl_id_callback);
-
-  return 1;
-}
-
-static void uninitialize_ssl(struct mg_context *ctx) {
-  int i;
-  if (ctx->ssl_ctx != NULL) {
-    CRYPTO_set_locking_callback(NULL);
-    for (i = 0; i < CRYPTO_num_locks(); i++) {
-      pthread_mutex_destroy(&ssl_mutexes[i]);
-    }
-    CRYPTO_set_locking_callback(NULL);
-    CRYPTO_set_id_callback(NULL);
-  }
-}
-#endif // !NO_SSL
-
-static int set_gpass_option(struct mg_context *ctx) {
-  struct file file = STRUCT_FILE_INITIALIZER;
-  const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
-  if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
-    cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
-    return 0;
-  }
-  return 1;
-}
-
-static int set_acl_option(struct mg_context *ctx) {
-  return check_acl(ctx, (uint32_t) 0x7f000001UL) != -1;
-}
-
-static void reset_per_request_attributes(struct mg_connection *conn) {
-  conn->path_info = NULL;
-  conn->num_bytes_sent = conn->consumed_content = 0;
-  conn->status_code = -1;
-  conn->must_close = conn->request_len = conn->throttle = 0;
-}
-
-static void close_socket_gracefully(struct mg_connection *conn) {
-#if defined(_WIN32)
-  char buf[MG_BUF_LEN];
-  int n;
-#endif
-  struct linger linger;
-
-  // Set linger option to avoid socket hanging out after close. This prevent
-  // ephemeral port exhaust problem under high QPS.
-  linger.l_onoff = 1;
-  linger.l_linger = 1;
-  setsockopt(conn->client.sock, SOL_SOCKET, SO_LINGER,
-             (char *) &linger, sizeof(linger));
-
-  // Send FIN to the client
-  shutdown(conn->client.sock, SHUT_WR);
-  set_non_blocking_mode(conn->client.sock);
-
-#if defined(_WIN32)
-  // Read and discard pending incoming data. If we do not do that and close the
-  // socket, the data in the send buffer may be discarded. This
-  // behaviour is seen on Windows, when client keeps sending data
-  // when server decides to close the connection; then when client
-  // does recv() it gets no data back.
-  do {
-    n = pull(NULL, conn, buf, sizeof(buf));
-  } while (n > 0);
-#endif
-
-  // Now we know that our FIN is ACK-ed, safe to close
-  closesocket(conn->client.sock);
-}
-
-static void close_connection(struct mg_connection *conn) {
-  conn->must_close = 1;
-
-#ifndef NO_SSL
-  if (conn->ssl != NULL) {
-    // Run SSL_shutdown twice to ensure completly close SSL connection
-    SSL_shutdown(conn->ssl);
-    SSL_free(conn->ssl);
-    conn->ssl = NULL;
-  }
-#endif
-  if (conn->client.sock != INVALID_SOCKET) {
-    close_socket_gracefully(conn);
-    conn->client.sock = INVALID_SOCKET;
-  }
-}
-
-void mg_close_connection(struct mg_connection *conn) {
-#ifndef NO_SSL
-  if (conn->client_ssl_ctx != NULL) {
-    SSL_CTX_free((SSL_CTX *) conn->client_ssl_ctx);
-  }
-#endif
-  close_connection(conn);
-  free(conn);
-}
-
-struct mg_connection *mg_connect(const char *host, int port, int use_ssl,
-                                 char *ebuf, size_t ebuf_len) {
-  static struct mg_context fake_ctx;
-  struct mg_connection *conn = NULL;
-  SOCKET sock;
-
-  if ((sock = conn2(host, port, use_ssl, ebuf, ebuf_len)) == INVALID_SOCKET) {
-  } else if ((conn = (struct mg_connection *)
-              calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
-    snprintf(ebuf, ebuf_len, "calloc(): %s", strerror(ERRNO));
-    closesocket(sock);
-#ifndef NO_SSL
-  } else if (use_ssl && (conn->client_ssl_ctx =
-                         SSL_CTX_new(SSLv23_client_method())) == NULL) {
-    snprintf(ebuf, ebuf_len, "SSL_CTX_new error");
-    closesocket(sock);
-    free(conn);
-    conn = NULL;
-#endif // NO_SSL
-  } else {
-    socklen_t len;
-    conn->buf_size = MAX_REQUEST_SIZE;
-    conn->buf = (char *) (conn + 1);
-    conn->ctx = &fake_ctx;
-    conn->client.sock = sock;
-    getsockname(sock, &conn->client.rsa.sa, &len);
-    conn->client.is_ssl = use_ssl;
-#ifndef NO_SSL
-    if (use_ssl) {
-      // SSL_CTX_set_verify call is needed to switch off server certificate
-      // checking, which is off by default in OpenSSL and on in yaSSL.
-      SSL_CTX_set_verify(conn->client_ssl_ctx, 0, 0);
-      sslize(conn, conn->client_ssl_ctx, SSL_connect);
-    }
-#endif
-  }
-
-  return conn;
-}
-
-static int is_valid_uri(const char *uri) {
-  // Conform to http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
-  // URI can be an asterisk (*) or should start with slash.
-  return uri[0] == '/' || (uri[0] == '*' && uri[1] == '\0');
-}
-
-static int getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len) {
-  const char *cl;
-
-  ebuf[0] = '\0';
-  reset_per_request_attributes(conn);
-  conn->request_len = read_request(NULL, conn, conn->buf, conn->buf_size,
-                                   &conn->data_len);
-  assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
-
-  if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
-    snprintf(ebuf, ebuf_len, "%s", "Request Too Large");
-  } else if (conn->request_len <= 0) {
-    snprintf(ebuf, ebuf_len, "%s", "Client closed connection");
-  } else if (parse_http_message(conn->buf, conn->buf_size,
-                                &conn->request_info) <= 0) {
-    snprintf(ebuf, ebuf_len, "Bad request: [%.*s]", conn->data_len, conn->buf);
-  } else {
-    // Request is valid
-    if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
-      conn->content_len = strtoll(cl, NULL, 10);
-    } else if (!mg_strcasecmp(conn->request_info.request_method, "POST") ||
-               !mg_strcasecmp(conn->request_info.request_method, "PUT")) {
-      conn->content_len = -1;
-    } else {
-      conn->content_len = 0;
-    }
-    conn->birth_time = time(NULL);
-  }
-  return ebuf[0] == '\0';
-}
-
-struct mg_connection *mg_download(const char *host, int port, int use_ssl,
-                                  char *ebuf, size_t ebuf_len,
-                                  const char *fmt, ...) {
-  struct mg_connection *conn;
-  va_list ap;
-
-  va_start(ap, fmt);
-  ebuf[0] = '\0';
-  if ((conn = mg_connect(host, port, use_ssl, ebuf, ebuf_len)) == NULL) {
-  } else if (mg_vprintf(conn, fmt, ap) <= 0) {
-    snprintf(ebuf, ebuf_len, "%s", "Error sending request");
-  } else {
-    getreq(conn, ebuf, ebuf_len);
-  }
-  if (ebuf[0] != '\0' && conn != NULL) {
-    mg_close_connection(conn);
-    conn = NULL;
-  }
-
-  return conn;
-}
-
-static void process_new_connection(struct mg_connection *conn) {
-  struct mg_request_info *ri = &conn->request_info;
-  int keep_alive_enabled, keep_alive, discard_len;
-  char ebuf[100];
-
-  keep_alive_enabled = !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
-  keep_alive = 0;
-
-  // Important: on new connection, reset the receiving buffer. Credit goes
-  // to crule42.
-  conn->data_len = 0;
-  do {
-    if (!getreq(conn, ebuf, sizeof(ebuf))) {
-      send_http_error(conn, 500, "Server Error", "%s", ebuf);
-      conn->must_close = 1;
-    } else if (!is_valid_uri(conn->request_info.uri)) {
-      snprintf(ebuf, sizeof(ebuf), "Invalid URI: [%s]", ri->uri);
-      send_http_error(conn, 400, "Bad Request", "%s", ebuf);
-    } else if (strcmp(ri->http_version, "1.0") &&
-               strcmp(ri->http_version, "1.1")) {
-      snprintf(ebuf, sizeof(ebuf), "Bad HTTP version: [%s]", ri->http_version);
-      send_http_error(conn, 505, "Bad HTTP version", "%s", ebuf);
-    }
-
-    if (ebuf[0] == '\0') {
-      handle_request(conn);
-      if (conn->ctx->callbacks.end_request != NULL) {
-        conn->ctx->callbacks.end_request(conn, conn->status_code);
-      }
-      log_access(conn);
-    }
-    if (ri->remote_user != NULL) {
-      free((void *) ri->remote_user);
-      // Important! When having connections with and without auth
-      // would cause double free and then crash
-      ri->remote_user = NULL;
-    }
-
-    // NOTE(lsm): order is important here. should_keep_alive() call
-    // is using parsed request, which will be invalid after memmove's below.
-    // Therefore, memorize should_keep_alive() result now for later use
-    // in loop exit condition.
-    keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled &&
-      conn->content_len >= 0 && should_keep_alive(conn);
-
-    // Discard all buffered data for this request
-    discard_len = conn->content_len >= 0 && conn->request_len > 0 &&
-      conn->request_len + conn->content_len < (int64_t) conn->data_len ?
-      (int) (conn->request_len + conn->content_len) : conn->data_len;
-    assert(discard_len >= 0);
-    memmove(conn->buf, conn->buf + discard_len, conn->data_len - discard_len);
-    conn->data_len -= discard_len;
-    assert(conn->data_len >= 0);
-    assert(conn->data_len <= conn->buf_size);
-  } while (keep_alive);
-}
-
-// Worker threads take accepted socket from the queue
-static int consume_socket(struct mg_context *ctx, struct socket *sp) {
-  (void) pthread_mutex_lock(&ctx->mutex);
-  DEBUG_TRACE(("going idle"));
-
-  // If the queue is empty, wait. We're idle at this point.
-  while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
-    pthread_cond_wait(&ctx->sq_full, &ctx->mutex);
-  }
-
-  // If we're stopping, sq_head may be equal to sq_tail.
-  if (ctx->sq_head > ctx->sq_tail) {
-    // Copy socket from the queue and increment tail
-    *sp = ctx->queue[ctx->sq_tail % ARRAY_SIZE(ctx->queue)];
-    ctx->sq_tail++;
-    DEBUG_TRACE(("grabbed socket %d, going busy", sp->sock));
-
-    // Wrap pointers if needed
-    while (ctx->sq_tail > (int) ARRAY_SIZE(ctx->queue)) {
-      ctx->sq_tail -= ARRAY_SIZE(ctx->queue);
-      ctx->sq_head -= ARRAY_SIZE(ctx->queue);
-    }
-  }
-
-  (void) pthread_cond_signal(&ctx->sq_empty);
-  (void) pthread_mutex_unlock(&ctx->mutex);
-
-  return !ctx->stop_flag;
-}
-
-static void *worker_thread(void *thread_func_param) {
-  struct mg_context *ctx = thread_func_param;
-  struct mg_connection *conn;
-
-  conn = (struct mg_connection *) calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
-  if (conn == NULL) {
-    cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
-  } else {
-    conn->buf_size = MAX_REQUEST_SIZE;
-    conn->buf = (char *) (conn + 1);
-    conn->ctx = ctx;
-    conn->request_info.user_data = ctx->user_data;
-
-    // Call consume_socket() even when ctx->stop_flag > 0, to let it signal
-    // sq_empty condvar to wake up the master waiting in produce_socket()
-    while (consume_socket(ctx, &conn->client)) {
-      conn->birth_time = time(NULL);
-
-      // Fill in IP, port info early so even if SSL setup below fails,
-      // error handler would have the corresponding info.
-      // Thanks to Johannes Winkelmann for the patch.
-      // TODO(lsm): Fix IPv6 case
-      conn->request_info.remote_port = ntohs(conn->client.rsa.sin.sin_port);
-      memcpy(&conn->request_info.remote_ip,
-             &conn->client.rsa.sin.sin_addr.s_addr, 4);
-      conn->request_info.remote_ip = ntohl(conn->request_info.remote_ip);
-      conn->request_info.is_ssl = conn->client.is_ssl;
-
-      if (!conn->client.is_ssl
-#ifndef NO_SSL
-          || sslize(conn, conn->ctx->ssl_ctx, SSL_accept)
-#endif
-         ) {
-        process_new_connection(conn);
-      }
-
-      close_connection(conn);
-    }
-    free(conn);
-  }
-
-  // Signal master that we're done with connection and exiting
-  (void) pthread_mutex_lock(&ctx->mutex);
-  ctx->num_threads--;
-  (void) pthread_cond_signal(&ctx->cond);
-  assert(ctx->num_threads >= 0);
-  (void) pthread_mutex_unlock(&ctx->mutex);
-
-  DEBUG_TRACE(("exiting"));
-  return NULL;
-}
-
-// Master thread adds accepted socket to a queue
-static void produce_socket(struct mg_context *ctx, const struct socket *sp) {
-  (void) pthread_mutex_lock(&ctx->mutex);
-
-  // If the queue is full, wait
-  while (ctx->stop_flag == 0 &&
-         ctx->sq_head - ctx->sq_tail >= (int) ARRAY_SIZE(ctx->queue)) {
-    (void) pthread_cond_wait(&ctx->sq_empty, &ctx->mutex);
-  }
-
-  if (ctx->sq_head - ctx->sq_tail < (int) ARRAY_SIZE(ctx->queue)) {
-    // Copy socket to the queue and increment head
-    ctx->queue[ctx->sq_head % ARRAY_SIZE(ctx->queue)] = *sp;
-    ctx->sq_head++;
-    DEBUG_TRACE(("queued socket %d", sp->sock));
-  }
-
-  (void) pthread_cond_signal(&ctx->sq_full);
-  (void) pthread_mutex_unlock(&ctx->mutex);
-}
-
-static int set_sock_timeout(SOCKET sock, int milliseconds) {
-#ifdef _WIN32
-  DWORD t = milliseconds;
-#else
-  struct timeval t;
-  t.tv_sec = milliseconds / 1000;
-  t.tv_usec = (milliseconds * 1000) % 1000000;
-#endif
-  return setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (void *) &t, sizeof(t)) ||
-    setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (void *) &t, sizeof(t));
-}
-
-static void accept_new_connection(const struct socket *listener,
-                                  struct mg_context *ctx) {
-  struct socket so;
-  char src_addr[IP_ADDR_STR_LEN];
-  socklen_t len = sizeof(so.rsa);
-  int on = 1;
-
-  if ((so.sock = accept(listener->sock, &so.rsa.sa, &len)) == INVALID_SOCKET) {
-  } else if (!check_acl(ctx, ntohl(* (uint32_t *) &so.rsa.sin.sin_addr))) {
-    sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
-    cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
-    closesocket(so.sock);
-  } else {
-    // Put so socket structure into the queue
-    DEBUG_TRACE(("Accepted socket %d", (int) so.sock));
-    so.is_ssl = listener->is_ssl;
-    so.ssl_redir = listener->ssl_redir;
-    getsockname(so.sock, &so.lsa.sa, &len);
-    // Set TCP keep-alive. This is needed because if HTTP-level keep-alive
-    // is enabled, and client resets the connection, server won't get
-    // TCP FIN or RST and will keep the connection open forever. With TCP
-    // keep-alive, next keep-alive handshake will figure out that the client
-    // is down and will close the server end.
-    // Thanks to Igor Klopov who suggested the patch.
-    setsockopt(so.sock, SOL_SOCKET, SO_KEEPALIVE, (void *) &on, sizeof(on));
-    set_sock_timeout(so.sock, atoi(ctx->config[REQUEST_TIMEOUT]));
-    produce_socket(ctx, &so);
-  }
-}
-
-static void *master_thread(void *thread_func_param) {
-  struct mg_context *ctx = thread_func_param;
-  struct pollfd *pfd;
-  int i;
-
-  // Increase priority of the master thread
-#if defined(_WIN32)
-  SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
-#endif
-
-#if defined(ISSUE_317)
-  struct sched_param sched_param;
-  sched_param.sched_priority = sched_get_priority_max(SCHED_RR);
-  pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
-#endif
-
-  pfd = calloc(ctx->num_listening_sockets, sizeof(pfd[0]));
-  while (pfd != NULL && ctx->stop_flag == 0) {
-    for (i = 0; i < ctx->num_listening_sockets; i++) {
-      pfd[i].fd = ctx->listening_sockets[i].sock;
-      pfd[i].events = POLLIN;
-    }
-
-    if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
-      for (i = 0; i < ctx->num_listening_sockets; i++) {
-        // NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
-        // successfull poll, and POLLIN is defined as (POLLRDNORM | POLLRDBAND)
-        // Therefore, we're checking pfd[i].revents & POLLIN, not
-        // pfd[i].revents == POLLIN.
-        if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
-          accept_new_connection(&ctx->listening_sockets[i], ctx);
-        }
-      }
-    }
-  }
-  free(pfd);
-  DEBUG_TRACE(("stopping workers"));
-
-  // Stop signal received: somebody called mg_stop. Quit.
-  close_all_listening_sockets(ctx);
-
-  // Wakeup workers that are waiting for connections to handle.
-  pthread_cond_broadcast(&ctx->sq_full);
-
-  // Wait until all threads finish
-  (void) pthread_mutex_lock(&ctx->mutex);
-  while (ctx->num_threads > 0) {
-    (void) pthread_cond_wait(&ctx->cond, &ctx->mutex);
-  }
-  (void) pthread_mutex_unlock(&ctx->mutex);
-
-  // All threads exited, no sync is needed. Destroy mutex and condvars
-  (void) pthread_mutex_destroy(&ctx->mutex);
-  (void) pthread_cond_destroy(&ctx->cond);
-  (void) pthread_cond_destroy(&ctx->sq_empty);
-  (void) pthread_cond_destroy(&ctx->sq_full);
-
-#if !defined(NO_SSL)
-  uninitialize_ssl(ctx);
-#endif
-  DEBUG_TRACE(("exiting"));
-
-  // Signal mg_stop() that we're done.
-  // WARNING: This must be the very last thing this
-  // thread does, as ctx becomes invalid after this line.
-  ctx->stop_flag = 2;
-  return NULL;
-}
-
-static void free_context(struct mg_context *ctx) {
-  int i;
-
-  // Deallocate config parameters
-  for (i = 0; i < NUM_OPTIONS; i++) {
-    if (ctx->config[i] != NULL)
-      free(ctx->config[i]);
-  }
-
-#ifndef NO_SSL
-  // Deallocate SSL context
-  if (ctx->ssl_ctx != NULL) {
-    SSL_CTX_free(ctx->ssl_ctx);
-  }
-  if (ssl_mutexes != NULL) {
-    free(ssl_mutexes);
-    ssl_mutexes = NULL;
-  }
-#endif // !NO_SSL
-
-  // Deallocate context itself
-  free(ctx);
-}
-
-void mg_stop(struct mg_context *ctx) {
-  ctx->stop_flag = 1;
-
-  // Wait until mg_fini() stops
-  while (ctx->stop_flag != 2) {
-    (void) mg_sleep(10);
-  }
-  free_context(ctx);
-
-#if defined(_WIN32) && !defined(__SYMBIAN32__)
-  (void) WSACleanup();
-#endif // _WIN32
-}
-
-struct mg_context *mg_start(const struct mg_callbacks *callbacks,
-                            void *user_data,
-                            const char **options) {
-  struct mg_context *ctx;
-  const char *name, *value, *default_value;
-  int i;
-
-#if defined(_WIN32) && !defined(__SYMBIAN32__)
-  WSADATA data;
-  WSAStartup(MAKEWORD(2,2), &data);
-  InitializeCriticalSection(&global_log_file_lock);
-#endif // _WIN32
-
-  // Allocate context and initialize reasonable general case defaults.
-  // TODO(lsm): do proper error handling here.
-  if ((ctx = (struct mg_context *) calloc(1, sizeof(*ctx))) == NULL) {
-    return NULL;
-  }
-  ctx->callbacks = *callbacks;
-  ctx->user_data = user_data;
-
-  while (options && (name = *options++) != NULL) {
-    if ((i = get_option_index(name)) == -1) {
-      cry(fc(ctx), "Invalid option: %s", name);
-      free_context(ctx);
-      return NULL;
-    } else if ((value = *options++) == NULL) {
-      cry(fc(ctx), "%s: option value cannot be NULL", name);
-      free_context(ctx);
-      return NULL;
-    }
-    if (ctx->config[i] != NULL) {
-      cry(fc(ctx), "warning: %s: duplicate option", name);
-      free(ctx->config[i]);
-    }
-    ctx->config[i] = mg_strdup(value);
-    DEBUG_TRACE(("[%s] -> [%s]", name, value));
-  }
-
-  // Set default value if needed
-  for (i = 0; config_options[i * 2] != NULL; i++) {
-    default_value = config_options[i * 2 + 1];
-    if (ctx->config[i] == NULL && default_value != NULL) {
-      ctx->config[i] = mg_strdup(default_value);
-    }
-  }
-
-  // NOTE(lsm): order is important here. SSL certificates must
-  // be initialized before listening ports. UID must be set last.
-  if (!set_gpass_option(ctx) ||
-#if !defined(NO_SSL)
-      !set_ssl_option(ctx) ||
-#endif
-      !set_ports_option(ctx) ||
-#if !defined(_WIN32)
-      !set_uid_option(ctx) ||
-#endif
-      !set_acl_option(ctx)) {
-    free_context(ctx);
-    return NULL;
-  }
-
-#if !defined(_WIN32) && !defined(__SYMBIAN32__)
-  // Ignore SIGPIPE signal, so if browser cancels the request, it
-  // won't kill the whole process.
-  (void) signal(SIGPIPE, SIG_IGN);
-  // Also ignoring SIGCHLD to let the OS to reap zombies properly.
-  (void) signal(SIGCHLD, SIG_IGN);
-#endif // !_WIN32
-
-  (void) pthread_mutex_init(&ctx->mutex, NULL);
-  (void) pthread_cond_init(&ctx->cond, NULL);
-  (void) pthread_cond_init(&ctx->sq_empty, NULL);
-  (void) pthread_cond_init(&ctx->sq_full, NULL);
-
-  // Start master (listening) thread
-  mg_start_thread(master_thread, ctx);
-
-  // Start worker threads
-  for (i = 0; i < atoi(ctx->config[NUM_THREADS]); i++) {
-    if (mg_start_thread(worker_thread, ctx) != 0) {
-      cry(fc(ctx), "Cannot start worker thread: %ld", (long) ERRNO);
-    } else {
-      ctx->num_threads++;
-    }
-  }
-
-  return ctx;
-}
diff --git a/src/mongoose/mongoose.h b/src/mongoose/mongoose.h
deleted file mode 100644
index 83c244c..0000000
--- a/src/mongoose/mongoose.h
+++ /dev/null
@@ -1,384 +0,0 @@
-// Copyright (c) 2004-2012 Sergey Lyubka
-//
-// Permission is hereby granted, free of charge, to any person obtaining a copy
-// of this software and associated documentation files (the "Software"), to deal
-// in the Software without restriction, including without limitation the rights
-// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-// copies of the Software, and to permit persons to whom the Software is
-// furnished to do so, subject to the following conditions:
-//
-// The above copyright notice and this permission notice shall be included in
-// all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-// THE SOFTWARE.
-
-#ifndef MONGOOSE_HEADER_INCLUDED
-#define  MONGOOSE_HEADER_INCLUDED
-
-#include <stdio.h>
-#include <stddef.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif // __cplusplus
-
-struct mg_context;     // Handle for the HTTP service itself
-struct mg_connection;  // Handle for the individual connection
-
-
-// This structure contains information about the HTTP request.
-struct mg_request_info {
-  const char *request_method; // "GET", "POST", etc
-  const char *uri;            // URL-decoded URI
-  const char *http_version;   // E.g. "1.0", "1.1"
-  const char *query_string;   // URL part after '?', not including '?', or NULL
-  const char *remote_user;    // Authenticated user, or NULL if no auth used
-  long remote_ip;             // Client's IP address
-  int remote_port;            // Client's port
-  int is_ssl;                 // 1 if SSL-ed, 0 if not
-  void *user_data;            // User data pointer passed to mg_start()
-
-  int num_headers;            // Number of HTTP headers
-  struct mg_header {
-    const char *name;         // HTTP header name
-    const char *value;        // HTTP header value
-  } http_headers[64];         // Maximum 64 headers
-};
-
-
-// This structure needs to be passed to mg_start(), to let mongoose know
-// which callbacks to invoke. For detailed description, see
-// https://github.com/valenok/mongoose/blob/master/UserManual.md
-struct mg_callbacks {
-  // Called when mongoose has received new HTTP request.
-  // If callback returns non-zero,
-  // callback must process the request by sending valid HTTP headers and body,
-  // and mongoose will not do any further processing.
-  // If callback returns 0, mongoose processes the request itself. In this case,
-  // callback must not send any data to the client.
-  int  (*begin_request)(struct mg_connection *);
-
-  // Called when mongoose has finished processing request.
-  void (*end_request)(const struct mg_connection *, int reply_status_code);
-
-  // Called when mongoose is about to log a message. If callback returns
-  // non-zero, mongoose does not log anything.
-  int  (*log_message)(const struct mg_connection *, const char *message);
-
-  // Called when mongoose initializes SSL library.
-  int  (*init_ssl)(void *ssl_context, void *user_data);
-
-  // Called when websocket request is received, before websocket handshake.
-  // If callback returns 0, mongoose proceeds with handshake, otherwise
-  // cinnection is closed immediately.
-  int (*websocket_connect)(const struct mg_connection *);
-
-  // Called when websocket handshake is successfully completed, and
-  // connection is ready for data exchange.
-  void (*websocket_ready)(struct mg_connection *);
-
-  // Called when data frame has been received from the client.
-  // Parameters:
-  //    bits: first byte of the websocket frame, see websocket RFC at
-  //          http://tools.ietf.org/html/rfc6455, section 5.2
-  //    data, data_len: payload, with mask (if any) already applied.
-  // Return value:
-  //    non-0: keep this websocket connection opened.
-  //    0:     close this websocket connection.
-  int  (*websocket_data)(struct mg_connection *, int bits,
-                         char *data, size_t data_len);
-
-  // Called when mongoose tries to open a file. Used to intercept file open
-  // calls, and serve file data from memory instead.
-  // Parameters:
-  //    path:     Full path to the file to open.
-  //    data_len: Placeholder for the file size, if file is served from memory.
-  // Return value:
-  //    NULL: do not serve file from memory, proceed with normal file open.
-  //    non-NULL: pointer to the file contents in memory. data_len must be
-  //              initilized with the size of the memory block.
-  const char * (*open_file)(const struct mg_connection *,
-                             const char *path, size_t *data_len);
-
-  // Called when mongoose is about to serve Lua server page (.lp file), if
-  // Lua support is enabled.
-  // Parameters:
-  //   lua_context: "lua_State *" pointer.
-  void (*init_lua)(struct mg_connection *, void *lua_context);
-
-  // Called when mongoose has uploaded a file to a temporary directory as a
-  // result of mg_upload() call.
-  // Parameters:
-  //    file_file: full path name to the uploaded file.
-  void (*upload)(struct mg_connection *, const char *file_name);
-
-  // Called when mongoose is about to send HTTP error to the client.
-  // Implementing this callback allows to create custom error pages.
-  // Parameters:
-  //   status: HTTP error status code.
-  int  (*http_error)(struct mg_connection *, int status);
-};
-
-// Start web server.
-//
-// Parameters:
-//   callbacks: mg_callbacks structure with user-defined callbacks.
-//   options: NULL terminated list of option_name, option_value pairs that
-//            specify Mongoose configuration parameters.
-//
-// Side-effects: on UNIX, ignores SIGCHLD and SIGPIPE signals. If custom
-//    processing is required for these, signal handlers must be set up
-//    after calling mg_start().
-//
-//
-// Example:
-//   const char *options[] = {
-//     "document_root", "/var/www",
-//     "listening_ports", "80,443s",
-//     NULL
-//   };
-//   struct mg_context *ctx = mg_start(&my_func, NULL, options);
-//
-// Refer to https://github.com/valenok/mongoose/blob/master/UserManual.md
-// for the list of valid option and their possible values.
-//
-// Return:
-//   web server context, or NULL on error.
-struct mg_context *mg_start(const struct mg_callbacks *callbacks,
-                            void *user_data,
-                            const char **configuration_options);
-
-
-// Stop the web server.
-//
-// Must be called last, when an application wants to stop the web server and
-// release all associated resources. This function blocks until all Mongoose
-// threads are stopped. Context pointer becomes invalid.
-void mg_stop(struct mg_context *);
-
-
-// Get the value of particular configuration parameter.
-// The value returned is read-only. Mongoose does not allow changing
-// configuration at run time.
-// If given parameter name is not valid, NULL is returned. For valid
-// names, return value is guaranteed to be non-NULL. If parameter is not
-// set, zero-length string is returned.
-const char *mg_get_option(const struct mg_context *ctx, const char *name);
-
-
-// Return array of strings that represent valid configuration options.
-// For each option, a short name, long name, and default value is returned.
-// Array is NULL terminated.
-const char **mg_get_valid_option_names(void);
-
-
-// Add, edit or delete the entry in the passwords file.
-//
-// This function allows an application to manipulate .htpasswd files on the
-// fly by adding, deleting and changing user records. This is one of the
-// several ways of implementing authentication on the server side. For another,
-// cookie-based way please refer to the examples/chat.c in the source tree.
-//
-// If password is not NULL, entry is added (or modified if already exists).
-// If password is NULL, entry is deleted.
-//
-// Return:
-//   1 on success, 0 on error.
-int mg_modify_passwords_file(const char *passwords_file_name,
-                             const char *domain,
-                             const char *user,
-                             const char *password);
-
-
-// Return information associated with the request.
-struct mg_request_info *mg_get_request_info(struct mg_connection *);
-
-
-// Send data to the client.
-// Return:
-//  0   when the connection has been closed
-//  -1  on error
-//  >0  number of bytes written on success
-int mg_write(struct mg_connection *, const void *buf, size_t len);
-
-
-// Send data to a websocket client wrapped in a websocket frame.
-// It is unsafe to read/write to this connection from another thread.
-// This function is available when mongoose is compiled with -DUSE_WEBSOCKET
-//
-// Return:
-//  0   when the connection has been closed
-//  -1  on error
-//  >0  number of bytes written on success
-int mg_websocket_write(struct mg_connection* conn, int opcode,
-                       const char *data, size_t data_len);
-
-// Opcodes, from http://tools.ietf.org/html/rfc6455
-enum {
-  WEBSOCKET_OPCODE_CONTINUATION = 0x0,
-  WEBSOCKET_OPCODE_TEXT = 0x1,
-  WEBSOCKET_OPCODE_BINARY = 0x2,
-  WEBSOCKET_OPCODE_CONNECTION_CLOSE = 0x8,
-  WEBSOCKET_OPCODE_PING = 0x9,
-  WEBSOCKET_OPCODE_PONG = 0xa
-};
-
-
-// Macros for enabling compiler-specific checks for printf-like arguments.
-#undef PRINTF_FORMAT_STRING
-#if defined(_MSC_VER) && _MSC_VER >= 1400
-#include <sal.h>
-#if defined(_MSC_VER) && _MSC_VER > 1400
-#define PRINTF_FORMAT_STRING(s) _Printf_format_string_ s
-#else
-#define PRINTF_FORMAT_STRING(s) __format_string s
-#endif
-#else
-#define PRINTF_FORMAT_STRING(s) s
-#endif
-
-#ifdef __GNUC__
-#define PRINTF_ARGS(x, y) __attribute__((format(printf, x, y)))
-#else
-#define PRINTF_ARGS(x, y)
-#endif
-
-// Send data to the client using printf() semantics.
-//
-// Works exactly like mg_write(), but allows to do message formatting.
-int mg_printf(struct mg_connection *,
-              PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(2, 3);
-
-
-// Send contents of the entire file together with HTTP headers.
-void mg_send_file(struct mg_connection *conn, const char *path);
-
-
-// Read data from the remote end, return number of bytes read.
-// Return:
-//   0     connection has been closed by peer. No more data could be read.
-//   < 0   read error. No more data could be read from the connection.
-//   > 0   number of bytes read into the buffer.
-int mg_read(struct mg_connection *, void *buf, size_t len);
-
-
-// Get the value of particular HTTP header.
-//
-// This is a helper function. It traverses request_info->http_headers array,
-// and if the header is present in the array, returns its value. If it is
-// not present, NULL is returned.
-const char *mg_get_header(const struct mg_connection *, const char *name);
-
-
-// Get a value of particular form variable.
-//
-// Parameters:
-//   data: pointer to form-uri-encoded buffer. This could be either POST data,
-//         or request_info.query_string.
-//   data_len: length of the encoded data.
-//   var_name: variable name to decode from the buffer
-//   dst: destination buffer for the decoded variable
-//   dst_len: length of the destination buffer
-//
-// Return:
-//   On success, length of the decoded variable.
-//   On error:
-//      -1 (variable not found).
-//      -2 (destination buffer is NULL, zero length or too small to hold the
-//          decoded variable).
-//
-// Destination buffer is guaranteed to be '\0' - terminated if it is not
-// NULL or zero length.
-int mg_get_var(const char *data, size_t data_len,
-               const char *var_name, char *dst, size_t dst_len);
-
-// Fetch value of certain cookie variable into the destination buffer.
-//
-// Destination buffer is guaranteed to be '\0' - terminated. In case of
-// failure, dst[0] == '\0'. Note that RFC allows many occurrences of the same
-// parameter. This function returns only first occurrence.
-//
-// Return:
-//   On success, value length.
-//   On error:
-//      -1 (either "Cookie:" header is not present at all or the requested
-//          parameter is not found).
-//      -2 (destination buffer is NULL, zero length or too small to hold the
-//          value).
-int mg_get_cookie(const char *cookie, const char *var_name,
-                  char *buf, size_t buf_len);
-
-
-// Download data from the remote web server.
-//   host: host name to connect to, e.g. "foo.com", or "10.12.40.1".
-//   port: port number, e.g. 80.
-//   use_ssl: wether to use SSL connection.
-//   error_buffer, error_buffer_size: error message placeholder.
-//   request_fmt,...: HTTP request.
-// Return:
-//   On success, valid pointer to the new connection, suitable for mg_read().
-//   On error, NULL. error_buffer contains error message.
-// Example:
-//   char ebuf[100];
-//   struct mg_connection *conn;
-//   conn = mg_download("google.com", 80, 0, ebuf, sizeof(ebuf),
-//                      "%s", "GET / HTTP/1.0\r\nHost: google.com\r\n\r\n");
-struct mg_connection *mg_download(const char *host, int port, int use_ssl,
-                                  char *error_buffer, size_t error_buffer_size,
-                                  PRINTF_FORMAT_STRING(const char *request_fmt),
-                                  ...) PRINTF_ARGS(6, 7);
-
-
-// Close the connection opened by mg_download().
-void mg_close_connection(struct mg_connection *conn);
-
-
-// File upload functionality. Each uploaded file gets saved into a temporary
-// file and MG_UPLOAD event is sent.
-// Return number of uploaded files.
-int mg_upload(struct mg_connection *conn, const char *destination_dir);
-
-
-// Convenience function -- create detached thread.
-// Return: 0 on success, non-0 on error.
-typedef void * (*mg_thread_func_t)(void *);
-int mg_start_thread(mg_thread_func_t f, void *p);
-
-
-// Return builtin mime type for the given file name.
-// For unrecognized extensions, "text/plain" is returned.
-const char *mg_get_builtin_mime_type(const char *file_name);
-
-
-// Return Mongoose version.
-const char *mg_version(void);
-
-// URL-decode input buffer into destination buffer.
-// 0-terminate the destination buffer.
-// form-url-encoded data differs from URI encoding in a way that it
-// uses '+' as character for space, see RFC 1866 section 8.2.1
-// http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
-// Return: length of the decoded data, or -1 if dst buffer is too small.
-int mg_url_decode(const char *src, int src_len, char *dst,
-                  int dst_len, int is_form_url_encoded);
-
-// MD5 hash given strings.
-// Buffer 'buf' must be 33 bytes long. Varargs is a NULL terminated list of
-// ASCIIz strings. When function returns, buf will contain human-readable
-// MD5 hash. Example:
-//   char buf[33];
-//   mg_md5(buf, "aa", "bb", NULL);
-char *mg_md5(char buf[33], ...);
-
-
-#ifdef __cplusplus
-}
-#endif // __cplusplus
-
-#endif // MONGOOSE_HEADER_INCLUDED
diff --git a/src/regal/Regal.cpp b/src/regal/Regal.cpp
index fee11d2..7292a5f 100644
--- a/src/regal/Regal.cpp
+++ b/src/regal/Regal.cpp
@@ -8669,15 +8669,15 @@
     _next->call(&_next->glClearNamedBufferDataEXT)(buffer, internalformat, format, type, data);
   }
 
-  REGAL_DECL void REGAL_CALL glClearNamedBufferSubDataEXT(GLuint buffer, GLenum internalformat, GLenum format, GLenum type, GLintptr offset, GLsizeiptr size, const GLvoid *data)
+  REGAL_DECL void REGAL_CALL glClearNamedBufferSubDataEXT(GLuint buffer, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const GLvoid *data)
   {
     RegalContext *_context = REGAL_GET_CONTEXT();
     RegalAssert(Init::isInitialized());
-    App("glClearNamedBufferSubDataEXT","(", buffer, ", ", toString(internalformat), ", ", toString(format), ", ", toString(type), ", ", offset, ", ", size, ", ", boost::print::optional(data,Logging::pointers), ")");
+    App("glClearNamedBufferSubDataEXT","(", buffer, ", ", toString(internalformat), ", ", offset, ", ", size, ", ", toString(format), ", ", toString(type), ", ", boost::print::optional(data,Logging::pointers), ")");
     if (!_context) return;
     DispatchTableGL *_next = &_context->dispatcher.front();
     RegalAssert(_next);
-    _next->call(&_next->glClearNamedBufferSubDataEXT)(buffer, internalformat, format, type, offset, size, data);
+    _next->call(&_next->glClearNamedBufferSubDataEXT)(buffer, internalformat, offset, size, format, type, data);
   }
 
   /* GL_ARB_clear_texture */
diff --git a/src/regal/RegalDispatch.h b/src/regal/RegalDispatch.h
index 61d88ce..1ec18e6 100644
--- a/src/regal/RegalDispatch.h
+++ b/src/regal/RegalDispatch.h
@@ -1613,7 +1613,7 @@
     void (REGAL_CALL *glClearBufferData)(GLenum target, GLenum internalformat, GLenum format, GLenum type, const GLvoid *data);
     void (REGAL_CALL *glClearBufferSubData)(GLenum target, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const GLvoid *data);
     void (REGAL_CALL *glClearNamedBufferDataEXT)(GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const GLvoid *data);
-    void (REGAL_CALL *glClearNamedBufferSubDataEXT)(GLuint buffer, GLenum internalformat, GLenum format, GLenum type, GLintptr offset, GLsizeiptr size, const GLvoid *data);
+    void (REGAL_CALL *glClearNamedBufferSubDataEXT)(GLuint buffer, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const GLvoid *data);
 
     // GL_ARB_clear_texture
 
diff --git a/src/regal/RegalDispatchCode.cpp b/src/regal/RegalDispatchCode.cpp
index 59f3ebc..f69c529 100644
--- a/src/regal/RegalDispatchCode.cpp
+++ b/src/regal/RegalDispatchCode.cpp
@@ -13690,22 +13690,22 @@
       fprintf(_context->codeSource,"%s",_code.str().c_str());
 }
 
-static void REGAL_CALL code_glClearNamedBufferSubDataEXT(GLuint buffer, GLenum internalformat, GLenum format, GLenum type, GLintptr offset, GLsizeiptr size, const GLvoid *data)
+static void REGAL_CALL code_glClearNamedBufferSubDataEXT(GLuint buffer, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const GLvoid *data)
 {
     RegalContext *_context = REGAL_GET_CONTEXT();
     RegalAssert(_context);
     DispatchTableGL *_next = _context->dispatcher.code.next();
     RegalAssert(_next);
-    _next->call(&_next->glClearNamedBufferSubDataEXT)(buffer, internalformat, format, type, offset, size, data);
+    _next->call(&_next->glClearNamedBufferSubDataEXT)(buffer, internalformat, offset, size, format, type, data);
     std::string indent((_context->depthBeginEnd + _context->depthPushAttrib + 1)*2,' ');
     string_list< ::std::string > _code;
     _code << indent << "glClearNamedBufferSubDataEXT(";
                    _code << buffer;
     _code << ", "; _code << toString(internalformat);
-    _code << ", "; _code << toString(format);
-    _code << ", "; _code << toString(type);
     _code << ", "; _code << offset;
     _code << ", "; _code << size;
+    _code << ", "; _code << toString(format);
+    _code << ", "; _code << toString(type);
     _code << ", "; _code << data;
     _code << ");\n";
     if (_context->codeSource)
diff --git a/src/regal/RegalDispatchDebug.cpp b/src/regal/RegalDispatchDebug.cpp
index e259dd5..aba156a 100644
--- a/src/regal/RegalDispatchDebug.cpp
+++ b/src/regal/RegalDispatchDebug.cpp
@@ -6920,13 +6920,13 @@
   _next->call(&_next->glClearNamedBufferDataEXT)(buffer, internalformat, format, type, data);
 }
 
-static void REGAL_CALL debug_glClearNamedBufferSubDataEXT(GLuint buffer, GLenum internalformat, GLenum format, GLenum type, GLintptr offset, GLsizeiptr size, const GLvoid *data)
+static void REGAL_CALL debug_glClearNamedBufferSubDataEXT(GLuint buffer, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const GLvoid *data)
 {
   RegalContext *_context = REGAL_GET_CONTEXT();
   RegalAssert(_context);
   DispatchTableGL *_next = _context->dispatcher.debug.next();
   RegalAssert(_next);
-  _next->call(&_next->glClearNamedBufferSubDataEXT)(buffer, internalformat, format, type, offset, size, data);
+  _next->call(&_next->glClearNamedBufferSubDataEXT)(buffer, internalformat, offset, size, format, type, data);
 }
 
 // GL_ARB_clear_texture
diff --git a/src/regal/RegalDispatchError.cpp b/src/regal/RegalDispatchError.cpp
index 91e6499..25f5610 100644
--- a/src/regal/RegalDispatchError.cpp
+++ b/src/regal/RegalDispatchError.cpp
@@ -18838,7 +18838,7 @@
   }
 }
 
-static void REGAL_CALL error_glClearNamedBufferSubDataEXT(GLuint buffer, GLenum internalformat, GLenum format, GLenum type, GLintptr offset, GLsizeiptr size, const GLvoid *data)
+static void REGAL_CALL error_glClearNamedBufferSubDataEXT(GLuint buffer, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const GLvoid *data)
 {
   Internal("error_glClearNamedBufferSubDataEXT","()");
   RegalContext *_context = REGAL_GET_CONTEXT();
@@ -18849,7 +18849,7 @@
   if (!_context->err.inBeginEnd)
     _error = _next->call(&_next->glGetError)();
   RegalAssert(_error==GL_NO_ERROR);
-  _next->call(&_next->glClearNamedBufferSubDataEXT)(buffer, internalformat, format, type, offset, size, data);
+  _next->call(&_next->glClearNamedBufferSubDataEXT)(buffer, internalformat, offset, size, format, type, data);
   if (!_context->err.inBeginEnd) {
     _error = _next->call(&_next->glGetError)();
     if (_error!=GL_NO_ERROR) {
diff --git a/src/regal/RegalDispatchLoader.cpp b/src/regal/RegalDispatchLoader.cpp
index fd275b0..f9c621d 100644
--- a/src/regal/RegalDispatchLoader.cpp
+++ b/src/regal/RegalDispatchLoader.cpp
@@ -5402,11 +5402,11 @@
     _driver.call(&_driver.glClearNamedBufferDataEXT)(buffer, internalformat, format, type, data);
   }
 
-  static void REGAL_CALL glClearNamedBufferSubDataEXT(GLuint buffer, GLenum internalformat, GLenum format, GLenum type, GLintptr offset, GLsizeiptr size, const GLvoid *data)
+  static void REGAL_CALL glClearNamedBufferSubDataEXT(GLuint buffer, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const GLvoid *data)
   {
     DispatchTableGL &_driver = _getDispatchGL();
     _getProcAddress(reinterpret_cast<void (**)()>(&_driver.glClearNamedBufferSubDataEXT),reinterpret_cast<void (*)()>(glClearNamedBufferSubDataEXT),"glClearNamedBufferSubDataEXT");
-    _driver.call(&_driver.glClearNamedBufferSubDataEXT)(buffer, internalformat, format, type, offset, size, data);
+    _driver.call(&_driver.glClearNamedBufferSubDataEXT)(buffer, internalformat, offset, size, format, type, data);
   }
 
 // GL_ARB_clear_texture
diff --git a/src/regal/RegalDispatchLog.cpp b/src/regal/RegalDispatchLog.cpp
index d5971f2..c69bce7 100644
--- a/src/regal/RegalDispatchLog.cpp
+++ b/src/regal/RegalDispatchLog.cpp
@@ -7676,14 +7676,14 @@
     Driver("glClearNamedBufferDataEXT","(", buffer, ", ", toString(internalformat), ", ", toString(format), ", ", toString(type), ", ", boost::print::optional(data,Logging::pointers), ")");
 }
 
-static void REGAL_CALL log_glClearNamedBufferSubDataEXT(GLuint buffer, GLenum internalformat, GLenum format, GLenum type, GLintptr offset, GLsizeiptr size, const GLvoid *data)
+static void REGAL_CALL log_glClearNamedBufferSubDataEXT(GLuint buffer, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const GLvoid *data)
 {
     RegalContext *_context = REGAL_GET_CONTEXT();
     RegalAssert(_context);
     DispatchTableGL *_next = _context->dispatcher.logging.next();
     RegalAssert(_next);
-    _next->call(&_next->glClearNamedBufferSubDataEXT)(buffer, internalformat, format, type, offset, size, data);
-    Driver("glClearNamedBufferSubDataEXT","(", buffer, ", ", toString(internalformat), ", ", toString(format), ", ", toString(type), ", ", offset, ", ", size, ", ", boost::print::optional(data,Logging::pointers), ")");
+    _next->call(&_next->glClearNamedBufferSubDataEXT)(buffer, internalformat, offset, size, format, type, data);
+    Driver("glClearNamedBufferSubDataEXT","(", buffer, ", ", toString(internalformat), ", ", offset, ", ", size, ", ", toString(format), ", ", toString(type), ", ", boost::print::optional(data,Logging::pointers), ")");
 }
 
 // GL_ARB_clear_texture
diff --git a/src/regal/RegalDispatchMissing.cpp b/src/regal/RegalDispatchMissing.cpp
index 5821d25..9e6895c 100644
--- a/src/regal/RegalDispatchMissing.cpp
+++ b/src/regal/RegalDispatchMissing.cpp
@@ -5921,14 +5921,14 @@
     Warning( "glClearNamedBufferDataEXT", " not available." );
   }
 
-  static void REGAL_CALL glClearNamedBufferSubDataEXT(GLuint buffer, GLenum internalformat, GLenum format, GLenum type, GLintptr offset, GLsizeiptr size, const GLvoid *data)
+  static void REGAL_CALL glClearNamedBufferSubDataEXT(GLuint buffer, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const GLvoid *data)
 {
     UNUSED_PARAMETER(buffer);
     UNUSED_PARAMETER(internalformat);
-    UNUSED_PARAMETER(format);
-    UNUSED_PARAMETER(type);
     UNUSED_PARAMETER(offset);
     UNUSED_PARAMETER(size);
+    UNUSED_PARAMETER(format);
+    UNUSED_PARAMETER(type);
     UNUSED_PARAMETER(data);
     Warning( "glClearNamedBufferSubDataEXT", " not available." );
   }
diff --git a/src/regal/RegalDispatchStatistics.cpp b/src/regal/RegalDispatchStatistics.cpp
index 1e36199..0875ce2 100644
--- a/src/regal/RegalDispatchStatistics.cpp
+++ b/src/regal/RegalDispatchStatistics.cpp
@@ -10886,7 +10886,7 @@
   _next->call(&_next->glClearNamedBufferDataEXT)(buffer, internalformat, format, type, data);
 }
 
-static void REGAL_CALL statistics_glClearNamedBufferSubDataEXT(GLuint buffer, GLenum internalformat, GLenum format, GLenum type, GLintptr offset, GLsizeiptr size, const GLvoid *data)
+static void REGAL_CALL statistics_glClearNamedBufferSubDataEXT(GLuint buffer, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const GLvoid *data)
 {
   RegalContext *_context = REGAL_GET_CONTEXT();
   RegalAssert(_context);
@@ -10899,7 +10899,7 @@
 
   DispatchTableGL *_next = _context->dispatcher.statistics.next();
   RegalAssert(_next);
-  _next->call(&_next->glClearNamedBufferSubDataEXT)(buffer, internalformat, format, type, offset, size, data);
+  _next->call(&_next->glClearNamedBufferSubDataEXT)(buffer, internalformat, offset, size, format, type, data);
 }
 
 // GL_ARB_clear_texture
diff --git a/src/regal/RegalDispatchTrace.cpp b/src/regal/RegalDispatchTrace.cpp
index 01aeba1..2a2b543 100644
--- a/src/regal/RegalDispatchTrace.cpp
+++ b/src/regal/RegalDispatchTrace.cpp
@@ -892,7 +892,7 @@
   void  glClearBufferData(GLenum target, GLenum internalformat, GLenum format, GLenum type, const GLvoid *data);
   void  glClearBufferSubData(GLenum target, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const GLvoid *data);
   void  glClearNamedBufferDataEXT(GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const GLvoid *data);
-  void  glClearNamedBufferSubDataEXT(GLuint buffer, GLenum internalformat, GLenum format, GLenum type, GLintptr offset, GLsizeiptr size, const GLvoid *data);
+  void  glClearNamedBufferSubDataEXT(GLuint buffer, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const GLvoid *data);
 
 // GL_ARB_clear_texture
 
@@ -2664,6 +2664,10 @@
   void  glProgramNamedParameter4fNV(GLuint id, GLsizei len, const GLubyte *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
   void  glProgramNamedParameter4fvNV(GLuint id, GLsizei len, const GLubyte *name, const GLfloat *v);
 
+// GL_NV_framebuffer_blit
+
+  void  glBlitFramebufferNV(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
+
 // GL_NV_framebuffer_multisample_coverage
 
   void  glRenderbufferStorageMultisampleCoverageNV(GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height);
@@ -11162,14 +11166,14 @@
   Trace::glClearNamedBufferDataEXT(buffer, internalformat, format, type, data);
 }
 
-static void REGAL_CALL trace_glClearNamedBufferSubDataEXT(GLuint buffer, GLenum internalformat, GLenum format, GLenum type, GLintptr offset, GLsizeiptr size, const GLvoid *data)
+static void REGAL_CALL trace_glClearNamedBufferSubDataEXT(GLuint buffer, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const GLvoid *data)
 {
   Internal("trace_glClearNamedBufferSubDataEXT","()");
   Thread::ThreadLocal &_instance = Thread::ThreadLocal::instance();
   RegalAssert(_instance.currentContext);
   Push<DispatchTableGL *> _push(_instance.nextDispatchTable);
   _instance.nextDispatchTable = _instance.currentContext->dispatcher.trace.next();
-  Trace::glClearNamedBufferSubDataEXT(buffer, internalformat, format, type, offset, size, data);
+  Trace::glClearNamedBufferSubDataEXT(buffer, internalformat, offset, size, format, type, data);
 }
 
 // GL_ARB_clear_texture
@@ -24545,6 +24549,18 @@
   Trace::glProgramNamedParameter4fvNV(id, len, name, v);
 }
 
+// GL_NV_framebuffer_blit
+
+static void REGAL_CALL trace_glBlitFramebufferNV(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter)
+{
+  Internal("trace_glBlitFramebufferNV","()");
+  Thread::ThreadLocal &_instance = Thread::ThreadLocal::instance();
+  RegalAssert(_instance.currentContext);
+  Push<DispatchTableGL *> _push(_instance.nextDispatchTable);
+  _instance.nextDispatchTable = _instance.currentContext->dispatcher.trace.next();
+  Trace::glBlitFramebufferNV(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter);
+}
+
 // GL_NV_framebuffer_multisample_coverage
 
 static void REGAL_CALL trace_glRenderbufferStorageMultisampleCoverageNV(GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height)
@@ -36463,6 +36479,10 @@
   tbl.glProgramNamedParameter4fNV = trace_glProgramNamedParameter4fNV;
   tbl.glProgramNamedParameter4fvNV = trace_glProgramNamedParameter4fvNV;
 
+  // GL_NV_framebuffer_blit
+
+  tbl.glBlitFramebufferNV = trace_glBlitFramebufferNV;
+
   // GL_NV_framebuffer_multisample_coverage
 
   tbl.glRenderbufferStorageMultisampleCoverageNV = trace_glRenderbufferStorageMultisampleCoverageNV;
diff --git a/src/regal/RegalHttp.cpp b/src/regal/RegalHttp.cpp
index f430b64..64f0daa 100644
--- a/src/regal/RegalHttp.cpp
+++ b/src/regal/RegalHttp.cpp
@@ -67,7 +67,7 @@
 #include <boost/print/print_string.hpp>
 using boost::print::print_string;
 
-#include "mongoose.h"
+#include "civetweb.h"
 
 REGAL_GLOBAL_END
 
@@ -79,7 +79,7 @@
   int  port    = REGAL_HTTP_PORT; // HTTP listening port - 8080 by default
 
   mg_callbacks callbacks;         // Callbacks
-  mg_context   *ctx = NULL;       // Mongoose context
+  mg_context   *ctx = NULL;       // civetweb context
 
   void Init()
   {
@@ -198,7 +198,7 @@
               html);
 
     mg_write(conn,http.c_str(),http.length());
-    return 1;  // Mark as handled for Mongoose
+    return 1;  // Mark as handled for civetweb
   }
 
   void Start()
@@ -246,7 +246,7 @@
     {
       HTrace("Closing HTTP connections.");
 
-      // Currently there is a problem with shutting down mongoose
+      // Currently there is a problem with shutting down civetweb
       // on Windows - so just skip the cleanup for now.
 
       #if !REGAL_SYS_WGL
diff --git a/src/regal/RegalPlugin.cpp b/src/regal/RegalPlugin.cpp
index e568955..21edf06 100644
--- a/src/regal/RegalPlugin.cpp
+++ b/src/regal/RegalPlugin.cpp
@@ -6118,12 +6118,12 @@
     _next->call(&_next->glClearNamedBufferDataEXT)(buffer, internalformat, format, type, data);
   }
 
-  void REGAL_CALL plugin_glClearNamedBufferSubDataEXT(GLuint buffer, GLenum internalformat, GLenum format, GLenum type, GLintptr offset, GLsizeiptr size, const GLvoid *data)
+  void REGAL_CALL plugin_glClearNamedBufferSubDataEXT(GLuint buffer, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const GLvoid *data)
   {
     ::REGAL_NAMESPACE_INTERNAL::Thread::ThreadLocal &_instance = ::REGAL_NAMESPACE_INTERNAL::Thread::ThreadLocal::instance();
     ::REGAL_NAMESPACE_INTERNAL::DispatchTableGL *_next = _instance.nextDispatchTable;
     RegalAssert(_next);
-    _next->call(&_next->glClearNamedBufferSubDataEXT)(buffer, internalformat, format, type, offset, size, data);
+    _next->call(&_next->glClearNamedBufferSubDataEXT)(buffer, internalformat, offset, size, format, type, data);
   }
 
   /* GL_ARB_clear_texture */