浏览代码

first commit

xhj 8 月之前
当前提交
4d99525703
共有 100 个文件被更改,包括 18725 次插入0 次删除
  1. 二进制
      .DS_Store
  2. 15 0
      .clang-format
  3. 64 0
      CMakeLists.txt
  4. 176 0
      Makefile
  5. 1 0
      README.md
  6. 二进制
      document/.DS_Store
  7. 42 0
      document/cmake.md
  8. 133 0
      document/compile/deploy.sh
  9. 211 0
      document/json/Communication.json
  10. 53 0
      document/json/CommunicationGPIO.json
  11. 137 0
      document/json/CommunicationRS485.json
  12. 52 0
      document/json/Feature.json
  13. 269 0
      document/json/Protocol.json
  14. 190 0
      document/json/gateway_server_communication.json
  15. 269 0
      document/json/gateway_server_protocol.json
  16. 452 0
      document/json/gateway_server_protocol.json.backup
  17. 15 0
      document/markdown/Debug.md
  18. 9 0
      document/markdown/README.md
  19. 72 0
      document/markdown/Redis.md
  20. 109 0
      document/markdown/Remain.md
  21. 72 0
      document/modbus/ModbusUtils.cpp
  22. 39 0
      document/modbus/ModbusUtils.h
  23. 20 0
      document/request/request.http
  24. 二进制
      library/.DS_Store
  25. 2383 0
      library/include/MQTTAsync.h
  26. 1980 0
      library/include/MQTTClient.h
  27. 277 0
      library/include/MQTTClientPersistence.h
  28. 36 0
      library/include/MQTTExportDeclarations.h
  29. 222 0
      library/include/MQTTProperties.h
  30. 79 0
      library/include/MQTTReasonCodes.h
  31. 46 0
      library/include/MQTTSubscribeOpts.h
  32. 二进制
      library/include/boost/.DS_Store
  33. 27 0
      library/include/boost/accumulators/accumulators.hpp
  34. 232 0
      library/include/boost/accumulators/accumulators_fwd.hpp
  35. 65 0
      library/include/boost/accumulators/framework/accumulator_base.hpp
  36. 29 0
      library/include/boost/accumulators/framework/accumulator_concept.hpp
  37. 549 0
      library/include/boost/accumulators/framework/accumulator_set.hpp
  38. 333 0
      library/include/boost/accumulators/framework/accumulators/droppable_accumulator.hpp
  39. 108 0
      library/include/boost/accumulators/framework/accumulators/external_accumulator.hpp
  40. 89 0
      library/include/boost/accumulators/framework/accumulators/reference_accumulator.hpp
  41. 89 0
      library/include/boost/accumulators/framework/accumulators/value_accumulator.hpp
  42. 461 0
      library/include/boost/accumulators/framework/depends_on.hpp
  43. 27 0
      library/include/boost/accumulators/framework/external.hpp
  44. 248 0
      library/include/boost/accumulators/framework/extractor.hpp
  45. 29 0
      library/include/boost/accumulators/framework/features.hpp
  46. 22 0
      library/include/boost/accumulators/framework/parameters/accumulator.hpp
  47. 22 0
      library/include/boost/accumulators/framework/parameters/sample.hpp
  48. 23 0
      library/include/boost/accumulators/framework/parameters/weight.hpp
  49. 23 0
      library/include/boost/accumulators/framework/parameters/weights.hpp
  50. 75 0
      library/include/boost/accumulators/numeric/detail/function1.hpp
  51. 10 0
      library/include/boost/accumulators/numeric/detail/function2.hpp
  52. 10 0
      library/include/boost/accumulators/numeric/detail/function3.hpp
  53. 10 0
      library/include/boost/accumulators/numeric/detail/function4.hpp
  54. 148 0
      library/include/boost/accumulators/numeric/detail/function_n.hpp
  55. 20 0
      library/include/boost/accumulators/numeric/detail/pod_singleton.hpp
  56. 537 0
      library/include/boost/accumulators/numeric/functional.hpp
  57. 82 0
      library/include/boost/accumulators/numeric/functional/complex.hpp
  58. 362 0
      library/include/boost/accumulators/numeric/functional/valarray.hpp
  59. 347 0
      library/include/boost/accumulators/numeric/functional/vector.hpp
  60. 221 0
      library/include/boost/accumulators/numeric/functional_fwd.hpp
  61. 61 0
      library/include/boost/accumulators/statistics.hpp
  62. 87 0
      library/include/boost/accumulators/statistics/count.hpp
  63. 219 0
      library/include/boost/accumulators/statistics/covariance.hpp
  64. 266 0
      library/include/boost/accumulators/statistics/density.hpp
  65. 99 0
      library/include/boost/accumulators/statistics/error_of.hpp
  66. 73 0
      library/include/boost/accumulators/statistics/error_of_mean.hpp
  67. 309 0
      library/include/boost/accumulators/statistics/extended_p_square.hpp
  68. 332 0
      library/include/boost/accumulators/statistics/extended_p_square_quantile.hpp
  69. 116 0
      library/include/boost/accumulators/statistics/kurtosis.hpp
  70. 92 0
      library/include/boost/accumulators/statistics/max.hpp
  71. 308 0
      library/include/boost/accumulators/statistics/mean.hpp
  72. 324 0
      library/include/boost/accumulators/statistics/median.hpp
  73. 92 0
      library/include/boost/accumulators/statistics/min.hpp
  74. 132 0
      library/include/boost/accumulators/statistics/moment.hpp
  75. 279 0
      library/include/boost/accumulators/statistics/p_square_cumul_dist.hpp
  76. 19 0
      library/include/boost/accumulators/statistics/p_square_cumulative_distribution.hpp
  77. 271 0
      library/include/boost/accumulators/statistics/p_square_quantile.hpp
  78. 23 0
      library/include/boost/accumulators/statistics/parameters/quantile_probability.hpp
  79. 434 0
      library/include/boost/accumulators/statistics/peaks_over_threshold.hpp
  80. 212 0
      library/include/boost/accumulators/statistics/pot_quantile.hpp
  81. 219 0
      library/include/boost/accumulators/statistics/pot_tail_mean.hpp
  82. 84 0
      library/include/boost/accumulators/statistics/rolling_count.hpp
  83. 196 0
      library/include/boost/accumulators/statistics/rolling_mean.hpp
  84. 120 0
      library/include/boost/accumulators/statistics/rolling_moment.hpp
  85. 98 0
      library/include/boost/accumulators/statistics/rolling_sum.hpp
  86. 259 0
      library/include/boost/accumulators/statistics/rolling_variance.hpp
  87. 221 0
      library/include/boost/accumulators/statistics/rolling_window.hpp
  88. 118 0
      library/include/boost/accumulators/statistics/skewness.hpp
  89. 29 0
      library/include/boost/accumulators/statistics/stats.hpp
  90. 146 0
      library/include/boost/accumulators/statistics/sum.hpp
  91. 196 0
      library/include/boost/accumulators/statistics/sum_kahan.hpp
  92. 352 0
      library/include/boost/accumulators/statistics/tail.hpp
  93. 254 0
      library/include/boost/accumulators/statistics/tail_mean.hpp
  94. 162 0
      library/include/boost/accumulators/statistics/tail_quantile.hpp
  95. 150 0
      library/include/boost/accumulators/statistics/tail_variate.hpp
  96. 270 0
      library/include/boost/accumulators/statistics/tail_variate_means.hpp
  97. 70 0
      library/include/boost/accumulators/statistics/times2_iterator.hpp
  98. 247 0
      library/include/boost/accumulators/statistics/variance.hpp
  99. 25 0
      library/include/boost/accumulators/statistics/variates/covariate.hpp
  100. 140 0
      library/include/boost/accumulators/statistics/weighted_covariance.hpp

二进制
.DS_Store


+ 15 - 0
.clang-format

@@ -0,0 +1,15 @@
+
+---
+# We'll use defaults from the LLVM style, but with 4 columns indentation.
+# BasedOnStyle: LLVM
+BasedOnStyle: Google
+IndentWidth: 2
+
+---
+Language: Cpp
+# Force pointers to the type for C++.
+# DerivePointerAlignment: false
+# PointerAlignment: Left
+ColumnLimit: 160
+
+

+ 64 - 0
CMakeLists.txt

@@ -0,0 +1,64 @@
+
+# Set the minimum version of CMake that can be used
+# To find the cmake version run
+# $ cmake --version
+cmake_minimum_required(VERSION 3.13)
+
+# -std=c++17
+set(CMAKE_CXX_STANDARD 17)
+
+
+# add compiler flags for neovim lsp 
+set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
+set(CMAKE_CXX_STANDARD_REQUIRED ON)
+
+# Set the output directory for executables
+set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/build)
+
+
+# set(DATA_BASE_DIR /usr/local/bin)
+
+set(DATA_BASE_SQLITE_DIR /usr/local/bin/database/sqlite)
+set(DATA_BASE_JSON_DIR /usr/local/bin/database/json)
+
+
+# set(DATA_BASE_SQLITE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/database/sqlite)
+# set(DATA_BASE_JSON_DIR ${CMAKE_CURRENT_SOURCE_DIR}/database/json)
+
+
+# 设置交叉编译器路径
+set(TOOLCHAIN_PREFIX /home/ubuntu/Desktop/gcc-linaro-7.5.0-2019.12-x86_64_aarch64-linux-gnu/bin/aarch64-linux-gnu-)
+
+# 设置 C 编译器
+set(CMAKE_C_COMPILER ${TOOLCHAIN_PREFIX}gcc)
+
+# 设置 C++ 编译器
+set(CMAKE_CXX_COMPILER ${TOOLCHAIN_PREFIX}g++)
+
+# 指定目标系统
+set(CMAKE_SYSTEM_NAME Linux)
+set(CMAKE_SYSTEM_PROCESSOR aarch64)
+
+# define debug
+add_definitions(-DDEBUG)
+# define DATA_BASE_DIR to project source directory database 
+add_definitions(-DDATABASE_SQLITE_DIR="${DATA_BASE_SQLITE_DIR}")
+add_definitions(-DDATABASE_JSON_DIR="${DATA_BASE_JSON_DIR}")
+
+
+# Set the project name
+project (embedded-gateway)
+
+
+add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/modules/gateway-basic)
+add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/modules/gateway-scheduler)
+add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/modules/gateway-server)
+
+
+##### sub directories #####
+#
+# add_subdirectory(${PROJECT_SOURCE_DIR}/modules/gateway-collector)
+# add_subdirectory(${PROJECT_SOURCE_DIR}/modules/gateway-schedule)
+#
+##### sub directories #####
+

+ 176 - 0
Makefile

@@ -0,0 +1,176 @@
+# CMAKE generated file: DO NOT EDIT!
+# Generated by "Unix Makefiles" Generator, CMake Version 3.16
+
+# Default target executed when no arguments are given to make.
+default_target: all
+
+.PHONY : default_target
+
+# Allow only one "make -f Makefile2" at a time, but pass parallelism.
+.NOTPARALLEL:
+
+
+#=============================================================================
+# Special targets provided by cmake.
+
+# Disable implicit rules so canonical targets will work.
+.SUFFIXES:
+
+
+# Remove some rules from gmake that .SUFFIXES does not remove.
+SUFFIXES =
+
+.SUFFIXES: .hpux_make_needs_suffix_list
+
+
+# Suppress display of executed commands.
+$(VERBOSE).SILENT:
+
+
+# A target that is always out of date.
+cmake_force:
+
+.PHONY : cmake_force
+
+#=============================================================================
+# Set environment variables for the build.
+
+# The shell in which to execute make rules.
+SHELL = /bin/sh
+
+# The CMake executable.
+CMAKE_COMMAND = /usr/bin/cmake
+
+# The command to remove a file.
+RM = /usr/bin/cmake -E remove -f
+
+# Escaping for special characters.
+EQUALS = =
+
+# The top-level source directory on which CMake was run.
+CMAKE_SOURCE_DIR = /home/ubuntu/embedded-gateway
+
+# The top-level build directory on which CMake was run.
+CMAKE_BINARY_DIR = /home/ubuntu/embedded-gateway
+
+#=============================================================================
+# Targets provided globally by CMake.
+
+# Special rule for the target rebuild_cache
+rebuild_cache:
+	@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..."
+	/usr/bin/cmake -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)
+.PHONY : rebuild_cache
+
+# Special rule for the target rebuild_cache
+rebuild_cache/fast: rebuild_cache
+
+.PHONY : rebuild_cache/fast
+
+# Special rule for the target edit_cache
+edit_cache:
+	@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "No interactive CMake dialog available..."
+	/usr/bin/cmake -E echo No\ interactive\ CMake\ dialog\ available.
+.PHONY : edit_cache
+
+# Special rule for the target edit_cache
+edit_cache/fast: edit_cache
+
+.PHONY : edit_cache/fast
+
+# The main all target
+all: cmake_check_build_system
+	$(CMAKE_COMMAND) -E cmake_progress_start /home/ubuntu/embedded-gateway/CMakeFiles /home/ubuntu/embedded-gateway/CMakeFiles/progress.marks
+	$(MAKE) -f CMakeFiles/Makefile2 all
+	$(CMAKE_COMMAND) -E cmake_progress_start /home/ubuntu/embedded-gateway/CMakeFiles 0
+.PHONY : all
+
+# The main clean target
+clean:
+	$(MAKE) -f CMakeFiles/Makefile2 clean
+.PHONY : clean
+
+# The main clean target
+clean/fast: clean
+
+.PHONY : clean/fast
+
+# Prepare targets for installation.
+preinstall: all
+	$(MAKE) -f CMakeFiles/Makefile2 preinstall
+.PHONY : preinstall
+
+# Prepare targets for installation.
+preinstall/fast:
+	$(MAKE) -f CMakeFiles/Makefile2 preinstall
+.PHONY : preinstall/fast
+
+# clear depends
+depend:
+	$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1
+.PHONY : depend
+
+#=============================================================================
+# Target rules for targets named gateway-basic
+
+# Build rule for target.
+gateway-basic: cmake_check_build_system
+	$(MAKE) -f CMakeFiles/Makefile2 gateway-basic
+.PHONY : gateway-basic
+
+# fast build rule for target.
+gateway-basic/fast:
+	$(MAKE) -f modules/gateway-basic/CMakeFiles/gateway-basic.dir/build.make modules/gateway-basic/CMakeFiles/gateway-basic.dir/build
+.PHONY : gateway-basic/fast
+
+#=============================================================================
+# Target rules for targets named gateway-scheduler
+
+# Build rule for target.
+gateway-scheduler: cmake_check_build_system
+	$(MAKE) -f CMakeFiles/Makefile2 gateway-scheduler
+.PHONY : gateway-scheduler
+
+# fast build rule for target.
+gateway-scheduler/fast:
+	$(MAKE) -f modules/gateway-scheduler/CMakeFiles/gateway-scheduler.dir/build.make modules/gateway-scheduler/CMakeFiles/gateway-scheduler.dir/build
+.PHONY : gateway-scheduler/fast
+
+#=============================================================================
+# Target rules for targets named gateway-server
+
+# Build rule for target.
+gateway-server: cmake_check_build_system
+	$(MAKE) -f CMakeFiles/Makefile2 gateway-server
+.PHONY : gateway-server
+
+# fast build rule for target.
+gateway-server/fast:
+	$(MAKE) -f modules/gateway-server/CMakeFiles/gateway-server.dir/build.make modules/gateway-server/CMakeFiles/gateway-server.dir/build
+.PHONY : gateway-server/fast
+
+# Help Target
+help:
+	@echo "The following are some of the valid targets for this Makefile:"
+	@echo "... all (the default if no target is provided)"
+	@echo "... clean"
+	@echo "... depend"
+	@echo "... rebuild_cache"
+	@echo "... edit_cache"
+	@echo "... gateway-basic"
+	@echo "... gateway-scheduler"
+	@echo "... gateway-server"
+.PHONY : help
+
+
+
+#=============================================================================
+# Special targets to cleanup operation of make.
+
+# Special rule to run CMake to check the build system integrity.
+# No rule that depends on this can have commands that come from listfiles
+# because they might be regenerated.
+cmake_check_build_system:
+	$(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0
+.PHONY : cmake_check_build_system
+

+ 1 - 0
README.md

@@ -0,0 +1 @@
+# embedded-gateway

二进制
document/.DS_Store


+ 42 - 0
document/cmake.md

@@ -0,0 +1,42 @@
+
+```
+
+# Set the project name
+project (gateway-server)
+
+
+# CMAKE_SOURCE_DIR path to CMakeLists.txt directory
+set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/deploy/bin)
+
+
+set(INCLUDE_SUBDIRECTORIES 
+        ${CMAKE_SOURCE_DIR}/include
+        ${CMAKE_SOURCE_DIR}/library/include
+        ${CMAKE_SOURCE_DIR}/include/gateway-server
+)
+
+
+include_directories(${INCLUDE_SUBDIRECTORIES})
+
+set(CMAKE_PREFIX_PATH "${CMAKE_SOURCE_DIR}/library")
+ 
+find_library(MICROHTTPD_LIB microhttpd PATHS "${CMAKE_SOURCE_DIR}/lib")
+
+
+
+
+file(GLOB_RECURSE SRC_FILES src/*.cpp)
+
+
+# link_directories(${CMAKE_SOURCE_DIR}/library)
+# link_libraries(microhttpd)
+
+
+# Add an executable
+add_executable(${PROJECT_NAME} ${SRC_FILES})
+
+ 
+target_link_libraries(${PROJECT_NAME} ${MICROHTTPD_LIB})
+
+
+```

+ 133 - 0
document/compile/deploy.sh

@@ -0,0 +1,133 @@
+
+ 
+HOME_PATH="/home/forlinx/asmodeus" 
+ 
+# file libboost_math_c99l.so.1.82.0
+
+auto_reconfig() {
+
+    autoreconf -f -i
+
+}
+
+ 
+lib_microhttpd_compile() { 
+ 
+        cd libmicrohttpd 
+ 
+        ./configure --prefix=$HOME_PATH/third-part-library/build CC=aarch64-linux-gnu-gcc  --host aarch64-linux-gnu 
+ 
+        make 
+ 
+        make install  
+ 
+} 
+ 
+lib_modbus_compile() { 
+ 
+        cd libmodbus 
+ 
+        ./autogen.sh 
+ 
+        ./configure --prefix=$HOME_PATH/third-part-library/build CC=aarch64-linux-gnu-gcc  --host aarch64-linux-gnu 
+ 
+        make 
+ 
+        make install  
+ 
+} 
+
+
+lib_sqlite_compile() {
+
+        cd sqlite-autoconf
+
+        ./configure --prefix=$HOME_PATH/third-part-library/build CC=aarch64-linux-gnu-gcc  --host aarch64-linux-gnu
+
+        make
+
+        make install
+
+}
+
+
+lib_boost_compile() {
+
+
+    # ./bootstrap.sh
+    # vim project-config.jam
+    # if ! gcc in [ feature.values <toolset> ]
+    # {
+    #    using gcc : : /usr/bin/aarch64-linux-gnu-gcc ;
+    # }
+    # sudo ./b2
+    # sudo ./b2 install
+
+    cd boost_1_84_0
+
+    ./bootstrap.sh --prefix=$HOME_PATH/third-part-library/build CC=aarch64-linux-gnu-gcc  --host aarch64-linux-gnu
+
+    ./b2
+
+    ./b2 install
+
+}
+
+
+# TODO 
+lib_json_compile() {
+
+    cd json 
+
+    mkdir build
+    
+    cd build
+    
+    cmake ../CMakeLists.txt --install-prefix=$HOME_PATH/third-part-library/build CC=aarch64-linux-gnu-gcc  --host aarch64-linux-gnu -j 8 
+
+    make 
+
+    make install 
+
+}
+
+lib_hiredis_compile() {
+    cd hiredis
+
+    mkdir build
+    
+    cd build
+    
+    cmake ../CMakeLists.txt --install-prefix=$HOME_PATH/third-part-library/build CC=aarch64-linux-gnu-gcc  --host aarch64-linux-gnu
+    # cmake ../CMakeLists.txt -DCMAKE_INSTALL_PREFIX=$HOME_PATH/third-part-library/build CC=aarch64-linux-gnu-gcc  --host aarch64-linux-gnu
+
+    make 
+
+    make install
+
+}
+
+redis_compile() {
+
+    # sudo apt-get install libjemalloc-dev
+    #
+    # make distclean
+
+    # make PREFIX=/path/to/build/directory CC=aarch64-linux-gnu-gcc  MALLOC=libc
+
+    make prefix=/path/to/build/directory CC=aarch64-linux-gnu-gcc  MALLOC=libc
+    
+}
+
+ 
+echo " begin compile third part library " 
+ 
+echo " begin compile lib_modbus " 
+
+lib_modbus_compile 
+ 
+echo " compile complete " 
+ 
+ 
+
+

+ 211 - 0
document/json/Communication.json

@@ -0,0 +1,211 @@
+[
+  {
+    "id": 1,
+    "key": "GPIO",
+    "name": "GPIO",
+    "description": "",
+    "properties": [
+      {
+        "id": 1,
+        "key": "GPIO_CODE",
+        "name": "系统GPIO号",
+        "label": "系统GPIO号",
+        "type": "integer",
+        "defaultValue": "66",
+        "placeholder": "请输入系统GPIO号",
+        "description": " linux 系统 GPIO 号, 0-63 ",
+        "selections": []
+      },
+      {
+        "id": 2,
+        "key": "GPIO_INPUT_OUTPUT",
+        "name": "输入、输出",
+        "label": "输入、输出",
+        "type": "select",
+        "defaultValue": "1",
+        "placeholder": "请选择输入、输出",
+        "description": " GPIO类型 输入、输出 ",
+        "selections": [
+          {
+            "value": 1,
+            "label": "输入"
+          },
+          {
+            "value": 2,
+            "label": "输出"
+          }
+        ]
+      },
+      {
+        "id": 3,
+        "key": "GPIO_DEFAULT_VOLTAGE",
+        "name": "默认值",
+        "label": "默认值",
+        "type": "select",
+        "defaultValue": "1",
+        "placeholder": "请选择默认值",
+        "description": " GPIO类型 默认值 ",
+        "selections": [
+          {
+            "value": 1,
+            "label": "低电平"
+          },
+          {
+            "value": 2,
+            "label": "高电平"
+          }
+        ]
+      }
+    ],
+    "executor": {
+      "id": 1,
+      "key": "GPIO_EXECUTOR",
+      "name": "GPIO_EXECUTOR",
+      "description": "",
+      "properties": []
+    }
+  },
+  {
+    "id": 2,
+    "key": "RS485_RTU",
+    "name": "RS485_RTU",
+    "description": "",
+    "properties": [
+      {
+        "id": 1,
+        "key": "RS485_PORT",
+        "name": "串口名称",
+        "label": "串口名称",
+        "type": "string",
+        "defaultValue": "",
+        "placeholder": "请输入系统串口名称",
+        "description": " linux 系统串口名称, 0-63 ",
+        "selections": []
+      },
+      {
+        "id": 1,
+        "key": "RS485_ADDRESS",
+        "name": "设备地址",
+        "label": "设备地址",
+        "type": "string",
+        "defaultValue": "",
+        "placeholder": "请输入设备地址",
+        "description": "设备地址标识",
+        "selections": []
+      },
+      {
+        "id": 2,
+        "key": "RS485_BAUDRATE",
+        "name": "波特率",
+        "label": "波特率",
+        "type": "integer",
+        "defaultValue": "1",
+        "placeholder": "请输入波特率",
+        "description": "请输入波特率",
+        "selections": []
+      },
+      {
+        "id": 3,
+        "key": "RS485_STOP_BIT",
+        "name": "停止位",
+        "label": "停止位",
+        "type": "select",
+        "defaultValue": "1",
+        "placeholder": "请选择停止位",
+        "description": " RS485 停止位 ",
+        "selections": [
+          {
+            "value": 1,
+            "label": "1位"
+          },
+          {
+            "value": 2,
+            "label": "2位"
+          }
+        ]
+      },
+      {
+        "id": 4,
+        "key": "RS485_VERIFY",
+        "name": "校验位",
+        "label": "校验位",
+        "type": "select",
+        "defaultValue": "1",
+        "placeholder": "请选择校验位",
+        "description": " RS485 校验位 ",
+        "selections": [
+          {
+            "value": 1,
+            "label": "无校验"
+          },
+          {
+            "value": 2,
+            "label": "奇校验"
+          },
+          {
+            "value": 3,
+            "label": "偶校验"
+          }
+        ]
+      },
+      {
+        "id": 5,
+        "key": "RS485_DATA_BIT",
+        "name": "数据位",
+        "label": "数据位",
+        "type": "select",
+        "defaultValue": "1",
+        "placeholder": "请选择数据位",
+        "description": " RS485 数据位 ",
+        "selections": [
+          {
+            "value": 1,
+            "label": "5位"
+          },
+          {
+            "value": 2,
+            "label": "6位"
+          },
+          {
+            "value": 3,
+            "label": "7位"
+          },
+          {
+            "value": 4,
+            "label": "8位"
+          }
+        ]
+      }
+    ],
+    "executor": {
+      "id": 1,
+      "key": "RS485_RTU_EXECUTOR",
+      "name": "RS485_RTU_EXECUTOR",
+      "description": "",
+      "properties": [
+        {
+          "id": 1,
+          "key": "RS485_REGISTER_ADDRESS",
+          "name": "寄存器地址",
+          "label": "寄存器地址",
+          "type": "integer",
+          "defaultValue": "0",
+          "placeholder": "请输入寄存器地址",
+          "description": "",
+          "selections": []
+        },
+        {
+          "id": 2,
+          "key": "RS485_REGISTER_QUANTITY",
+          "name": "寄存器数量",
+          "label": "寄存器数量",
+          "type": "integer",
+          "defaultValue": "0",
+          "placeholder": "请输入寄存器数量",
+          "description": "",
+          "selections": []
+        }
+      ]
+    }
+  }
+]

+ 53 - 0
document/json/CommunicationGPIO.json

@@ -0,0 +1,53 @@
+{
+  "id": 1,
+  "key": "GPIO",
+  "name": "GPIO",
+  "description": "",
+  "properties": [
+    {
+      "id": 1,
+      "name": "系统GPIO号",
+      "type": "integer",
+      "default": "66",
+      "placeholder": "请输入系统GPIO号",
+      "description": " linux 系统 GPIO 号, 0-63 ",
+      "selection": []
+    },
+    {
+      "id": 2,
+      "name": "输入、输出",
+      "type": "select",
+      "default": 0,
+      "placeholder": "请选择输入、输出",
+      "description": " GPIO类型 输入、输出 ",
+      "selection": [
+        {
+          "value": 0,
+          "name": "输入"
+        },
+        {
+          "value": 1,
+          "name": "输出"
+        }
+      ]
+    },
+    {
+      "id": 3,
+      "name": "默认值",
+      "type": "select",
+      "default": 0,
+      "placeholder": "请选择默认值",
+      "description": " GPIO类型 默认值 ",
+      "selection": [
+        {
+          "value": 0,
+          "name": "低电平"
+        },
+        {
+          "value": 1,
+          "name": "高电平"
+        }
+      ]
+    }
+  ]
+}

+ 137 - 0
document/json/CommunicationRS485.json

@@ -0,0 +1,137 @@
+{
+  "key": "RS-485-RTU",
+  "label": "RS-485-RTU",
+  "description": "",
+  "properties": [
+    {
+      "key": "",
+      "label": "系统串口标识",
+      "type": "string",
+      "default": "COM1",
+      "placeholder": "请输入系统串口标识",
+      "description": "",
+      "selections": []
+    },
+    {
+      "label": "硬件串口名称",
+      "type": "string",
+      "default": "环控主机一号串口",
+      "placeholder": "请输入硬件串口名称",
+      "description": "",
+      "selection": []
+    },
+    {
+      "label": "波特率",
+      "type": "select",
+      "default": 0,
+      "placeholder": "请输入串口名称",
+      "description": "",
+      "selection": [
+        {
+          "value": 0,
+          "label": "9600"
+        },
+        {
+          "value": 1,
+          "label": "19200"
+        },
+        {
+          "value": 2,
+          "label": "38400"
+        },
+        {
+          "value": 3,
+          "label": "57600"
+        },
+        {
+          "value": 4,
+          "label": "115200"
+        }
+      ]
+    },
+    {
+      "id": 4,
+      "label": "停止位",
+      "type": "select",
+      "default": 0,
+      "placeholder": "请输入选择停止位",
+      "description": "",
+      "selection": [
+        {
+          "value": 0,
+          "label": "1位"
+        },
+        {
+          "value": 1,
+          "label": "2位"
+        }
+      ]
+    },
+    {
+      "id": 5,
+      "label": "停止位",
+      "type": "select",
+      "default": 0,
+      "placeholder": "请输入选择停止位",
+      "description": "",
+      "selection": [
+        {
+          "value": 0,
+          "label": "1位"
+        },
+        {
+          "value": 1,
+          "label": "2位"
+        }
+      ]
+    },
+    {
+      "id": 6,
+      "label": "校验方式",
+      "type": "select",
+      "default": 0,
+      "placeholder": "请输入选择校验方式",
+      "description": "",
+      "selection": [
+        {
+          "value": 0,
+          "label": "无校验"
+        },
+        {
+          "value": 1,
+          "label": "奇校验"
+        },
+        {
+          "value": 2,
+          "label": "偶校验"
+        }
+      ]
+    },
+    {
+      "key": 7,
+      "label": "数据位",
+      "type": "select",
+      "default": 0,
+      "placeholder": "请输入选择数据位",
+      "description": "",
+      "selection": [
+        {
+          "value": 0,
+          "label": "5"
+        },
+        {
+          "value": 1,
+          "label": "6"
+        },
+        {
+          "value": 2,
+          "label": "7"
+        },
+        {
+          "value": 3,
+          "label": "8"
+        }
+      ]
+    }
+  ]
+}

+ 52 - 0
document/json/Feature.json

@@ -0,0 +1,52 @@
+[
+  {
+    "id": 1,
+    "key": "Endianness",
+    "name": "遥测功能码",
+    "type": "string",
+    "default": 0,
+    "placeholder": "请输入遥测功能码",
+    "description": "",
+    "selection": []
+  },
+  {
+    "id": 2,
+    "key": "Endianness",
+    "name": "遥信功能码",
+    "type": "string",
+    "default": 0,
+    "placeholder": "请输入遥信功能码",
+    "description": "",
+    "selection": []
+  },
+  {
+    "id": 3,
+    "key": "Endianness",
+    "name": "遥脉功能码",
+    "type": "string",
+    "default": 0,
+    "placeholder": "请输入遥脉功能码",
+    "description": "",
+    "selection": []
+  },
+  {
+    "id": 4,
+    "key": "Endianness",
+    "name": "遥控功能码",
+    "type": "string",
+    "default": 0,
+    "placeholder": "请输入遥控功能码",
+    "description": "",
+    "selection": []
+  },
+  {
+    "id": 5,
+    "key": "Endianness",
+    "name": "遥调功能码",
+    "type": "string",
+    "default": 0,
+    "placeholder": "请输入遥调功能码",
+    "description": "",
+    "selection": []
+  }
+]

+ 269 - 0
document/json/Protocol.json

@@ -0,0 +1,269 @@
+[
+  {
+    "id": 1,
+    "key": "PROTOCAL_RS485",
+    "name": "RS485 规约 ",
+    "description": " ",
+    "properties": [
+      {
+        "id": 1,
+        "key": "RS485_CLEAR_INTERRUPT",
+        "name": "通信中断数据是否清零",
+        "label": "通信中断数据是否清零",
+        "type": "select",
+        "defaultValue": "",
+        "placeholder": "请选择通信中断数据是否清零",
+        "description": "",
+        "selections": [
+          {
+            "value": 1,
+            "label": "是"
+          },
+          {
+            "value": 2,
+            "label": "否"
+          }
+        ]
+      },
+      {
+        "id": 2,
+        "key": "RS485_SEND_TIME_INTERVAL",
+        "name": "发送时间间隔(ms)",
+        "label": "发送时间间隔(ms)",
+        "type": "double",
+        "defaultValue": "",
+        "description": "",
+        "placeholder": "输入发送时间间隔(ms)",
+        "selections": []
+      },
+      {
+        "id": 3,
+        "key": "RS485_TIME_OUT",
+        "name": "超时时间(ms)",
+        "label": "超时时间(ms)",
+        "type": "double",
+        "defaultValue": "",
+        "description": "",
+        "placeholder": "输入超时时间(ms)",
+        "selections": []
+      },
+      {
+        "id": 4,
+        "key": "RS485_COLON_NEEDED",
+        "name": "是否需要冒号",
+        "label": "是否需要冒号",
+        "type": "select",
+        "defaultValue": "",
+        "description": "",
+        "placeholder": "请选择是否需要冒号",
+        "selections": [
+          {
+            "value": 1,
+            "label": "不需要"
+          },
+          {
+            "value": 2,
+            "label": "需要"
+          }
+        ]
+      },
+      {
+        "id": 5,
+        "key": "RS485_ADDRESS_BIT",
+        "name": "地址字节长度",
+        "label": "地址字节长度",
+        "type": "integer",
+        "defaultValue": "",
+        "description": "",
+        "placeholder": "请输入地址字节长度",
+        "selections": []
+      },
+      {
+        "id": 6,
+        "key": "RS485_ADDRESS_ENDIANSS",
+        "name": "地址字节序",
+        "label": "地址字节序",
+        "type": "select",
+        "defaultValue": "",
+        "description": "",
+        "placeholder": "请选择地址字节序",
+        "selections": [
+          {
+            "value": 1,
+            "label": "前高后低"
+          },
+          {
+            "value": 2,
+            "label": "前低后高"
+          }
+        ]
+      },
+      {
+        "id": 7,
+        "key": "RS485_FUNCTION_BIT",
+        "name": "功能码字节长度",
+        "label": "功能码字节长度",
+        "type": "integer",
+        "defaultValue": "",
+        "description": "",
+        "placeholder": "请输入功能码字节长度",
+        "selections": []
+      },
+      {
+        "id": 8,
+        "key": "RS485_FUNCTION_ENDIANSS",
+        "name": "功能码字节序",
+        "label": "功能码字节序",
+        "type": "select",
+        "defaultValue": "",
+        "description": "",
+        "placeholder": "请选择功能码字节序",
+        "selections": [
+          {
+            "value": 1,
+            "label": "前高后低"
+          },
+          {
+            "value": 2,
+            "label": "前低后高"
+          }
+        ]
+      },
+      {
+        "id": 9,
+        "key": "RS485_VERIFY_ALGORITHM",
+        "name": "校验方式",
+        "label": "校验方式",
+        "type": "select",
+        "defaultValue": "",
+        "description": "",
+        "placeholder": "请选择校验方式",
+        "selections": [
+          {
+            "value": 1,
+            "label": "CRC8校验"
+          },
+          {
+            "value": 2,
+            "label": "CRC16校验"
+          },
+          {
+            "value": 3,
+            "label": "CRC32校验"
+          }
+        ]
+      },
+      {
+        "id": 10,
+        "key": "RS485_VERIFY_BIT",
+        "name": "校验码字节长度",
+        "label": "校验码字节长度",
+        "type": "integer",
+        "defaultValue": "",
+        "description": "",
+        "placeholder": "请输入校验码字节长度",
+        "selections": []
+      },
+      {
+        "id": 11,
+        "key": "RS485_VERIFY_ENDIANSS",
+        "name": "校验码字节序",
+        "label": "校验能码字节序",
+        "type": "select",
+        "defaultValue": "",
+        "description": "",
+        "placeholder": "请选择校验码字节序",
+        "selections": [
+          {
+            "value": 1,
+            "label": "前高后低"
+          },
+          {
+            "value": 2,
+            "label": "前低后高"
+          }
+        ]
+      },
+      {
+        "id": 12,
+        "key": "RS485_RETURN_BIT_ENDIANSS",
+        "name": "返回报文字组装方式",
+        "label": "返回报文字组装方式",
+        "type": "select",
+        "defaultValue": "",
+        "description": "",
+        "placeholder": "请输入返回报文字组装方式",
+        "selections": [
+          {
+            "value": 1,
+            "label": "前高后低"
+          },
+          {
+            "value": 2,
+            "label": "前低后高"
+          }
+        ]
+      },
+      {
+        "id": 13,
+        "key": "RS485_RETURN_BYTE_ENDIANSS",
+        "name": "返回报文字节组装方式",
+        "label": "返回报文字节组装方式",
+        "type": "select",
+        "defaultValue": "",
+        "description": "",
+        "placeholder": "请输入返回报文字节组装方式",
+        "selections": [
+          {
+            "value": 1,
+            "label": "前高后低"
+          },
+          {
+            "value": 2,
+            "label": "前低后高"
+          }
+        ]
+      },
+      {
+        "id": 14,
+        "key": "RS485_RETURN_BYTE",
+        "name": "返回数据字节数",
+        "label": "返回数据字节数",
+        "type": "select",
+        "defaultValue": "",
+        "description": "",
+        "placeholder": "请选择返回数据字节数",
+        "selections": [
+          {
+            "value": 1,
+            "label": "1"
+          },
+          {
+            "value": 2,
+            "label": "2"
+          }
+        ]
+      },
+      {
+        "id": 15,
+        "key": "RS485_NEGATIVE_DISPLAY",
+        "name": "负数显示方式",
+        "label": "负数显示方式",
+        "type": "select",
+        "defaultValue": "",
+        "description": "",
+        "placeholder": "请选择负数显示方式",
+        "selections": [
+          {
+            "value": 1,
+            "label": "补码"
+          },
+          {
+            "value": 2,
+            "label": "原码"
+          }
+        ]
+      }
+    ]
+  }
+]

+ 190 - 0
document/json/gateway_server_communication.json

@@ -0,0 +1,190 @@
+[
+  {
+    "id": 1,
+    "key": "GPIO",
+    "name": "GPIO",
+    "description": "",
+    "properties": [
+      {
+        "id": 1,
+        "key": "GPIO_CODE",
+        "name": "系统GPIO号",
+        "label": "系统GPIO号",
+        "type": "integer",
+        "defaultValue": "66",
+        "placeholder": "请输入系统GPIO号",
+        "description": " linux 系统 GPIO 号, 0-63 ",
+        "selections": []
+      },
+      {
+        "id": 2,
+        "key": "GPIO_INPUT_OUTPUT",
+        "name": "输入、输出",
+        "label": "输入、输出",
+        "type": "select",
+        "defaultValue": "1",
+        "placeholder": "请选择输入、输出",
+        "description": " GPIO类型 输入、输出 ",
+        "selections": [
+          {
+            "value": 1,
+            "label": "输入"
+          },
+          {
+            "value": 2,
+            "label": "输出"
+          }
+        ]
+      },
+      {
+        "id": 3,
+        "key": "GPIO_DEFAULT_VOLTAGE",
+        "name": "默认值",
+        "label": "默认值",
+        "type": "select",
+        "defaultValue": "1",
+        "placeholder": "请选择默认值",
+        "description": " GPIO类型 默认值 ",
+        "selections": [
+          {
+            "value": 1,
+            "label": "低电平"
+          },
+          {
+            "value": 2,
+            "label": "高电平"
+          }
+        ]
+      }
+    ],
+    "executor": {
+      "id": 1,
+      "key": "GPIO_EXECUTOR",
+      "name": "GPIO_EXECUTOR",
+      "description": "",
+      "properties": []
+    }
+  },
+  {
+    "id": 2,
+    "key": "RS485_RTU",
+    "name": "RS485_RTU",
+    "description": "",
+    "properties": [
+      {
+        "id": 1,
+        "key": "RS485_PORT",
+        "name": "串口名称",
+        "label": "串口名称",
+        "type": "string",
+        "defaultValue": "",
+        "placeholder": "请输入系统串口名称",
+        "description": " linux 系统串口名称, 0-63 ",
+        "selections": []
+      },
+      {
+        "id": 1,
+        "key": "RS485_ADDRESS",
+        "name": "设备地址",
+        "label": "设备地址",
+        "type": "string",
+        "defaultValue": "",
+        "placeholder": "请输入设备地址",
+        "description": "设备地址标识",
+        "selections": []
+      },
+      {
+        "id": 2,
+        "key": "RS485_BAUDRATE",
+        "name": "波特率",
+        "label": "波特率",
+        "type": "integer",
+        "defaultValue": "1",
+        "placeholder": "请输入波特率",
+        "description": "请输入波特率",
+        "selections": []
+      },
+      {
+        "id": 3,
+        "key": "RS485_STOP_BIT",
+        "name": "停止位",
+        "label": "停止位",
+        "type": "select",
+        "defaultValue": "1",
+        "placeholder": "请选择停止位",
+        "description": " RS485 停止位 ",
+        "selections": [
+          {
+            "value": 1,
+            "label": "1位"
+          },
+          {
+            "value": 2,
+            "label": "2位"
+          }
+        ]
+      },
+      {
+        "id": 4,
+        "key": "RS485_VERIFY",
+        "name": "校验位",
+        "label": "校验位",
+        "type": "select",
+        "defaultValue": "1",
+        "placeholder": "请选择校验位",
+        "description": " RS485 校验位 ",
+        "selections": [
+          {
+            "value": 1,
+            "label": "无校验"
+          },
+          {
+            "value": 2,
+            "label": "奇校验"
+          },
+          {
+            "value": 3,
+            "label": "偶校验"
+          }
+        ]
+      },
+      {
+        "id": 5,
+        "key": "RS485_DATA_BIT",
+        "name": "数据位",
+        "label": "数据位",
+        "type": "select",
+        "defaultValue": "1",
+        "placeholder": "请选择数据位",
+        "description": " RS485 数据位 ",
+        "selections": [
+          {
+            "value": 1,
+            "label": "5位"
+          },
+          {
+            "value": 2,
+            "label": "6位"
+          },
+          {
+            "value": 3,
+            "label": "7位"
+          },
+          {
+            "value": 4,
+            "label": "8位"
+          }
+        ]
+      }
+    ],
+    "executor": {
+      "id": 1,
+      "key": "RS485_RTU_EXECUTOR",
+      "name": "RS485_RTU_EXECUTOR",
+      "description": "",
+      "properties": [
+
+      ]
+    }
+  }
+]

+ 269 - 0
document/json/gateway_server_protocol.json

@@ -0,0 +1,269 @@
+[
+  {
+    "id": 1,
+    "key": "PROTOCAL_RS485",
+    "name": "RS485 规约 ",
+    "description": " ",
+    "properties": [
+      {
+        "id": 1,
+        "key": "RS485_CLEAR_INTERRUPT",
+        "name": "通信中断数据是否清零",
+        "label": "通信中断数据是否清零",
+        "type": "select",
+        "defaultValue": "",
+        "placeholder": "请选择通信中断数据是否清零",
+        "description": "",
+        "selections": [
+          {
+            "value": 1,
+            "label": "是"
+          },
+          {
+            "value": 2,
+            "label": "否"
+          }
+        ]
+      },
+      {
+        "id": 2,
+        "key": "RS485_SEND_TIME_INTERVAL",
+        "name": "发送时间间隔(ms)",
+        "label": "发送时间间隔(ms)",
+        "type": "double",
+        "defaultValue": "",
+        "description": "",
+        "placeholder": "输入发送时间间隔(ms)",
+        "selections": []
+      },
+      {
+        "id": 3,
+        "key": "RS485_TIME_OUT",
+        "name": "超时时间(ms)",
+        "label": "超时时间(ms)",
+        "type": "double",
+        "defaultValue": "",
+        "description": "",
+        "placeholder": "输入超时时间(ms)",
+        "selections": []
+      },
+      {
+        "id": 4,
+        "key": "RS485_COLON_NEEDED",
+        "name": "是否需要冒号",
+        "label": "是否需要冒号",
+        "type": "select",
+        "defaultValue": "",
+        "description": "",
+        "placeholder": "请选择是否需要冒号",
+        "selections": [
+          {
+            "value": 1,
+            "label": "不需要"
+          },
+          {
+            "value": 2,
+            "label": "需要"
+          }
+        ]
+      },
+      {
+        "id": 5,
+        "key": "RS485_ADDRESS_BIT",
+        "name": "地址字节长度",
+        "label": "地址字节长度",
+        "type": "integer",
+        "defaultValue": "",
+        "description": "",
+        "placeholder": "请输入地址字节长度",
+        "selections": []
+      },
+      {
+        "id": 6,
+        "key": "RS485_ADDRESS_ENDIANSS",
+        "name": "地址字节序",
+        "label": "地址字节序",
+        "type": "select",
+        "defaultValue": "",
+        "description": "",
+        "placeholder": "请选择地址字节序",
+        "selections": [
+          {
+            "value": 1,
+            "label": "前高后低"
+          },
+          {
+            "value": 2,
+            "label": "前低后高"
+          }
+        ]
+      },
+      {
+        "id": 7,
+        "key": "RS485_FUNCTION_BIT",
+        "name": "功能码字节长度",
+        "label": "功能码字节长度",
+        "type": "integer",
+        "defaultValue": "",
+        "description": "",
+        "placeholder": "请输入功能码字节长度",
+        "selections": []
+      },
+      {
+        "id": 8,
+        "key": "RS485_FUNCTION_ENDIANSS",
+        "name": "功能码字节序",
+        "label": "功能码字节序",
+        "type": "select",
+        "defaultValue": "",
+        "description": "",
+        "placeholder": "请选择功能码字节序",
+        "selections": [
+          {
+            "value": 1,
+            "label": "前高后低"
+          },
+          {
+            "value": 2,
+            "label": "前低后高"
+          }
+        ]
+      },
+      {
+        "id": 9,
+        "key": "RS485_VERIFY_ALGORITHM",
+        "name": "校验方式",
+        "label": "校验方式",
+        "type": "select",
+        "defaultValue": "",
+        "description": "",
+        "placeholder": "请选择校验方式",
+        "selections": [
+          {
+            "value": 1,
+            "label": "CRC8校验"
+          },
+          {
+            "value": 2,
+            "label": "CRC16校验"
+          },
+          {
+            "value": 3,
+            "label": "CRC32校验"
+          }
+        ]
+      },
+      {
+        "id": 10,
+        "key": "RS485_VERIFY_BIT",
+        "name": "校验码字节长度",
+        "label": "校验码字节长度",
+        "type": "integer",
+        "defaultValue": "",
+        "description": "",
+        "placeholder": "请输入校验码字节长度",
+        "selections": []
+      },
+      {
+        "id": 11,
+        "key": "RS485_VERIFY_ENDIANSS",
+        "name": "校验码字节序",
+        "label": "校验能码字节序",
+        "type": "select",
+        "defaultValue": "",
+        "description": "",
+        "placeholder": "请选择校验码字节序",
+        "selections": [
+          {
+            "value": 1,
+            "label": "前高后低"
+          },
+          {
+            "value": 2,
+            "label": "前低后高"
+          }
+        ]
+      },
+      {
+        "id": 12,
+        "key": "RS485_RETURN_BIT_ENDIANSS",
+        "name": "返回报文字组装方式",
+        "label": "返回报文字组装方式",
+        "type": "select",
+        "defaultValue": "",
+        "description": "",
+        "placeholder": "请输入返回报文字组装方式",
+        "selections": [
+          {
+            "value": 1,
+            "label": "前高后低"
+          },
+          {
+            "value": 2,
+            "label": "前低后高"
+          }
+        ]
+      },
+      {
+        "id": 13,
+        "key": "RS485_RETURN_BYTE_ENDIANSS",
+        "name": "返回报文字节组装方式",
+        "label": "返回报文字节组装方式",
+        "type": "select",
+        "defaultValue": "",
+        "description": "",
+        "placeholder": "请输入返回报文字节组装方式",
+        "selections": [
+          {
+            "value": 1,
+            "label": "前高后低"
+          },
+          {
+            "value": 2,
+            "label": "前低后高"
+          }
+        ]
+      },
+      {
+        "id": 14,
+        "key": "RS485_RETURN_BYTE",
+        "name": "返回数据字节数",
+        "label": "返回数据字节数",
+        "type": "select",
+        "defaultValue": "",
+        "description": "",
+        "placeholder": "请选择返回数据字节数",
+        "selections": [
+          {
+            "value": 1,
+            "label": "1"
+          },
+          {
+            "value": 2,
+            "label": "2"
+          }
+        ]
+      },
+      {
+        "id": 15,
+        "key": "RS485_NEGATIVE_DISPLAY",
+        "name": "负数显示方式",
+        "label": "负数显示方式",
+        "type": "select",
+        "defaultValue": "",
+        "description": "",
+        "placeholder": "请选择负数显示方式",
+        "selections": [
+          {
+            "value": 1,
+            "label": "补码"
+          },
+          {
+            "value": 2,
+            "label": "原码"
+          }
+        ]
+      }
+    ]
+  }
+]

+ 452 - 0
document/json/gateway_server_protocol.json.backup

@@ -0,0 +1,452 @@
+[
+  {
+    "key": "PROTOCAL-RS-485-RTU",
+    "type": "RS-485-RTU",
+    "communication_id": "1",
+    "name": "RS-485-RTU 规约 123 ",
+    "description": " ",
+    "properties": [
+      {
+        "id": 1,
+        "key": "_CLEAN",
+        "name": "通信中断数据是否清零",
+        "type": "select",
+        "default": 0,
+        "placeholder": "请选择通信中断数据是否清零",
+        "description": "",
+        "selections": [
+          {
+            "value": 0,
+            "name": "9600"
+          },
+          {
+            "value": 1,
+            "name": "19200"
+          }
+        ]
+      },
+      {
+        "id": 2,
+        "name": "发送时间间隔(ms)",
+        "type": "double",
+        "default": 0,
+        "placeholder": "输入发送时间间隔(ms)",
+        "description": "",
+        "selections": []
+      },
+      {
+        "id": 3,
+        "name": "超时时间(ms)",
+        "type": "double",
+        "default": 0,
+        "placeholder": "输入发送时间间隔(ms)",
+        "description": "",
+        "selections": []
+      },
+      {
+        "id": 4,
+        "name": "地址字节长度",
+        "type": "integer",
+        "default": 0,
+        "placeholder": "请输入地址字节长度",
+        "description": "",
+        "selections": []
+      },
+      {
+        "id": 4,
+        "key": "Endianness",
+        "name": "地址字节序",
+        "type": "select",
+        "default": 0,
+        "placeholder": "请选择地址字节序",
+        "description": "",
+        "selections": [
+          {
+            "value": 0,
+            "name": "前高后低"
+          },
+          {
+            "value": 1,
+            "name": "前低后高"
+          }
+        ]
+      },
+      {
+        "id": 5,
+        "name": "功能码字节长度",
+        "type": "integer",
+        "default": 0,
+        "placeholder": "请输入功能码字节长度",
+        "description": "",
+        "selections": []
+      },
+      {
+        "id": 6,
+        "key": "Endianness",
+        "name": "功能码字节序",
+        "type": "select",
+        "default": 0,
+        "placeholder": "请选择功能码字节序",
+        "description": "",
+        "selections": [
+          {
+            "value": 0,
+            "name": "前高后低"
+          },
+          {
+            "value": 1,
+            "name": "前低后高"
+          }
+        ]
+      },
+      {
+        "id": 7,
+        "key": "Endianness",
+        "name": "校验码字节长度",
+        "type": "string",
+        "default": 0,
+        "placeholder": "请输入校验码字节长度",
+        "description": "",
+        "selections": []
+      },
+      {
+        "id": 8,
+        "key": "Endianness",
+        "name": "校验码字节序",
+        "type": "select",
+        "default": 0,
+        "placeholder": "请选择校验码字节序",
+        "description": "",
+        "selections": [
+          {
+            "value": 0,
+            "name": "前高后低"
+          },
+          {
+            "value": 1,
+            "name": "前低后高"
+          }
+        ]
+      },
+      {
+        "id": 9,
+        "key": "Endianness",
+        "name": "校验方式",
+        "type": "select",
+        "default": 0,
+        "placeholder": "请选择校验方式",
+        "description": "",
+        "selections": [
+          {
+            "value": 0,
+            "name": "CRC校验"
+          },
+          {
+            "value": 1,
+            "name": "无校验"
+          }
+        ]
+      }
+    ]
+  },
+  {
+    "key": "PROTOCAL-RS-485-RTU-1",
+    "type": "RS-485-RTU",
+    "communication_id": "1",
+    "name": "RS-485-RTU 规约协议(1)",
+    "description": " ",
+    "properties": [
+      {
+        "id": 1,
+        "key": "_CLEAN",
+        "name": "通信中断数据是否清零",
+        "type": "select",
+        "default": 0,
+        "placeholder": "请选择通信中断数据是否清零",
+        "description": "",
+        "selections": [
+          {
+            "value": 0,
+            "name": "9600"
+          },
+          {
+            "value": 1,
+            "name": "19200"
+          }
+        ]
+      },
+      {
+        "id": 2,
+        "name": "发送时间间隔(ms)",
+        "type": "double",
+        "default": 0,
+        "placeholder": "输入发送时间间隔(ms)",
+        "description": "",
+        "selections": []
+      },
+      {
+        "id": 3,
+        "name": "超时时间(ms)",
+        "type": "double",
+        "default": 0,
+        "placeholder": "输入发送时间间隔(ms)",
+        "description": "",
+        "selections": []
+      },
+      {
+        "id": 4,
+        "name": "地址字节长度",
+        "type": "integer",
+        "default": 0,
+        "placeholder": "请输入地址字节长度",
+        "description": "",
+        "selections": []
+      },
+      {
+        "id": 4,
+        "key": "Endianness",
+        "name": "地址字节序",
+        "type": "select",
+        "default": 0,
+        "placeholder": "请选择地址字节序",
+        "description": "",
+        "selections": [
+          {
+            "value": 0,
+            "name": "前高后低"
+          },
+          {
+            "value": 1,
+            "name": "前低后高"
+          }
+        ]
+      },
+      {
+        "id": 5,
+        "name": "功能码字节长度",
+        "type": "integer",
+        "default": 0,
+        "placeholder": "请输入功能码字节长度",
+        "description": "",
+        "selections": []
+      },
+      {
+        "id": 6,
+        "key": "Endianness",
+        "name": "功能码字节序",
+        "type": "select",
+        "default": 0,
+        "placeholder": "请选择功能码字节序",
+        "description": "",
+        "selections": [
+          {
+            "value": 0,
+            "name": "前高后低"
+          },
+          {
+            "value": 1,
+            "name": "前低后高"
+          }
+        ]
+      },
+      {
+        "id": 7,
+        "key": "Endianness",
+        "name": "校验码字节长度",
+        "type": "string",
+        "default": 0,
+        "placeholder": "请输入校验码字节长度",
+        "description": "",
+        "selections": []
+      },
+      {
+        "id": 8,
+        "key": "Endianness",
+        "name": "校验码字节序",
+        "type": "select",
+        "default": 0,
+        "placeholder": "请选择校验码字节序",
+        "description": "",
+        "selections": [
+          {
+            "value": 0,
+            "name": "前高后低"
+          },
+          {
+            "value": 1,
+            "name": "前低后高"
+          }
+        ]
+      },
+      {
+        "id": 9,
+        "key": "Endianness",
+        "name": "校验方式",
+        "type": "select",
+        "default": 0,
+        "placeholder": "请选择校验方式",
+        "description": "",
+        "selections": [
+          {
+            "value": 0,
+            "name": "CRC校验"
+          },
+          {
+            "value": 1,
+            "name": "无校验"
+          }
+        ]
+      }
+    ]
+  },
+  {
+    "key": "PROTOCAL-RS-485-RTU-2",
+    "type": "RS-485-RTU",
+    "communication_id": "1",
+    "name": "RS-485-RTU 规约协议(2)",
+    "description": " ",
+    "properties": [
+      {
+        "id": 1,
+        "key": "_CLEAN",
+        "name": "通信中断数据是否清零",
+        "type": "select",
+        "default": 0,
+        "placeholder": "请选择通信中断数据是否清零",
+        "description": "",
+        "selections": [
+          {
+            "value": 0,
+            "name": "9600"
+          },
+          {
+            "value": 1,
+            "name": "19200"
+          }
+        ]
+      },
+      {
+        "id": 2,
+        "name": "发送时间间隔(ms)",
+        "type": "double",
+        "default": 0,
+        "placeholder": "输入发送时间间隔(ms)",
+        "description": "",
+        "selections": []
+      },
+      {
+        "id": 3,
+        "name": "超时时间(ms)",
+        "type": "double",
+        "default": 0,
+        "placeholder": "输入发送时间间隔(ms)",
+        "description": "",
+        "selections": []
+      },
+      {
+        "id": 4,
+        "name": "地址字节长度",
+        "type": "integer",
+        "default": 0,
+        "placeholder": "请输入地址字节长度",
+        "description": "",
+        "selections": []
+      },
+      {
+        "id": 4,
+        "key": "Endianness",
+        "name": "地址字节序",
+        "type": "select",
+        "default": 0,
+        "placeholder": "请选择地址字节序",
+        "description": "",
+        "selections": [
+          {
+            "value": 0,
+            "name": "前高后低"
+          },
+          {
+            "value": 1,
+            "name": "前低后高"
+          }
+        ]
+      },
+      {
+        "id": 5,
+        "name": "功能码字节长度",
+        "type": "integer",
+        "default": 0,
+        "placeholder": "请输入功能码字节长度",
+        "description": "",
+        "selections": []
+      },
+      {
+        "id": 6,
+        "key": "Endianness",
+        "name": "功能码字节序",
+        "type": "select",
+        "default": 0,
+        "placeholder": "请选择功能码字节序",
+        "description": "",
+        "selections": [
+          {
+            "value": 0,
+            "name": "前高后低"
+          },
+          {
+            "value": 1,
+            "name": "前低后高"
+          }
+        ]
+      },
+      {
+        "id": 7,
+        "key": "Endianness",
+        "name": "校验码字节长度",
+        "type": "string",
+        "default": 0,
+        "placeholder": "请输入校验码字节长度",
+        "description": "",
+        "selections": []
+      },
+      {
+        "id": 8,
+        "key": "Endianness",
+        "name": "校验码字节序",
+        "type": "select",
+        "default": 0,
+        "placeholder": "请选择校验码字节序",
+        "description": "",
+        "selections": [
+          {
+            "value": 0,
+            "name": "前高后低"
+          },
+          {
+            "value": 1,
+            "name": "前低后高"
+          }
+        ]
+      },
+      {
+        "id": 9,
+        "key": "Endianness",
+        "name": "校验方式",
+        "type": "select",
+        "default": 0,
+        "placeholder": "请选择校验方式",
+        "description": "",
+        "selections": [
+          {
+            "value": 0,
+            "name": "CRC校验"
+          },
+          {
+            "value": 1,
+            "name": "无校验"
+          }
+        ]
+      }
+    ]
+  }
+]

+ 15 - 0
document/markdown/Debug.md

@@ -0,0 +1,15 @@
+
+```
+
+#include "../configuration.h"
+
+ps -ef | grep gateway-server
+
+
+top -pid 54426 ( pid )
+
+
+ps -aux | grep grep gateway-server
+
+
+```

+ 9 - 0
document/markdown/README.md

@@ -0,0 +1,9 @@
+
+
+### run command 
+
+``` shell
+
+cmake CMakeLists.txt && make && ./build/gateway-server
+
+```

+ 72 - 0
document/markdown/Redis.md

@@ -0,0 +1,72 @@
+
+# C client of redis `hiredis`
+## implementation of deque 
+
+```
+#include <stdio.h>
+#include <stdlib.h>
+#include <hiredis/hiredis.h>
+
+int main(void) {
+    // Connect to Redis server
+    redisContext *ctx = redisConnect("127.0.0.1", 6379);
+    if (ctx == NULL || ctx->err) {
+        if (ctx) {
+            printf("Error: %s\n", ctx->errstr);
+            redisFree(ctx);
+        } else {
+            printf("Error: Can't allocate redis context\n");
+        }
+        exit(1);
+    }
+
+    // Push items from top and bottom of the deque
+    redisReply *reply;
+    reply = redisCommand(ctx, "LPUSH mydeque item1"); // Push at the front
+    freeReplyObject(reply);
+    reply = redisCommand(ctx, "RPUSH mydeque item2"); // Push at the back
+    freeReplyObject(reply);
+
+    // Pop items from top and bottom of the deque
+    reply = redisCommand(ctx, "LPOP mydeque"); // Pop from the front
+    if (reply && reply->type == REDIS_REPLY_STRING) {
+        printf("Popped item from the front: %s\n", reply->str);
+    }
+    freeReplyObject(reply);
+
+    reply = redisCommand(ctx, "RPOP mydeque"); // Pop from the back
+    if (reply && reply->type == REDIS_REPLY_STRING) {
+        printf("Popped item from the back: %s\n", reply->str);
+    }
+    freeReplyObject(reply);
+
+    // Free the Redis context
+    redisFree(ctx);
+
+    return 0;
+}
+
+```
+
+
+    /* Set some keys and then read them back.  Once we do that, Redis will deliver
+     * invalidation push messages whenever the key is modified */
+    for (j = 0; j < KEY_COUNT; j++) {
+        reply = redisCommand(c, "SET key:%d initial:%d", j, j);
+        assertReplyAndFree(c, reply, REDIS_REPLY_STATUS);
+
+        reply = redisCommand(c, "GET key:%d", j);
+        assertReplyAndFree(c, reply, REDIS_REPLY_STRING);
+    }
+
+    /* Trigger invalidation messages by updating keys we just read */
+    for (j = 0; j < KEY_COUNT; j++) {
+        printf("            main(): SET key:%d update:%d\n", j, j);
+        reply = redisCommand(c, "SET key:%d update:%d", j, j);
+        assertReplyAndFree(c, reply, REDIS_REPLY_STATUS);
+        printf("            main(): SET REPLY OK\n");
+    }
+
+
+```
+

+ 109 - 0
document/markdown/Remain.md

@@ -0,0 +1,109 @@
+
+```  json
+
+
+[
+    {
+      "id": 7,
+      "key": "Endianness",
+      "name": "遥测功能码",
+      "type": "string",
+      "default": 0,
+      "placeholder": "请输入遥测功能码",
+      "description": "",
+      "selection": []
+    },
+    {
+      "id": 8,
+      "key": "Endianness",
+      "name": "遥信功能码",
+      "type": "string",
+      "default": 0,
+      "placeholder": "请输入遥测功能码",
+      "description": "",
+      "selection": []
+    },
+    {
+      "id": 9,
+      "key": "Endianness",
+      "name": "遥脉功能码",
+      "type": "string",
+      "default": 0,
+      "placeholder": "请输入遥测功能码",
+      "description": "",
+      "selection": []
+    },
+    {
+      "id": 10,
+      "key": "Endianness",
+      "name": "遥控功能码",
+      "type": "string",
+      "default": 0,
+      "placeholder": "请输入遥测功能码",
+      "description": "",
+      "selection": []
+    },
+    {
+      "id": 11,
+      "key": "Endianness",
+      "name": "遥调功能码",
+      "type": "string",
+      "default": 0,
+      "placeholder": "请输入遥调功能码",
+      "description": "",
+      "selection": []
+    },
+]
+
+
+```
+
+```cpp
+
+
+#ifndef _GATEWAY_SERVER_ENTITY_COMMUNICATION_H_
+#define _GATEWAY_SERVER_ENTITY_COMMUNICATION_H_
+
+#include <string>
+
+namespace server {
+
+namespace entity {
+
+enum COMMUNICATION_TYPE_ENUM { RS485 = 0, SWITCH = 1 };
+
+enum BAUDRATE_ENUM {
+  BAUD_1200 = 1200,
+  BAUD_2400 = 2400,
+  BAUD_4800 = 4800,
+  BAUD_9600 = 9600,
+  BAUD_19200 = 19200,
+  BAUD_38400 = 38400,
+  BAUD_57600 = 57600,
+  BAUD_115200 = 115200
+};
+
+enum PARITY_ENUM { NONE = 'N', EVEN = 'E', ODD = 'O' };
+
+class Communication {
+
+  std::string value;
+
+  BAUDRATE_ENUM baudrate;
+
+  PARITY_ENUM parity;
+
+  int32_t data_bits;
+
+  int32_t stop_bits;
+
+};
+
+}  // namespace entity
+
+}  // namespace server
+
+#endif
+
+
+```

+ 72 - 0
document/modbus/ModbusUtils.cpp

@@ -0,0 +1,72 @@
+
+#include "ModbusUtils.h"
+
+#include <unistd.h>
+
+#include <iostream>
+#include <vector>
+
+#include "modbus/modbus.h"
+
+// #define DEVICE_NAME "/dev/ttyUSB0"
+
+// #define DEVICE_NAME "/dev/tty.usbserial-A91UENJO"
+
+#define DEVICE_NAME "/dev/tty.usbserial-FT99NQSV0"
+
+using namespace server::utils;
+
+ModbusUtils::ModbusUtils() {}
+
+ModbusUtils::~ModbusUtils() {}
+
+bool ModbusUtils::connect() {
+
+  context = modbus_new_rtu(DEVICE_NAME, 9600, 'N', 8, 1);
+
+  // modbus_set_response_timeout(modbus_t *ctx, uint32_t to_sec, uint32_t to_usec)
+
+  // modbus_set_indication_timeout(modbus_t *ctx, uint32_t to_sec, uint32_t to_usec)
+
+  // modbus_set_error_recovery(modbus_t *ctx, modbus_error_recovery_mode error_recovery)
+
+  // modbus_set_slave(context, 6);
+
+  // modbus_set_backend();
+
+  if (context == NULL) {
+    std::cout << " unable to create the context" << std::endl;
+    return false;
+  }
+
+  if (modbus_connect(context) == -1) {
+    std::cout << " enter the Connection failed function " << std::endl;
+    std::cout << " Failed to connect " << std::endl;
+    std::cout << "Error: " << modbus_strerror(errno) << std::endl;
+    modbus_close(context);
+    modbus_free(context);
+    return false;
+  }
+
+  return true;
+}
+
+bool ModbusUtils::disconnect() {
+  modbus_close(context);
+  modbus_free(context);
+  return true;
+}
+
+std::vector<uint16_t> ModbusUtils::read() {
+  modbus_set_slave(context, 6);
+  auto list = std::vector<uint16_t>();
+  uint16_t registers[64];
+  int count;
+  count = modbus_read_registers(context, 2, 1, registers);
+  for (auto i = 0; i < count; i++) {
+    // stream << " registers: " << std::oct << registers[i] << " the hex value : " << std::hex << registers[i];
+    auto value = registers[i];
+    list.push_back(value);
+  }
+  return list;
+}

+ 39 - 0
document/modbus/ModbusUtils.h

@@ -0,0 +1,39 @@
+
+#ifndef _GATEWAY_SCHEDULER_MODBUS_UTILS_H_
+#define _GATEWAY_SCHEDULER_MODBUS_UTILS_H_
+
+#include <modbus/modbus.h>
+
+#include <cstdint>
+#include <string>
+#include <vector>
+
+namespace server {
+namespace utils {
+
+class ModbusUtils {
+ public:
+  ModbusUtils();
+
+  ~ModbusUtils();
+
+  bool connect();
+
+  bool disconnect();
+
+  std::vector<uint16_t> read();
+
+ private:
+  std::string device;
+  std::int32_t baudrate;
+  bool parity;
+  std::int32_t dataBits;
+  std::int32_t stopBits;
+
+  modbus_t *context;
+};
+
+}  // namespace utils
+}  // namespace server
+
+#endif

+ 20 - 0
document/request/request.http

@@ -0,0 +1,20 @@
+
+
+# curl -X POST -H "Content-Type: application/json" -d '{"key1": "value1", "key2": "value2"}' http://localhost:8000/api/device/list
+
+
+POST http://127.0.0.1:8888
+Content-Type: application/json
+
+{
+    "printerType": 0,
+    "templateName": "HP3G46S-0B0001",
+    "printerIp": "192.168.168.100",
+    "printerPort": "8050",
+    "payload": {
+        "sn": "this_is_sn_name",
+        "seq": "this_is_seq_sequence"
+    },
+    "fieldOrders": ["sn", "seq"]
+}
+

二进制
library/.DS_Store


+ 2383 - 0
library/include/MQTTAsync.h

@@ -0,0 +1,2383 @@
+/*******************************************************************************
+ * Copyright (c) 2009, 2023 IBM Corp., Ian Craggs and others
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v2.0
+ * and Eclipse Distribution License v1.0 which accompany this distribution.
+ *
+ * The Eclipse Public License is available at
+ *    https://www.eclipse.org/legal/epl-2.0/
+ * and the Eclipse Distribution License is available at
+ *   http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ *    Ian Craggs - initial API and implementation
+ *    Ian Craggs, Allan Stockdill-Mander - SSL connections
+ *    Ian Craggs - multiple server connection support
+ *    Ian Craggs - MQTT 3.1.1 support
+ *    Ian Craggs - fix for bug 444103 - success/failure callbacks not invoked
+ *    Ian Craggs - automatic reconnect and offline buffering (send while disconnected)
+ *    Ian Craggs - binary will message
+ *    Ian Craggs - binary password
+ *    Ian Craggs - remove const on eyecatchers #168
+ *    Ian Craggs - MQTT 5.0
+ *******************************************************************************/
+
+/********************************************************************/
+
+/**
+ * @cond MQTTAsync_main
+ * @mainpage Asynchronous MQTT client library for C (MQTTAsync)
+ *
+ * &copy; Copyright 2009, 2023 IBM Corp., Ian Craggs and others
+ *
+ * @brief An Asynchronous MQTT client library for C.
+ *
+ * An MQTT client application connects to MQTT-capable servers.
+ * A typical client is responsible for collecting information from a telemetry
+ * device and publishing the information to the server. It can also subscribe
+ * to topics, receive messages, and use this information to control the
+ * telemetry device.
+ *
+ * MQTT clients implement the published MQTT v3 protocol. You can write your own
+ * API to the MQTT protocol using the programming language and platform of your
+ * choice. This can be time-consuming and error-prone.
+ *
+ * To simplify writing MQTT client applications, this library encapsulates
+ * the MQTT v3 protocol for you. Using this library enables a fully functional
+ * MQTT client application to be written in a few lines of code.
+ * The information presented here documents the API provided
+ * by the Asynchronous MQTT Client library for C.
+ *
+ * <b>Using the client</b><br>
+ * Applications that use the client library typically use a similar structure:
+ * <ul>
+ * <li>Create a client object</li>
+ * <li>Set the options to connect to an MQTT server</li>
+ * <li>Set up callback functions</li>
+ * <li>Connect the client to an MQTT server</li>
+ * <li>Subscribe to any topics the client needs to receive</li>
+ * <li>Repeat until finished:</li>
+ *     <ul>
+ *     <li>Publish any messages the client needs to</li>
+ *     <li>Handle any incoming messages</li>
+ *     </ul>
+ * <li>Disconnect the client</li>
+ * <li>Free any memory being used by the client</li>
+ * </ul>
+ * Some simple examples are shown here:
+ * <ul>
+ * <li>@ref publish</li>
+ * <li>@ref subscribe</li>
+ * </ul>
+ * Additional information about important concepts is provided here:
+ * <ul>
+ * <li>@ref async</li>
+ * <li>@ref wildcard</li>
+ * <li>@ref qos</li>
+ * <li>@ref tracing</li>
+ * <li>@ref auto_reconnect</li>
+ * <li>@ref offline_publish</li>
+ * </ul>
+ * @endcond
+ */
+
+/*
+/// @cond EXCLUDE
+*/
+#if !defined(MQTTASYNC_H)
+#define MQTTASYNC_H
+
+#if defined(__cplusplus)
+ extern "C" {
+#endif
+
+#include <stdio.h>
+/*
+/// @endcond
+*/
+
+#include "MQTTExportDeclarations.h"
+
+#include "MQTTProperties.h"
+#include "MQTTReasonCodes.h"
+#include "MQTTSubscribeOpts.h"
+#if !defined(NO_PERSISTENCE)
+#include "MQTTClientPersistence.h"
+#endif
+
+/**
+ * Return code: No error. Indicates successful completion of an MQTT client
+ * operation.
+ */
+#define MQTTASYNC_SUCCESS 0
+/**
+ * Return code: A generic error code indicating the failure of an MQTT client
+ * operation.
+ */
+#define MQTTASYNC_FAILURE -1
+
+/* error code -2 is MQTTAsync_PERSISTENCE_ERROR */
+
+#define MQTTASYNC_PERSISTENCE_ERROR -2
+
+/**
+ * Return code: The client is disconnected.
+ */
+#define MQTTASYNC_DISCONNECTED -3
+/**
+ * Return code: The maximum number of messages allowed to be simultaneously
+ * in-flight has been reached.
+ */
+#define MQTTASYNC_MAX_MESSAGES_INFLIGHT -4
+/**
+ * Return code: An invalid UTF-8 string has been detected.
+ */
+#define MQTTASYNC_BAD_UTF8_STRING -5
+/**
+ * Return code: A NULL parameter has been supplied when this is invalid.
+ */
+#define MQTTASYNC_NULL_PARAMETER -6
+/**
+ * Return code: The topic has been truncated (the topic string includes
+ * embedded NULL characters). String functions will not access the full topic.
+ * Use the topic length value to access the full topic.
+ */
+#define MQTTASYNC_TOPICNAME_TRUNCATED -7
+/**
+ * Return code: A structure parameter does not have the correct eyecatcher
+ * and version number.
+ */
+#define MQTTASYNC_BAD_STRUCTURE -8
+/**
+ * Return code: A qos parameter is not 0, 1 or 2
+ */
+#define MQTTASYNC_BAD_QOS -9
+/**
+ * Return code: All 65535 MQTT msgids are being used
+ */
+#define MQTTASYNC_NO_MORE_MSGIDS -10
+/**
+ * Return code: the request is being discarded when not complete
+ */
+#define MQTTASYNC_OPERATION_INCOMPLETE -11
+/**
+ * Return code: no more messages can be buffered
+ */
+#define MQTTASYNC_MAX_BUFFERED_MESSAGES -12
+/**
+ * Return code: Attempting SSL connection using non-SSL version of library
+ */
+#define MQTTASYNC_SSL_NOT_SUPPORTED -13
+/**
+ * Return code: protocol prefix in serverURI should be:
+ * @li @em tcp:// or @em mqtt:// - Insecure TCP
+ * @li @em ssl:// or @em mqtts:// - Encrypted SSL/TLS
+ * @li @em ws:// - Insecure websockets
+ * @li @em wss:// - Secure web sockets
+ *
+ * The TLS enabled prefixes (ssl, mqtts, wss) are only valid if the TLS
+ * version of the library is linked with.
+ */
+#define MQTTASYNC_BAD_PROTOCOL -14
+/**
+ * Return code: don't use options for another version of MQTT
+ */
+#define MQTTASYNC_BAD_MQTT_OPTION -15
+/**
+ * Return code: call not applicable to the client's version of MQTT
+ */
+#define MQTTASYNC_WRONG_MQTT_VERSION -16
+/**
+ *  Return code: 0 length will topic
+ */
+#define MQTTASYNC_0_LEN_WILL_TOPIC -17
+/*
+ * Return code: connect or disconnect command ignored because there is already a connect or disconnect
+ * command at the head of the list waiting to be processed. Use the onSuccess/onFailure callbacks to wait
+ * for the previous connect or disconnect command to be complete.
+ */
+#define MQTTASYNC_COMMAND_IGNORED -18
+ /*
+  * Return code: maxBufferedMessages in the connect options must be >= 0
+  */
+ #define MQTTASYNC_MAX_BUFFERED -19
+
+/**
+ * Default MQTT version to connect with.  Use 3.1.1 then fall back to 3.1
+ */
+#define MQTTVERSION_DEFAULT 0
+/**
+ * MQTT version to connect with: 3.1
+ */
+#define MQTTVERSION_3_1 3
+/**
+ * MQTT version to connect with: 3.1.1
+ */
+#define MQTTVERSION_3_1_1 4
+/**
+ * MQTT version to connect with: 5
+ */
+#define MQTTVERSION_5 5
+/**
+ * Bad return code from subscribe, as defined in the 3.1.1 specification
+ */
+#define MQTT_BAD_SUBSCRIBE 0x80
+
+
+/**
+ *  Initialization options
+ */
+typedef struct
+{
+	/** The eyecatcher for this structure.  Must be MQTG. */
+	char struct_id[4];
+	/** The version number of this structure.  Must be 0 */
+	int struct_version;
+	/** 1 = we do openssl init, 0 = leave it to the application */
+	int do_openssl_init;
+} MQTTAsync_init_options;
+
+#define MQTTAsync_init_options_initializer { {'M', 'Q', 'T', 'G'}, 0, 0 }
+
+/**
+ * Global init of mqtt library. Call once on program start to set global behaviour.
+ * handle_openssl_init - if mqtt library should handle openssl init (1) or rely on the caller to init it before using mqtt (0)
+ */
+LIBMQTT_API void MQTTAsync_global_init(MQTTAsync_init_options* inits);
+
+/**
+ * A handle representing an MQTT client. A valid client handle is available
+ * following a successful call to MQTTAsync_create().
+ */
+typedef void* MQTTAsync;
+/**
+ * A value representing an MQTT message. A token is returned to the
+ * client application when a message is published. The token can then be used to
+ * check that the message was successfully delivered to its destination (see
+ * MQTTAsync_publish(),
+ * MQTTAsync_publishMessage(),
+ * MQTTAsync_deliveryComplete(), and
+ * MQTTAsync_getPendingTokens()).
+ */
+typedef int MQTTAsync_token;
+
+/**
+ * A structure representing the payload and attributes of an MQTT message. The
+ * message topic is not part of this structure (see MQTTAsync_publishMessage(),
+ * MQTTAsync_publish(), MQTTAsync_receive(), MQTTAsync_freeMessage()
+ * and MQTTAsync_messageArrived()).
+ */
+typedef struct
+{
+	/** The eyecatcher for this structure.  must be MQTM. */
+	char struct_id[4];
+	/** The version number of this structure.  Must be 0 or 1.
+	 *  0 indicates no message properties */
+	int struct_version;
+	/** The length of the MQTT message payload in bytes. */
+	int payloadlen;
+	/** A pointer to the payload of the MQTT message. */
+	void* payload;
+	/**
+     * The quality of service (QoS) assigned to the message.
+     * There are three levels of QoS:
+     * <DL>
+     * <DT><B>QoS0</B></DT>
+     * <DD>Fire and forget - the message may not be delivered</DD>
+     * <DT><B>QoS1</B></DT>
+     * <DD>At least once - the message will be delivered, but may be
+     * delivered more than once in some circumstances.</DD>
+     * <DT><B>QoS2</B></DT>
+     * <DD>Once and one only - the message will be delivered exactly once.</DD>
+     * </DL>
+     */
+	int qos;
+	/**
+     * The retained flag serves two purposes depending on whether the message
+     * it is associated with is being published or received.
+     *
+     * <b>retained = true</b><br>
+     * For messages being published, a true setting indicates that the MQTT
+     * server should retain a copy of the message. The message will then be
+     * transmitted to new subscribers to a topic that matches the message topic.
+     * For subscribers registering a new subscription, the flag being true
+     * indicates that the received message is not a new one, but one that has
+     * been retained by the MQTT server.
+     *
+     * <b>retained = false</b> <br>
+     * For publishers, this indicates that this message should not be retained
+     * by the MQTT server. For subscribers, a false setting indicates this is
+     * a normal message, received as a result of it being published to the
+     * server.
+     */
+	int retained;
+	/**
+      * The dup flag indicates whether or not this message is a duplicate.
+      * It is only meaningful when receiving QoS1 messages. When true, the
+      * client application should take appropriate action to deal with the
+      * duplicate message.  This is an output parameter only.
+      */
+	int dup;
+	/** The message identifier is reserved for internal use by the
+      * MQTT client and server.  It is an output parameter only - writing
+      * to it will serve no purpose.  It contains the MQTT message id of
+      * an incoming publish message.
+      */
+	int msgid;
+	/**
+	 * The MQTT V5 properties associated with the message.
+	 */
+	MQTTProperties properties;
+} MQTTAsync_message;
+
+#define MQTTAsync_message_initializer { {'M', 'Q', 'T', 'M'}, 1, 0, NULL, 0, 0, 0, 0, MQTTProperties_initializer }
+
+/**
+ * This is a callback function. The client application
+ * must provide an implementation of this function to enable asynchronous
+ * receipt of messages. The function is registered with the client library by
+ * passing it as an argument to MQTTAsync_setCallbacks(). It is
+ * called by the client library when a new message that matches a client
+ * subscription has been received from the server. This function is executed on
+ * a separate thread to the one on which the client application is running.
+ *
+ * <b>Note:</b> Neither MQTTAsync_create() nor MQTTAsync_destroy() should be
+ * called within this callback.
+ * @param context A pointer to the <i>context</i> value originally passed to
+ * MQTTAsync_setCallbacks(), which contains any application-specific context.
+ * @param topicName The topic associated with the received message.
+ * @param topicLen The length of the topic if there are one
+ * more NULL characters embedded in <i>topicName</i>, otherwise <i>topicLen</i>
+ * is 0. If <i>topicLen</i> is 0, the value returned by <i>strlen(topicName)</i>
+ * can be trusted. If <i>topicLen</i> is greater than 0, the full topic name
+ * can be retrieved by accessing <i>topicName</i> as a byte array of length
+ * <i>topicLen</i>.
+ * @param message The MQTTAsync_message structure for the received message.
+ * This structure contains the message payload and attributes.
+ * @return This function must return 0 or 1 indicating whether or not
+ * the message has been safely received by the client application. <br>
+ * Returning 1 indicates that the message has been successfully handled.
+ * To free the message storage, ::MQTTAsync_freeMessage must be called.
+ * To free the topic name storage, ::MQTTAsync_free must be called.<br>
+ * Returning 0 indicates that there was a problem. In this
+ * case, the client library will reinvoke MQTTAsync_messageArrived() to
+ * attempt to deliver the message to the application again.
+ * Do not free the message and topic storage when returning 0, otherwise
+ * the redelivery will fail.
+ */
+typedef int MQTTAsync_messageArrived(void* context, char* topicName, int topicLen, MQTTAsync_message* message);
+
+/**
+ * This is a callback function. The client application
+ * must provide an implementation of this function to enable asynchronous
+ * notification of delivery of messages to the server. The function is
+ * registered with the client library by passing it as an argument to MQTTAsync_setCallbacks().
+ * It is called by the client library after the client application has
+ * published a message to the server. It indicates that the necessary
+ * handshaking and acknowledgements for the requested quality of service (see
+ * MQTTAsync_message.qos) have been completed. This function is executed on a
+ * separate thread to the one on which the client application is running.
+ *
+ * <b>Note:</b> Neither MQTTAsync_create() nor MQTTAsync_destroy() should be
+ * called within this callback.
+ * @param context A pointer to the <i>context</i> value originally passed to
+ * MQTTAsync_setCallbacks(), which contains any application-specific context.
+ * @param token The ::MQTTAsync_token associated with
+ * the published message. Applications can check that all messages have been
+ * correctly published by matching the tokens returned from calls to
+ * MQTTAsync_send() and MQTTAsync_sendMessage() with the tokens passed
+ * to this callback.
+ */
+typedef void MQTTAsync_deliveryComplete(void* context, MQTTAsync_token token);
+
+/**
+ * This is a callback function. The client application
+ * must provide an implementation of this function to enable asynchronous
+ * notification of the loss of connection to the server. The function is
+ * registered with the client library by passing it as an argument to
+ * MQTTAsync_setCallbacks(). It is called by the client library if the client
+ * loses its connection to the server. The client application must take
+ * appropriate action, such as trying to reconnect or reporting the problem.
+ * This function is executed on a separate thread to the one on which the
+ * client application is running.
+ *
+ * <b>Note:</b> Neither MQTTAsync_create() nor MQTTAsync_destroy() should be
+ * called within this callback.
+ * @param context A pointer to the <i>context</i> value originally passed to
+ * MQTTAsync_setCallbacks(), which contains any application-specific context.
+ * @param cause The reason for the disconnection.
+ * Currently, <i>cause</i> is always set to NULL.
+ */
+typedef void MQTTAsync_connectionLost(void* context, char* cause);
+
+
+/**
+ * This is a callback function, which will be called when the client
+ * library successfully connects.  This is superfluous when the connection
+ * is made in response to a MQTTAsync_connect call, because the onSuccess
+ * callback can be used.  It is intended for use when automatic reconnect
+ * is enabled, so that when a reconnection attempt succeeds in the background,
+ * the application is notified and can take any required actions.
+ *
+ * <b>Note:</b> Neither MQTTAsync_create() nor MQTTAsync_destroy() should be
+ * called within this callback.
+ * @param context A pointer to the <i>context</i> value originally passed to
+ * MQTTAsync_setCallbacks(), which contains any application-specific context.
+ * @param cause The reason for the disconnection.
+ * Currently, <i>cause</i> is always set to NULL.
+ */
+typedef void MQTTAsync_connected(void* context, char* cause);
+
+/**
+ * This is a callback function, which will be called when the client
+ * library receives a disconnect packet from the server. This applies to MQTT V5 and above only.
+ *
+ * <b>Note:</b> Neither MQTTAsync_create() nor MQTTAsync_destroy() should be
+ * called within this callback.
+ * @param context A pointer to the <i>context</i> value originally passed to
+ * MQTTAsync_setCallbacks(), which contains any application-specific context.
+ * @param properties the properties in the disconnect packet.
+ * @param properties the reason code from the disconnect packet
+ * Currently, <i>cause</i> is always set to NULL.
+ */
+typedef void MQTTAsync_disconnected(void* context, MQTTProperties* properties,
+		enum MQTTReasonCodes reasonCode);
+
+/**
+ * Sets the MQTTAsync_disconnected() callback function for a client.
+ * @param handle A valid client handle from a successful call to
+ * MQTTAsync_create().
+ *
+ * <b>Note:</b> Neither MQTTAsync_create() nor MQTTAsync_destroy() should be
+ * called within this callback.
+ * @param context A pointer to any application-specific context. The
+ * the <i>context</i> pointer is passed to each of the callback functions to
+ * provide access to the context information in the callback.
+ * @param co A pointer to an MQTTAsync_connected() callback
+ * function.  NULL removes the callback setting.
+ * @return ::MQTTASYNC_SUCCESS if the callbacks were correctly set,
+ * ::MQTTASYNC_FAILURE if an error occurred.
+ */
+LIBMQTT_API int MQTTAsync_setDisconnected(MQTTAsync handle, void* context, MQTTAsync_disconnected* co);
+
+/** The connect options that can be updated before an automatic reconnect. */
+typedef struct
+{
+	/** The eyecatcher for this structure.  Will be MQCD. */
+	char struct_id[4];
+	/** The version number of this structure.  Will be 0 */
+	int struct_version;
+	/**
+	 * MQTT servers that support the MQTT v3.1 protocol provide authentication
+	 * and authorisation by user name and password. This is the user name parameter.
+	 * Set data to NULL to remove.  To change, allocate new
+	 * storage with ::MQTTAsync_allocate - this will then be free later by the library.
+	 */
+	const char* username;
+	/**
+	 * The password parameter of the MQTT authentication.
+	 * Set data to NULL to remove.  To change, allocate new
+	 * storage with ::MQTTAsync_allocate - this will then be free later by the library.
+	 */
+	struct {
+		int len;           /**< binary password length */
+		const void* data;  /**< binary password data */
+	} binarypwd;
+} MQTTAsync_connectData;
+
+#define MQTTAsync_connectData_initializer {{'M', 'Q', 'C', 'D'}, 0, NULL, {0, NULL}}
+
+/**
+ * This is a callback function which will allow the client application to update the 
+ * connection data.
+ * @param data The connection data which can be modified by the application.
+ * @return Return a non-zero value to update the connect data, zero to keep the same data.
+ */
+typedef int MQTTAsync_updateConnectOptions(void* context, MQTTAsync_connectData* data);
+
+/**
+ * Sets the MQTTAsync_updateConnectOptions() callback function for a client.
+ * @param handle A valid client handle from a successful call to MQTTAsync_create().
+ * @param context A pointer to any application-specific context. The
+ * the <i>context</i> pointer is passed to each of the callback functions to
+ * provide access to the context information in the callback.
+ * @param co A pointer to an MQTTAsync_updateConnectOptions() callback
+ * function.  NULL removes the callback setting.
+ */
+LIBMQTT_API int MQTTAsync_setUpdateConnectOptions(MQTTAsync handle, void* context, MQTTAsync_updateConnectOptions* co);
+
+/**
+ * Sets the MQTTPersistence_beforeWrite() callback function for a client.
+ * @param handle A valid client handle from a successful call to MQTTAsync_create().
+ * @param context A pointer to any application-specific context. The
+ * the <i>context</i> pointer is passed to the callback function to
+ * provide access to the context information in the callback.
+ * @param co A pointer to an MQTTPersistence_beforeWrite() callback
+ * function.  NULL removes the callback setting.
+ */
+LIBMQTT_API int MQTTAsync_setBeforePersistenceWrite(MQTTAsync handle, void* context, MQTTPersistence_beforeWrite* co);
+
+
+/**
+ * Sets the MQTTPersistence_afterRead() callback function for a client.
+ * @param handle A valid client handle from a successful call to MQTTAsync_create().
+ * @param context A pointer to any application-specific context. The
+ * the <i>context</i> pointer is passed to the callback function to
+ * provide access to the context information in the callback.
+ * @param co A pointer to an MQTTPersistence_beforeWrite() callback
+ * function.  NULL removes the callback setting.
+ */
+LIBMQTT_API int MQTTAsync_setAfterPersistenceRead(MQTTAsync handle, void* context, MQTTPersistence_afterRead* co);
+
+
+/** The data returned on completion of an unsuccessful API call in the response callback onFailure. */
+typedef struct
+{
+	/** A token identifying the failed request. */
+	MQTTAsync_token token;
+	/** A numeric code identifying the error. */
+	int code;
+	/** Optional text explaining the error. Can be NULL. */
+	const char *message;
+} MQTTAsync_failureData;
+
+
+/** The data returned on completion of an unsuccessful API call in the response callback onFailure. */
+typedef struct
+{
+	/** The eyecatcher for this structure.  Will be MQFD. */
+	char struct_id[4];
+	/** The version number of this structure.  Will be 0 */
+	int struct_version;
+	/** A token identifying the failed request. */
+	MQTTAsync_token token;
+	/** The MQTT reason code returned. */
+	enum MQTTReasonCodes reasonCode;
+	/** The MQTT properties on the ack, if any. */
+	MQTTProperties properties;
+	/** A numeric code identifying the MQTT client library error. */
+	int code;
+	/** Optional further text explaining the error. Can be NULL. */
+	const char *message;
+	/** Packet type on which the failure occurred - used for publish QoS 1/2 exchanges*/
+	int packet_type;
+} MQTTAsync_failureData5;
+
+#define MQTTAsync_failureData5_initializer {{'M', 'Q', 'F', 'D'}, 0, 0, MQTTREASONCODE_SUCCESS, MQTTProperties_initializer, 0, NULL, 0}
+
+/** The data returned on completion of a successful API call in the response callback onSuccess. */
+typedef struct
+{
+	/** A token identifying the successful request. Can be used to refer to the request later. */
+	MQTTAsync_token token;
+	/** A union of the different values that can be returned for subscribe, unsubscribe and publish. */
+	union
+	{
+		/** For subscribe, the granted QoS of the subscription returned by the server.
+		 * Also for subscribeMany, if only 1 subscription was requested. */
+		int qos;
+		/** For subscribeMany, if more than one subscription was requested,
+		 * the list of granted QoSs of the subscriptions returned by the server. */
+		int* qosList;
+		/** For publish, the message being sent to the server. */
+		struct
+		{
+			MQTTAsync_message message; /**< the message being sent to the server */
+			char* destinationName;     /**< the topic destination for the message */
+		} pub;
+		/* For connect, the server connected to, MQTT version used, and sessionPresent flag */
+		struct
+		{
+			char* serverURI; /**< the connection string of the server */
+			int MQTTVersion; /**< the version of MQTT being used */
+			int sessionPresent; /**< the session present flag returned from the server */
+		} connect;
+	} alt;
+} MQTTAsync_successData;
+
+
+/** The data returned on completion of a successful API call in the response callback onSuccess. */
+typedef struct
+{
+	char struct_id[4];    	/**< The eyecatcher for this structure.  Will be MQSD. */
+	int struct_version;  	/**< The version number of this structure.  Will be 0 */
+	/** A token identifying the successful request. Can be used to refer to the request later. */
+	MQTTAsync_token token;
+	enum MQTTReasonCodes reasonCode;  	/**< MQTT V5 reason code returned */
+	MQTTProperties properties;  	        /**< MQTT V5 properties returned, if any */
+	/** A union of the different values that can be returned for subscribe, unsubscribe and publish. */
+	union
+	{
+		/** For subscribeMany, the list of reasonCodes returned by the server. */
+		struct
+		{
+			int reasonCodeCount; /**< the number of reason codes in the reasonCodes array */
+			enum MQTTReasonCodes* reasonCodes; /**< an array of reasonCodes */
+		} sub;
+		/** For publish, the message being sent to the server. */
+		struct
+		{
+			MQTTAsync_message message; /**< the message being sent to the server */
+			char* destinationName;     /**< the topic destination for the message */
+		} pub;
+		/* For connect, the server connected to, MQTT version used, and sessionPresent flag */
+		struct
+		{
+			char* serverURI;  /**< the connection string of the server */
+			int MQTTVersion;  /**< the version of MQTT being used */
+			int sessionPresent;  /**< the session present flag returned from the server */
+		} connect;
+		/** For unsubscribeMany, the list of reasonCodes returned by the server. */
+		struct
+		{
+			int reasonCodeCount; /**< the number of reason codes in the reasonCodes array */
+			enum MQTTReasonCodes* reasonCodes; /**< an array of reasonCodes */
+		} unsub;
+	} alt;
+} MQTTAsync_successData5;
+
+#define MQTTAsync_successData5_initializer {{'M', 'Q', 'S', 'D'}, 0, 0, MQTTREASONCODE_SUCCESS, MQTTProperties_initializer, {.sub={0,0}}}
+
+/**
+ * This is a callback function. The client application
+ * must provide an implementation of this function to enable asynchronous
+ * notification of the successful completion of an API call. The function is
+ * registered with the client library by passing it as an argument in
+ * ::MQTTAsync_responseOptions.
+ *
+ * <b>Note:</b> Neither MQTTAsync_create() nor MQTTAsync_destroy() should be
+ * called within this callback.
+ * @param context A pointer to the <i>context</i> value originally passed to
+ * ::MQTTAsync_responseOptions, which contains any application-specific context.
+ * @param response Any success data associated with the API completion.
+ */
+typedef void MQTTAsync_onSuccess(void* context, MQTTAsync_successData* response);
+
+/**
+ * This is a callback function, the MQTT V5 version of ::MQTTAsync_onSuccess.
+ * The client application
+ * must provide an implementation of this function to enable asynchronous
+ * notification of the successful completion of an API call. The function is
+ * registered with the client library by passing it as an argument in
+ * ::MQTTAsync_responseOptions.
+ *
+ * <b>Note:</b> Neither MQTTAsync_create() nor MQTTAsync_destroy() should be
+ * called within this callback.
+ * @param context A pointer to the <i>context</i> value originally passed to
+ * ::MQTTAsync_responseOptions, which contains any application-specific context.
+ * @param response Any success data associated with the API completion.
+ */
+typedef void MQTTAsync_onSuccess5(void* context, MQTTAsync_successData5* response);
+
+/**
+ * This is a callback function. The client application
+ * must provide an implementation of this function to enable asynchronous
+ * notification of the unsuccessful completion of an API call. The function is
+ * registered with the client library by passing it as an argument in
+ * ::MQTTAsync_responseOptions.
+ *
+ * <b>Note:</b> Neither MQTTAsync_create() nor MQTTAsync_destroy() should be
+ * called within this callback.
+ * @param context A pointer to the <i>context</i> value originally passed to
+ * ::MQTTAsync_responseOptions, which contains any application-specific context.
+ * @param response Failure data associated with the API completion.
+ */
+typedef void MQTTAsync_onFailure(void* context,  MQTTAsync_failureData* response);
+
+/**
+ * This is a callback function, the MQTT V5 version of ::MQTTAsync_onFailure.
+ * The application must provide an implementation of this function to enable asynchronous
+ * notification of the unsuccessful completion of an API call. The function is
+ * registered with the client library by passing it as an argument in
+ * ::MQTTAsync_responseOptions.
+ *
+ * <b>Note:</b> Neither MQTTAsync_create() nor MQTTAsync_destroy() should be
+ * called within this callback.
+ * @param context A pointer to the <i>context</i> value originally passed to
+ * ::MQTTAsync_responseOptions, which contains any application-specific context.
+ * @param response Failure data associated with the API completion.
+ */
+typedef void MQTTAsync_onFailure5(void* context,  MQTTAsync_failureData5* response);
+
+/** Structure to define call options.  For MQTT 5.0 there is input data as well as that
+ * describing the response method.  So there is now also a synonym ::MQTTAsync_callOptions
+ * to better reflect the use.  This responseOptions name is kept for backward
+ * compatibility.
+ */
+typedef struct MQTTAsync_responseOptions
+{
+	/** The eyecatcher for this structure.  Must be MQTR */
+	char struct_id[4];
+	/** The version number of this structure.  Must be 0 or 1
+	 *   if 0, no MQTTV5 options */
+	int struct_version;
+	/**
+    * A pointer to a callback function to be called if the API call successfully
+    * completes.  Can be set to NULL, in which case no indication of successful
+    * completion will be received.
+    */
+	MQTTAsync_onSuccess* onSuccess;
+	/**
+    * A pointer to a callback function to be called if the API call fails.
+    * Can be set to NULL, in which case no indication of unsuccessful
+    * completion will be received.
+    */
+	MQTTAsync_onFailure* onFailure;
+	/**
+    * A pointer to any application-specific context. The
+    * the <i>context</i> pointer is passed to success or failure callback functions to
+    * provide access to the context information in the callback.
+    */
+	void* context;
+	/**
+    * A token is returned from the call.  It can be used to track
+    * the state of this request, both in the callbacks and in future calls
+    * such as ::MQTTAsync_waitForCompletion. This is output only - any
+    * change by the application will be ignored.
+    */
+	MQTTAsync_token token;
+	/**
+    * A pointer to a callback function to be called if the API call successfully
+    * completes.  Can be set to NULL, in which case no indication of successful
+    * completion will be received.
+    */
+	MQTTAsync_onSuccess5* onSuccess5;
+	/**
+    * A pointer to a callback function to be called if the API call successfully
+    * completes.  Can be set to NULL, in which case no indication of successful
+    * completion will be received.
+    */
+	MQTTAsync_onFailure5* onFailure5;
+	/**
+	 * MQTT V5 input properties
+	 */
+	MQTTProperties properties;
+	/*
+	 * MQTT V5 subscribe options, when used with subscribe only.
+	 */
+	MQTTSubscribe_options subscribeOptions;
+	/*
+	 * MQTT V5 subscribe option count, when used with subscribeMany only.
+	 * The number of entries in the subscribe_options_list array.
+	 */
+	int subscribeOptionsCount;
+	/*
+	 * MQTT V5 subscribe option array, when used with subscribeMany only.
+	 */
+	MQTTSubscribe_options* subscribeOptionsList;
+} MQTTAsync_responseOptions;
+
+#define MQTTAsync_responseOptions_initializer { {'M', 'Q', 'T', 'R'}, 1, NULL, NULL, 0, 0, NULL, NULL, MQTTProperties_initializer, MQTTSubscribe_options_initializer, 0, NULL}
+
+/** A synonym for responseOptions to better reflect its usage since MQTT 5.0 */
+typedef struct MQTTAsync_responseOptions MQTTAsync_callOptions;
+#define MQTTAsync_callOptions_initializer MQTTAsync_responseOptions_initializer
+
+/**
+ * This function sets the global callback functions for a specific client.
+ * If your client application doesn't use a particular callback, set the
+ * relevant parameter to NULL. Any necessary message acknowledgements and
+ * status communications are handled in the background without any intervention
+ * from the client application.  If you do not set a messageArrived callback
+ * function, you will not be notified of the receipt of any messages as a
+ * result of a subscription.
+ *
+ * <b>Note:</b> The MQTT client must be disconnected when this function is
+ * called.
+ * @param handle A valid client handle from a successful call to
+ * MQTTAsync_create().
+ * @param context A pointer to any application-specific context. The
+ * the <i>context</i> pointer is passed to each of the callback functions to
+ * provide access to the context information in the callback.
+ * @param cl A pointer to an MQTTAsync_connectionLost() callback
+ * function. You can set this to NULL if your application doesn't handle
+ * disconnections.
+ * @param ma A pointer to an MQTTAsync_messageArrived() callback
+ * function.  If this callback is not set, an error will be returned.
+ * You must set this callback because otherwise there would be
+ * no way to deliver any incoming messages.
+ * @param dc A pointer to an MQTTAsync_deliveryComplete() callback
+ * function. You can set this to NULL if you do not want to check
+ * for successful delivery.
+ * @return ::MQTTASYNC_SUCCESS if the callbacks were correctly set,
+ * ::MQTTASYNC_FAILURE if an error occurred.
+ */
+LIBMQTT_API int MQTTAsync_setCallbacks(MQTTAsync handle, void* context, MQTTAsync_connectionLost* cl,
+									 MQTTAsync_messageArrived* ma, MQTTAsync_deliveryComplete* dc);
+
+/**
+ * This function sets the callback function for a connection lost event for
+ * a specific client. Any necessary message acknowledgements and status
+ * communications are handled in the background without any intervention
+ * from the client application.
+ *
+ * <b>Note:</b> The MQTT client must be disconnected when this function is
+ * called.
+ * @param handle A valid client handle from a successful call to
+ * MQTTAsync_create().
+ * @param context A pointer to any application-specific context. The
+ * the <i>context</i> pointer is passed the callback functions to provide
+ * access to the context information in the callback.
+ * @param cl A pointer to an MQTTAsync_connectionLost() callback
+ * function. You can set this to NULL if your application doesn't handle
+ * disconnections.
+ * @return ::MQTTASYNC_SUCCESS if the callbacks were correctly set,
+ * ::MQTTASYNC_FAILURE if an error occurred.
+ */
+
+LIBMQTT_API int MQTTAsync_setConnectionLostCallback(MQTTAsync handle, void* context,
+												  MQTTAsync_connectionLost* cl);
+
+/**
+ * This function sets the callback function for a message arrived event for
+ * a specific client. Any necessary message acknowledgements and status
+ * communications are handled in the background without any intervention
+ * from the client application.  If you do not set a messageArrived callback
+ * function, you will not be notified of the receipt of any messages as a
+ * result of a subscription.
+ *
+ * <b>Note:</b> The MQTT client must be disconnected when this function is
+ * called.
+ * @param handle A valid client handle from a successful call to
+ * MQTTAsync_create().
+ * @param context A pointer to any application-specific context. The
+ * the <i>context</i> pointer is passed to the callback functions to provide
+ * access to the context information in the callback.
+ * @param ma A pointer to an MQTTAsync_messageArrived() callback
+ * function.  You can set this to NULL if your application doesn't handle
+ * receipt of messages.
+ * @return ::MQTTASYNC_SUCCESS if the callbacks were correctly set,
+ * ::MQTTASYNC_FAILURE if an error occurred.
+ */
+LIBMQTT_API int MQTTAsync_setMessageArrivedCallback(MQTTAsync handle, void* context,
+												  MQTTAsync_messageArrived* ma);
+
+/**
+ * This function sets the callback function for a delivery complete event
+ * for a specific client. Any necessary message acknowledgements and status
+ * communications are handled in the background without any intervention
+ * from the client application.
+ *
+ * <b>Note:</b> The MQTT client must be disconnected when this function is
+ * called.
+ * @param handle A valid client handle from a successful call to
+ * MQTTAsync_create().
+ * @param context A pointer to any application-specific context. The
+ * the <i>context</i> pointer is passed to the callback functions to provide
+ * access to the context information in the callback.
+ * @param dc A pointer to an MQTTAsync_deliveryComplete() callback
+ * function. You can set this to NULL if you do not want to check
+ * for successful delivery.
+ * @return ::MQTTASYNC_SUCCESS if the callbacks were correctly set,
+ * ::MQTTASYNC_FAILURE if an error occurred.
+ */
+LIBMQTT_API int MQTTAsync_setDeliveryCompleteCallback(MQTTAsync handle, void* context,
+													MQTTAsync_deliveryComplete* dc);
+
+/**
+ * Sets the MQTTAsync_connected() callback function for a client.
+ * @param handle A valid client handle from a successful call to
+ * MQTTAsync_create().
+ * @param context A pointer to any application-specific context. The
+ * the <i>context</i> pointer is passed to each of the callback functions to
+ * provide access to the context information in the callback.
+ * @param co A pointer to an MQTTAsync_connected() callback
+ * function.  NULL removes the callback setting.
+ * @return ::MQTTASYNC_SUCCESS if the callbacks were correctly set,
+ * ::MQTTASYNC_FAILURE if an error occurred.
+ */
+LIBMQTT_API int MQTTAsync_setConnected(MQTTAsync handle, void* context, MQTTAsync_connected* co);
+
+
+/**
+ * Reconnects a client with the previously used connect options.  Connect
+ * must have previously been called for this to work.
+ * @param handle A valid client handle from a successful call to
+ * MQTTAsync_create().
+ * @return ::MQTTASYNC_SUCCESS if the callbacks were correctly set,
+ * ::MQTTASYNC_FAILURE if an error occurred.
+ */
+LIBMQTT_API int MQTTAsync_reconnect(MQTTAsync handle);
+
+
+/**
+ * This function creates an MQTT client ready for connection to the
+ * specified server and using the specified persistent storage (see
+ * MQTTAsync_persistence). See also MQTTAsync_destroy().
+ * @param handle A pointer to an ::MQTTAsync handle. The handle is
+ * populated with a valid client reference following a successful return from
+ * this function.
+ * @param serverURI A null-terminated string specifying the server to
+ * which the client will connect. It takes the form
+ * <i>protocol://host:port</i> where <i>protocol</i> must be:
+ * <br>
+ * @em tcp:// or @em mqtt:// - Insecure TCP
+ * <br>
+ * @em ssl:// or @em mqtts:// - Encrypted SSL/TLS
+ * <br>
+ * @em ws:// - Insecure websockets
+ * <br>
+ * @em wss:// - Secure web sockets
+ * <br>
+ * The TLS enabled prefixes (ssl, mqtts, wss) are only valid if a TLS
+ * version of the library is linked with.
+ * For <i>host</i>, you can specify either an IP address or a host name. For
+ * instance, to connect to a server running on the local machines with the
+ * default MQTT port, specify <i>tcp://localhost:1883</i>.
+ * @param clientId The client identifier passed to the server when the
+ * client connects to it. It is a null-terminated UTF-8 encoded string.
+ * @param persistence_type The type of persistence to be used by the client:
+ * <br>
+ * ::MQTTCLIENT_PERSISTENCE_NONE: Use in-memory persistence. If the device or
+ * system on which the client is running fails or is switched off, the current
+ * state of any in-flight messages is lost and some messages may not be
+ * delivered even at QoS1 and QoS2.
+ * <br>
+ * ::MQTTCLIENT_PERSISTENCE_DEFAULT: Use the default (file system-based)
+ * persistence mechanism. Status about in-flight messages is held in persistent
+ * storage and provides some protection against message loss in the case of
+ * unexpected failure.
+ * <br>
+ * ::MQTTCLIENT_PERSISTENCE_USER: Use an application-specific persistence
+ * implementation. Using this type of persistence gives control of the
+ * persistence mechanism to the application. The application has to implement
+ * the MQTTClient_persistence interface.
+ * @param persistence_context If the application uses
+ * ::MQTTCLIENT_PERSISTENCE_NONE persistence, this argument is unused and should
+ * be set to NULL. For ::MQTTCLIENT_PERSISTENCE_DEFAULT persistence, it
+ * should be set to the location of the persistence directory (if set
+ * to NULL, the persistence directory used is the working directory).
+ * Applications that use ::MQTTCLIENT_PERSISTENCE_USER persistence set this
+ * argument to point to a valid MQTTClient_persistence structure.
+ * @return ::MQTTASYNC_SUCCESS if the client is successfully created, otherwise
+ * an error code is returned.
+ */
+LIBMQTT_API int MQTTAsync_create(MQTTAsync* handle, const char* serverURI, const char* clientId,
+		int persistence_type, void* persistence_context);
+
+/** Options for the ::MQTTAsync_createWithOptions call */
+typedef struct
+{
+	/** The eyecatcher for this structure.  must be MQCO. */
+	char struct_id[4];
+	/** The version number of this structure.  Must be 0, 1, 2 or 3
+	 * 0 means no MQTTVersion
+	 * 1 means no allowDisconnectedSendAtAnyTime, deleteOldestMessages, restoreMessages
+	 * 2 means no persistQoS0
+	 */
+	int struct_version;
+	/** Whether to allow messages to be sent when the client library is not connected. */
+	int sendWhileDisconnected;
+	/** The maximum number of messages allowed to be buffered. This is intended to be used to
+	 * limit the number of messages queued while the client is not connected. It also applies
+	 * when the client is connected, however, so has to be greater than 0. */
+	int maxBufferedMessages;
+	/** Whether the MQTT version is 3.1, 3.1.1, or 5.  To use V5, this must be set.
+	 *  MQTT V5 has to be chosen here, because during the create call the message persistence
+	 *  is initialized, and we want to know whether the format of any persisted messages
+	 *  is appropriate for the MQTT version we are going to connect with.  Selecting 3.1 or
+	 *  3.1.1 and attempting to read 5.0 persisted messages will result in an error on create.  */
+	int MQTTVersion;
+	/**
+	 * Allow sending of messages while disconnected before a first successful connect.
+	 */
+	int allowDisconnectedSendAtAnyTime;
+	/*
+	 * When the maximum number of buffered messages is reached, delete the oldest rather than the newest.
+	 */
+	int deleteOldestMessages;
+	/*
+	 * Restore messages from persistence on create - or clear it.
+	 */
+	int restoreMessages;
+	/*
+	 * Persist QoS0 publish commands - an option to not persist them.
+	 */
+	int persistQoS0;
+} MQTTAsync_createOptions;
+
+#define MQTTAsync_createOptions_initializer  { {'M', 'Q', 'C', 'O'}, 2, 0, 100, MQTTVERSION_DEFAULT, 0, 0, 1, 1}
+
+#define MQTTAsync_createOptions_initializer5 { {'M', 'Q', 'C', 'O'}, 2, 0, 100, MQTTVERSION_5, 0, 0, 1, 1}
+
+
+LIBMQTT_API int MQTTAsync_createWithOptions(MQTTAsync* handle, const char* serverURI, const char* clientId,
+		int persistence_type, void* persistence_context, MQTTAsync_createOptions* options);
+
+/**
+ * MQTTAsync_willOptions defines the MQTT "Last Will and Testament" (LWT) settings for
+ * the client. In the event that a client unexpectedly loses its connection to
+ * the server, the server publishes the LWT message to the LWT topic on
+ * behalf of the client. This allows other clients (subscribed to the LWT topic)
+ * to be made aware that the client has disconnected. To enable the LWT
+ * function for a specific client, a valid pointer to an MQTTAsync_willOptions
+ * structure is passed in the MQTTAsync_connectOptions structure used in the
+ * MQTTAsync_connect() call that connects the client to the server. The pointer
+ * to MQTTAsync_willOptions can be set to NULL if the LWT function is not
+ * required.
+ */
+typedef struct
+{
+	/** The eyecatcher for this structure.  must be MQTW. */
+	char struct_id[4];
+	/** The version number of this structure.  Must be 0 or 1
+	    0 indicates no binary will message support
+	 */
+	int struct_version;
+	/** The LWT topic to which the LWT message will be published. */
+	const char* topicName;
+	/** The LWT payload. */
+	const char* message;
+	/**
+      * The retained flag for the LWT message (see MQTTAsync_message.retained).
+      */
+	int retained;
+	/**
+      * The quality of service setting for the LWT message (see
+      * MQTTAsync_message.qos and @ref qos).
+      */
+	int qos;
+	/** The LWT payload in binary form. This is only checked and used if the message option is NULL */
+	struct
+	{
+  	int len;            /**< binary payload length */
+		const void* data;  /**< binary payload data */
+	} payload;
+} MQTTAsync_willOptions;
+
+#define MQTTAsync_willOptions_initializer { {'M', 'Q', 'T', 'W'}, 1, NULL, NULL, 0, 0, { 0, NULL } }
+
+#define MQTT_SSL_VERSION_DEFAULT 0
+#define MQTT_SSL_VERSION_TLS_1_0 1
+#define MQTT_SSL_VERSION_TLS_1_1 2
+#define MQTT_SSL_VERSION_TLS_1_2 3
+
+/**
+* MQTTAsync_sslProperties defines the settings to establish an SSL/TLS connection using the
+* OpenSSL library. It covers the following scenarios:
+* - Server authentication: The client needs the digital certificate of the server. It is included
+*   in a store containting trusted material (also known as "trust store").
+* - Mutual authentication: Both client and server are authenticated during the SSL handshake. In
+*   addition to the digital certificate of the server in a trust store, the client will need its own
+*   digital certificate and the private key used to sign its digital certificate stored in a "key store".
+* - Anonymous connection: Both client and server do not get authenticated and no credentials are needed
+*   to establish an SSL connection. Note that this scenario is not fully secure since it is subject to
+*   man-in-the-middle attacks.
+*/
+typedef struct
+{
+	/** The eyecatcher for this structure.  Must be MQTS */
+	char struct_id[4];
+
+	/** The version number of this structure. Must be 0, 1, 2, 3, 4 or 5.
+	 * 0 means no sslVersion
+	 * 1 means no verify, CApath
+	 * 2 means no ssl_error_context, ssl_error_cb
+	 * 3 means no ssl_psk_cb, ssl_psk_context, disableDefaultTrustStore
+	 * 4 means no protos, protos_len
+	 */
+	int struct_version;
+
+	/** The file in PEM format containing the public digital certificates trusted by the client. */
+	const char* trustStore;
+
+	/** The file in PEM format containing the public certificate chain of the client. It may also include
+	* the client's private key.
+	*/
+	const char* keyStore;
+
+	/** If not included in the sslKeyStore, this setting points to the file in PEM format containing
+	* the client's private key.
+	*/
+	const char* privateKey;
+
+	/** The password to load the client's privateKey if encrypted. */
+	const char* privateKeyPassword;
+
+	/**
+	* The list of cipher suites that the client will present to the server during the SSL handshake. For a
+	* full explanation of the cipher list format, please see the OpenSSL on-line documentation:
+	* http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT
+	* If this setting is ommitted, its default value will be "ALL", that is, all the cipher suites -excluding
+	* those offering no encryption- will be considered.
+	* This setting can be used to set an SSL anonymous connection ("aNULL" string value, for instance).
+	*/
+	const char* enabledCipherSuites;
+
+    /** True/False option to enable verification of the server certificate **/
+    int enableServerCertAuth;
+
+    /** The SSL/TLS version to use. Specify one of MQTT_SSL_VERSION_DEFAULT (0),
+    * MQTT_SSL_VERSION_TLS_1_0 (1), MQTT_SSL_VERSION_TLS_1_1 (2) or MQTT_SSL_VERSION_TLS_1_2 (3).
+    * Only used if struct_version is >= 1.
+    */
+    int sslVersion;
+
+    /**
+     * Whether to carry out post-connect checks, including that a certificate
+     * matches the given host name.
+     * Exists only if struct_version >= 2
+     */
+    int verify;
+
+    /**
+     * From the OpenSSL documentation:
+     * If CApath is not NULL, it points to a directory containing CA certificates in PEM format.
+     * Exists only if struct_version >= 2
+	 */
+	const char* CApath;
+
+    /**
+     * Callback function for OpenSSL error handler ERR_print_errors_cb
+     * Exists only if struct_version >= 3
+     */
+    int (*ssl_error_cb) (const char *str, size_t len, void *u);
+
+    /**
+     * Application-specific contex for OpenSSL error handler ERR_print_errors_cb
+     * Exists only if struct_version >= 3
+     */
+    void* ssl_error_context;
+
+	/**
+	 * Callback function for setting TLS-PSK options. Parameters correspond to that of
+	 * SSL_CTX_set_psk_client_callback, except for u which is the pointer ssl_psk_context.
+	 * Exists only if struct_version >= 4
+	 */
+	unsigned int (*ssl_psk_cb) (const char *hint, char *identity, unsigned int max_identity_len, unsigned char *psk, unsigned int max_psk_len, void *u);
+
+	/**
+	 * Application-specific contex for ssl_psk_cb
+	 * Exists only if struct_version >= 4
+	 */
+	void* ssl_psk_context;
+
+	/**
+	 * Don't load default SSL CA. Should be used together with PSK to make sure
+	 * regular servers with certificate in place is not accepted.
+	 * Exists only if struct_version >= 4
+	 */
+	int disableDefaultTrustStore;
+
+	/**
+	 * The protocol-lists must be in wire-format, which is defined as a vector of non-empty, 8-bit length-prefixed, byte strings.
+	 * The length-prefix byte is not included in the length. Each string is limited to 255 bytes. A byte-string length of 0 is invalid.
+	 * A truncated byte-string is invalid.
+	 * Check documentation for SSL_CTX_set_alpn_protos
+	 * Exists only if struct_version >= 5
+	 */
+	const unsigned char *protos;
+
+	/**
+	 * The length of the vector protos vector
+	 * Exists only if struct_version >= 5
+	 */
+	unsigned int protos_len;
+} MQTTAsync_SSLOptions;
+
+#define MQTTAsync_SSLOptions_initializer { {'M', 'Q', 'T', 'S'}, 5, NULL, NULL, NULL, NULL, NULL, 1, MQTT_SSL_VERSION_DEFAULT, 0, NULL, NULL, NULL, NULL, NULL, 0, NULL, 0 }
+
+/** Utility structure where name/value pairs are needed */
+typedef struct
+{
+	const char* name; /**< name string */
+	const char* value; /**< value string */
+} MQTTAsync_nameValue;
+
+/**
+ * MQTTAsync_connectOptions defines several settings that control the way the
+ * client connects to an MQTT server.
+ *
+ * Suitable default values are set in the following initializers:
+ * - MQTTAsync_connectOptions_initializer: for MQTT 3.1.1 non-WebSockets
+ * - MQTTAsync_connectOptions_initializer5: for MQTT 5.0 non-WebSockets
+ * - MQTTAsync_connectOptions_initializer_ws: for MQTT 3.1.1 WebSockets
+ * - MQTTAsync_connectOptions_initializer5_ws: for MQTT 5.0 WebSockets
+ */
+typedef struct
+{
+	/** The eyecatcher for this structure.  must be MQTC. */
+	char struct_id[4];
+	/** The version number of this structure.  Must be 0, 1, 2, 3 4 5 6, 7 or 8.
+	  * 0 signifies no SSL options and no serverURIs
+	  * 1 signifies no serverURIs
+      * 2 signifies no MQTTVersion
+      * 3 signifies no automatic reconnect options
+      * 4 signifies no binary password option (just string)
+      * 5 signifies no MQTTV5 properties
+      * 6 signifies no HTTP headers option
+      * 7 signifies no HTTP proxy and HTTPS proxy options
+	  */
+	int struct_version;
+	/** The "keep alive" interval, measured in seconds, defines the maximum time
+      * that should pass without communication between the client and the server
+      * The client will ensure that at least one message travels across the
+      * network within each keep alive period.  In the absence of a data-related
+	  * message during the time period, the client sends a very small MQTT
+      * "ping" message, which the server will acknowledge. The keep alive
+      * interval enables the client to detect when the server is no longer
+	  * available without having to wait for the long TCP/IP timeout.
+	  * Set to 0 if you do not want any keep alive processing.
+	  */
+	int keepAliveInterval;
+	/**
+      * This is a boolean value. The cleansession setting controls the behaviour
+      * of both the client and the server at connection and disconnection time.
+      * The client and server both maintain session state information. This
+      * information is used to ensure "at least once" and "exactly once"
+      * delivery, and "exactly once" receipt of messages. Session state also
+      * includes subscriptions created by an MQTT client. You can choose to
+      * maintain or discard state information between sessions.
+      *
+      * When cleansession is true, the state information is discarded at
+      * connect and disconnect. Setting cleansession to false keeps the state
+      * information. When you connect an MQTT client application with
+      * MQTTAsync_connect(), the client identifies the connection using the
+      * client identifier and the address of the server. The server checks
+      * whether session information for this client
+      * has been saved from a previous connection to the server. If a previous
+      * session still exists, and cleansession=true, then the previous session
+      * information at the client and server is cleared. If cleansession=false,
+      * the previous session is resumed. If no previous session exists, a new
+      * session is started.
+	  */
+	int cleansession;
+	/**
+      * This controls how many messages can be in-flight simultaneously.
+	  */
+	int maxInflight;
+	/**
+      * This is a pointer to an MQTTAsync_willOptions structure. If your
+      * application does not make use of the Last Will and Testament feature,
+      * set this pointer to NULL.
+      */
+	MQTTAsync_willOptions* will;
+	/**
+      * MQTT servers that support the MQTT v3.1 protocol provide authentication
+      * and authorisation by user name and password. This is the user name
+      * parameter.
+      */
+	const char* username;
+	/**
+      * MQTT servers that support the MQTT v3.1 protocol provide authentication
+      * and authorisation by user name and password. This is the password
+      * parameter.
+      */
+	const char* password;
+	/**
+      * The time interval in seconds to allow a connect to complete.
+      */
+	int connectTimeout;
+	/**
+	 * The time interval in seconds after which unacknowledged publish requests are
+	 * retried during a TCP session.  With MQTT 3.1.1 and later, retries are
+	 * not required except on reconnect.  0 turns off in-session retries, and is the
+	 * recommended setting.  Adding retries to an already overloaded network only
+	 * exacerbates the problem.
+	 */
+	int retryInterval;
+	/**
+      * This is a pointer to an MQTTAsync_SSLOptions structure. If your
+      * application does not make use of SSL, set this pointer to NULL.
+      */
+	MQTTAsync_SSLOptions* ssl;
+	/**
+      * A pointer to a callback function to be called if the connect successfully
+      * completes.  Can be set to NULL, in which case no indication of successful
+      * completion will be received.
+      */
+	MQTTAsync_onSuccess* onSuccess;
+	/**
+      * A pointer to a callback function to be called if the connect fails.
+      * Can be set to NULL, in which case no indication of unsuccessful
+      * completion will be received.
+      */
+	MQTTAsync_onFailure* onFailure;
+	/**
+	  * A pointer to any application-specific context. The
+      * the <i>context</i> pointer is passed to success or failure callback functions to
+      * provide access to the context information in the callback.
+      */
+	void* context;
+	/**
+	  * The number of entries in the serverURIs array.
+	  */
+	int serverURIcount;
+	/**
+	  * An array of null-terminated strings specifying the servers to
+      * which the client will connect. Each string takes the form <i>protocol://host:port</i>.
+      * <i>protocol</i> must be <i>tcp</i>, <i>ssl</i>, <i>ws</i> or <i>wss</i>.
+      * The TLS enabled prefixes (ssl, wss) are only valid if a TLS version of the library
+      * is linked with.
+      * For <i>host</i>, you can
+      * specify either an IP address or a domain name. For instance, to connect to
+      * a server running on the local machines with the default MQTT port, specify
+      * <i>tcp://localhost:1883</i>.
+      */
+	char* const* serverURIs;
+	/**
+      * Sets the version of MQTT to be used on the connect.
+      * MQTTVERSION_DEFAULT (0) = default: start with 3.1.1, and if that fails, fall back to 3.1
+      * MQTTVERSION_3_1 (3) = only try version 3.1
+      * MQTTVERSION_3_1_1 (4) = only try version 3.1.1
+	  */
+	int MQTTVersion;
+	/**
+	  * Reconnect automatically in the case of a connection being lost. 0=false, 1=true
+	  */
+	int automaticReconnect;
+	/**
+	  * The minimum automatic reconnect retry interval in seconds. Doubled on each failed retry.
+	  */
+	int minRetryInterval;
+	/**
+	  * The maximum automatic reconnect retry interval in seconds. The doubling stops here on failed retries.
+	  */
+	int maxRetryInterval;
+	/**
+	 * Optional binary password.  Only checked and used if the password option is NULL
+	 */
+	struct {
+		int len;            /**< binary password length */
+		const void* data;  /**< binary password data */
+	} binarypwd;
+	/*
+	 * MQTT V5 clean start flag.  Only clears state at the beginning of the session.
+	 */
+	int cleanstart;
+	/**
+	 * MQTT V5 properties for connect
+	 */
+	MQTTProperties *connectProperties;
+	/**
+	 * MQTT V5 properties for the will message in the connect
+	 */
+	MQTTProperties *willProperties;
+	/**
+      * A pointer to a callback function to be called if the connect successfully
+      * completes.  Can be set to NULL, in which case no indication of successful
+      * completion will be received.
+      */
+	MQTTAsync_onSuccess5* onSuccess5;
+	/**
+      * A pointer to a callback function to be called if the connect fails.
+      * Can be set to NULL, in which case no indication of unsuccessful
+      * completion will be received.
+      */
+	MQTTAsync_onFailure5* onFailure5;
+	/**
+	 * HTTP headers for websockets
+	 */
+	const MQTTAsync_nameValue* httpHeaders;
+	/**
+	 * HTTP proxy
+	 */
+	const char* httpProxy;
+	/**
+	 * HTTPS proxy
+	 */
+	const char* httpsProxy;
+} MQTTAsync_connectOptions;
+
+/** Initializer for connect options for MQTT 3.1.1 non-WebSocket connections */
+#define MQTTAsync_connectOptions_initializer { {'M', 'Q', 'T', 'C'}, 8, 60, 1, 65535, NULL, NULL, NULL, 30, 0,\
+NULL, NULL, NULL, NULL, 0, NULL, MQTTVERSION_DEFAULT, 0, 1, 60, {0, NULL}, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL}
+
+/** Initializer for connect options for MQTT 5.0 non-WebSocket connections */
+#define MQTTAsync_connectOptions_initializer5 { {'M', 'Q', 'T', 'C'}, 8, 60, 0, 65535, NULL, NULL, NULL, 30, 0,\
+NULL, NULL, NULL, NULL, 0, NULL, MQTTVERSION_5, 0, 1, 60, {0, NULL}, 1, NULL, NULL, NULL, NULL, NULL, NULL, NULL}
+
+/** Initializer for connect options for MQTT 3.1.1 WebSockets connections.
+  * The keepalive interval is set to 45 seconds to avoid webserver 60 second inactivity timeouts.
+  */
+#define MQTTAsync_connectOptions_initializer_ws { {'M', 'Q', 'T', 'C'}, 8, 45, 1, 65535, NULL, NULL, NULL, 30, 0,\
+NULL, NULL, NULL, NULL, 0, NULL, MQTTVERSION_DEFAULT, 0, 1, 60, {0, NULL}, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL}
+
+/** Initializer for connect options for MQTT 5.0 WebSockets connections.
+  * The keepalive interval is set to 45 seconds to avoid webserver 60 second inactivity timeouts.
+  */
+#define MQTTAsync_connectOptions_initializer5_ws { {'M', 'Q', 'T', 'C'}, 8, 45, 0, 65535, NULL, NULL, NULL, 30, 0,\
+NULL, NULL, NULL, NULL, 0, NULL, MQTTVERSION_5, 0, 1, 60, {0, NULL}, 1, NULL, NULL, NULL, NULL, NULL, NULL, NULL}
+
+
+/**
+  * This function attempts to connect a previously-created client (see
+  * MQTTAsync_create()) to an MQTT server using the specified options. If you
+  * want to enable asynchronous message and status notifications, you must call
+  * MQTTAsync_setCallbacks() prior to MQTTAsync_connect().
+  * @param handle A valid client handle from a successful call to
+  * MQTTAsync_create().
+  * @param options A pointer to a valid MQTTAsync_connectOptions
+  * structure.
+  * @return ::MQTTASYNC_SUCCESS if the client connect request was accepted.
+  * If the client was unable to connect to the server, an error code is
+  * returned via the onFailure callback, if set.
+  * Error codes greater than 0 are returned by the MQTT protocol:<br><br>
+  * <b>1</b>: Connection refused: Unacceptable protocol version<br>
+  * <b>2</b>: Connection refused: Identifier rejected<br>
+  * <b>3</b>: Connection refused: Server unavailable<br>
+  * <b>4</b>: Connection refused: Bad user name or password<br>
+  * <b>5</b>: Connection refused: Not authorized<br>
+  * <b>6-255</b>: Reserved for future use<br>
+  */
+LIBMQTT_API int MQTTAsync_connect(MQTTAsync handle, const MQTTAsync_connectOptions* options);
+
+/** Options for the ::MQTTAsync_disconnect call */
+typedef struct
+{
+	/** The eyecatcher for this structure. Must be MQTD. */
+	char struct_id[4];
+	/** The version number of this structure.  Must be 0 or 1.  0 signifies no V5 properties */
+	int struct_version;
+	/**
+      * The client delays disconnection for up to this time (in
+      * milliseconds) in order to allow in-flight message transfers to complete.
+      */
+	int timeout;
+	/**
+    * A pointer to a callback function to be called if the disconnect successfully
+    * completes.  Can be set to NULL, in which case no indication of successful
+    * completion will be received.
+    */
+	MQTTAsync_onSuccess* onSuccess;
+	/**
+    * A pointer to a callback function to be called if the disconnect fails.
+    * Can be set to NULL, in which case no indication of unsuccessful
+    * completion will be received.
+    */
+	MQTTAsync_onFailure* onFailure;
+	/**
+	* A pointer to any application-specific context. The
+    * the <i>context</i> pointer is passed to success or failure callback functions to
+    * provide access to the context information in the callback.
+    */
+	void* context;
+	/**
+	 * MQTT V5 input properties
+	 */
+	MQTTProperties properties;
+	/**
+	 * Reason code for MQTTV5 disconnect
+	 */
+	enum MQTTReasonCodes reasonCode;
+	/**
+    * A pointer to a callback function to be called if the disconnect successfully
+    * completes.  Can be set to NULL, in which case no indication of successful
+    * completion will be received.
+    */
+	MQTTAsync_onSuccess5* onSuccess5;
+	/**
+    * A pointer to a callback function to be called if the disconnect fails.
+    * Can be set to NULL, in which case no indication of unsuccessful
+    * completion will be received.
+    */
+	MQTTAsync_onFailure5* onFailure5;
+} MQTTAsync_disconnectOptions;
+
+#define MQTTAsync_disconnectOptions_initializer { {'M', 'Q', 'T', 'D'}, 0, 0, NULL, NULL, NULL,\
+	MQTTProperties_initializer, MQTTREASONCODE_SUCCESS, NULL, NULL }
+
+#define MQTTAsync_disconnectOptions_initializer5 { {'M', 'Q', 'T', 'D'}, 1, 0, NULL, NULL, NULL,\
+	MQTTProperties_initializer, MQTTREASONCODE_SUCCESS, NULL, NULL }
+
+/**
+  * This function attempts to disconnect the client from the MQTT
+  * server. In order to allow the client time to complete handling of messages
+  * that are in-flight when this function is called, a timeout period is
+  * specified. When the timeout period has expired, the client disconnects even
+  * if there are still outstanding message acknowledgements.
+  * The next time the client connects to the same server, any QoS 1 or 2
+  * messages which have not completed will be retried depending on the
+  * cleansession settings for both the previous and the new connection (see
+  * MQTTAsync_connectOptions.cleansession and MQTTAsync_connect()).
+  * @param handle A valid client handle from a successful call to
+  * MQTTAsync_create().
+  * @param options The client delays disconnection for up to this time (in
+  * milliseconds) in order to allow in-flight message transfers to complete.
+  * @return ::MQTTASYNC_SUCCESS if the client successfully disconnects from
+  * the server. An error code is returned if the client was unable to disconnect
+  * from the server
+  */
+LIBMQTT_API int MQTTAsync_disconnect(MQTTAsync handle, const MQTTAsync_disconnectOptions* options);
+
+
+/**
+  * This function allows the client application to test whether or not a
+  * client is currently connected to the MQTT server.
+  * @param handle A valid client handle from a successful call to
+  * MQTTAsync_create().
+  * @return Boolean true if the client is connected, otherwise false.
+  */
+LIBMQTT_API int MQTTAsync_isConnected(MQTTAsync handle);
+
+
+/**
+  * This function attempts to subscribe a client to a single topic, which may
+  * contain wildcards (see @ref wildcard). This call also specifies the
+  * @ref qos requested for the subscription
+  * (see also MQTTAsync_subscribeMany()).
+  * @param handle A valid client handle from a successful call to
+  * MQTTAsync_create().
+  * @param topic The subscription topic, which may include wildcards.
+  * @param qos The requested quality of service for the subscription.
+  * @param response A pointer to a response options structure. Used to set callback functions.
+  * @return ::MQTTASYNC_SUCCESS if the subscription request is successful.
+  * An error code is returned if there was a problem registering the
+  * subscription.
+  */
+LIBMQTT_API int MQTTAsync_subscribe(MQTTAsync handle, const char* topic, int qos, MQTTAsync_responseOptions* response);
+
+
+/**
+  * This function attempts to subscribe a client to a list of topics, which may
+  * contain wildcards (see @ref wildcard). This call also specifies the
+  * @ref qos requested for each topic (see also MQTTAsync_subscribe()).
+  * @param handle A valid client handle from a successful call to
+  * MQTTAsync_create().
+  * @param count The number of topics for which the client is requesting
+  * subscriptions.
+  * @param topic An array (of length <i>count</i>) of pointers to
+  * topics, each of which may include wildcards.
+  * @param qos An array (of length <i>count</i>) of @ref qos
+  * values. qos[n] is the requested QoS for topic[n].
+  * @param response A pointer to a response options structure. Used to set callback functions.
+  * @return ::MQTTASYNC_SUCCESS if the subscription request is successful.
+  * An error code is returned if there was a problem registering the
+  * subscriptions.
+  */
+LIBMQTT_API int MQTTAsync_subscribeMany(MQTTAsync handle, int count, char* const* topic, const int* qos, MQTTAsync_responseOptions* response);
+
+/**
+  * This function attempts to remove an existing subscription made by the
+  * specified client.
+  * @param handle A valid client handle from a successful call to
+  * MQTTAsync_create().
+  * @param topic The topic for the subscription to be removed, which may
+  * include wildcards (see @ref wildcard).
+  * @param response A pointer to a response options structure. Used to set callback functions.
+  * @return ::MQTTASYNC_SUCCESS if the subscription is removed.
+  * An error code is returned if there was a problem removing the
+  * subscription.
+  */
+LIBMQTT_API int MQTTAsync_unsubscribe(MQTTAsync handle, const char* topic, MQTTAsync_responseOptions* response);
+
+/**
+  * This function attempts to remove existing subscriptions to a list of topics
+  * made by the specified client.
+  * @param handle A valid client handle from a successful call to
+  * MQTTAsync_create().
+  * @param count The number subscriptions to be removed.
+  * @param topic An array (of length <i>count</i>) of pointers to the topics of
+  * the subscriptions to be removed, each of which may include wildcards.
+  * @param response A pointer to a response options structure. Used to set callback functions.
+  * @return ::MQTTASYNC_SUCCESS if the subscriptions are removed.
+  * An error code is returned if there was a problem removing the subscriptions.
+  */
+LIBMQTT_API int MQTTAsync_unsubscribeMany(MQTTAsync handle, int count, char* const* topic, MQTTAsync_responseOptions* response);
+
+
+/**
+  * This function attempts to publish a message to a given topic (see also
+  * ::MQTTAsync_sendMessage()). An ::MQTTAsync_token is issued when
+  * this function returns successfully if the QoS is greater than 0.
+  * If the client application needs to
+  * test for successful delivery of messages, a callback should be set
+  * (see ::MQTTAsync_onSuccess() and ::MQTTAsync_deliveryComplete()).
+  * @param handle A valid client handle from a successful call to
+  * MQTTAsync_create().
+  * @param destinationName The topic associated with this message.
+  * @param payloadlen The length of the payload in bytes.
+  * @param payload A pointer to the byte array payload of the message.
+  * @param qos The @ref qos of the message.
+  * @param retained The retained flag for the message.
+  * @param response A pointer to an ::MQTTAsync_responseOptions structure. Used to set callback functions.
+  * This is optional and can be set to NULL.
+  * @return ::MQTTASYNC_SUCCESS if the message is accepted for publication.
+  * An error code is returned if there was a problem accepting the message.
+  */
+LIBMQTT_API int MQTTAsync_send(MQTTAsync handle, const char* destinationName, int payloadlen, const void* payload, int qos,
+		int retained, MQTTAsync_responseOptions* response);
+
+/**
+  * This function attempts to publish a message to a given topic (see also
+  * MQTTAsync_publish()). An ::MQTTAsync_token is issued when
+  * this function returns successfully if the QoS is greater than 0.
+  * If the client application needs to
+  * test for successful delivery of messages, a callback should be set
+  * (see ::MQTTAsync_onSuccess() and ::MQTTAsync_deliveryComplete()).
+  * @param handle A valid client handle from a successful call to
+  * MQTTAsync_create().
+  * @param destinationName The topic associated with this message.
+  * @param msg A pointer to a valid MQTTAsync_message structure containing
+  * the payload and attributes of the message to be published.
+  * @param response A pointer to an ::MQTTAsync_responseOptions structure. Used to set callback functions.
+  * @return ::MQTTASYNC_SUCCESS if the message is accepted for publication.
+  * An error code is returned if there was a problem accepting the message.
+  */
+LIBMQTT_API int MQTTAsync_sendMessage(MQTTAsync handle, const char* destinationName, const MQTTAsync_message* msg, MQTTAsync_responseOptions* response);
+
+
+/**
+  * This function sets a pointer to an array of tokens for
+  * messages that are currently in-flight (pending completion).
+  *
+  * <b>Important note:</b> The memory used to hold the array of tokens is
+  * malloc()'d in this function. The client application is responsible for
+  * freeing this memory when it is no longer required.
+  * @param handle A valid client handle from a successful call to
+  * MQTTAsync_create().
+  * @param tokens The address of a pointer to an ::MQTTAsync_token.
+  * When the function returns successfully, the pointer is set to point to an
+  * array of tokens representing messages pending completion. The last member of
+  * the array is set to -1 to indicate there are no more tokens. If no tokens
+  * are pending, the pointer is set to NULL.
+  * @return ::MQTTASYNC_SUCCESS if the function returns successfully.
+  * An error code is returned if there was a problem obtaining the list of
+  * pending tokens.
+  */
+LIBMQTT_API int MQTTAsync_getPendingTokens(MQTTAsync handle, MQTTAsync_token **tokens);
+
+/**
+ * Tests whether a request corresponding to a token is complete.
+ *
+ * @param handle A valid client handle from a successful call to
+ * MQTTAsync_create().
+ * @param token An ::MQTTAsync_token associated with a request.
+ * @return 1 if the request has been completed, 0 if not.
+ */
+#define MQTTASYNC_TRUE 1
+LIBMQTT_API int MQTTAsync_isComplete(MQTTAsync handle, MQTTAsync_token token);
+
+
+/**
+ * Waits for a request corresponding to a token to complete.  This only works for
+ * messages with QoS greater than 0.  A QoS 0 message has no MQTT token.
+ * This function will always return ::MQTTASYNC_SUCCESS for a QoS 0 message.
+ *
+ * @param handle A valid client handle from a successful call to
+ * MQTTAsync_create().
+ * @param token An ::MQTTAsync_token associated with a request.
+ * @param timeout the maximum time to wait for completion, in milliseconds
+ * @return ::MQTTASYNC_SUCCESS if the request has been completed in the time allocated,
+ *  ::MQTTASYNC_FAILURE or ::MQTTASYNC_DISCONNECTED if not.
+ */
+LIBMQTT_API int MQTTAsync_waitForCompletion(MQTTAsync handle, MQTTAsync_token token, unsigned long timeout);
+
+
+/**
+  * This function frees memory allocated to an MQTT message, including the
+  * additional memory allocated to the message payload. The client application
+  * calls this function when the message has been fully processed. <b>Important
+  * note:</b> This function does not free the memory allocated to a message
+  * topic string. It is the responsibility of the client application to free
+  * this memory using the MQTTAsync_free() library function.
+  * @param msg The address of a pointer to the ::MQTTAsync_message structure
+  * to be freed.
+  */
+LIBMQTT_API void MQTTAsync_freeMessage(MQTTAsync_message** msg);
+
+/**
+  * This function frees memory allocated by the MQTT C client library, especially the
+  * topic name. This is needed on Windows when the client library and application
+  * program have been compiled with different versions of the C compiler.  It is
+  * thus good policy to always use this function when freeing any MQTT C client-
+  * allocated memory.
+  * @param ptr The pointer to the client library storage to be freed.
+  */
+LIBMQTT_API void MQTTAsync_free(void* ptr);
+
+/**
+  * This function is used to allocate memory to be used or freed by the MQTT C client library,
+  * especially the data in the ::MQTTPersistence_afterRead and ::MQTTPersistence_beforeWrite
+  * callbacks. This is needed on Windows when the client library and application
+  * program have been compiled with different versions of the C compiler.
+  * @param size The size of the memory to be allocated.
+  */
+LIBMQTT_API void* MQTTAsync_malloc(size_t size);
+
+/**
+  * This function frees the memory allocated to an MQTT client (see
+  * MQTTAsync_create()). It should be called when the client is no longer
+  * required.
+  * @param handle A pointer to the handle referring to the ::MQTTAsync
+  * structure to be freed.
+  */
+LIBMQTT_API void MQTTAsync_destroy(MQTTAsync* handle);
+
+
+
+enum MQTTASYNC_TRACE_LEVELS
+{
+	MQTTASYNC_TRACE_MAXIMUM = 1,
+	MQTTASYNC_TRACE_MEDIUM,
+	MQTTASYNC_TRACE_MINIMUM,
+	MQTTASYNC_TRACE_PROTOCOL,
+	MQTTASYNC_TRACE_ERROR,
+	MQTTASYNC_TRACE_SEVERE,
+	MQTTASYNC_TRACE_FATAL,
+};
+
+
+/**
+  * This function sets the level of trace information which will be
+  * returned in the trace callback.
+  * @param level the trace level required
+  */
+LIBMQTT_API void MQTTAsync_setTraceLevel(enum MQTTASYNC_TRACE_LEVELS level);
+
+
+/**
+  * This is a callback function prototype which must be implemented if you want
+  * to receive trace information. Do not invoke any other Paho API calls in this
+  * callback function - unpredictable behavior may result.
+  * @param level the trace level of the message returned
+  * @param message the trace message.  This is a pointer to a static buffer which
+  * will be overwritten on each call.  You must copy the data if you want to keep
+  * it for later.
+  */
+typedef void MQTTAsync_traceCallback(enum MQTTASYNC_TRACE_LEVELS level, char* message);
+
+/**
+  * This function sets the trace callback if needed.  If set to NULL,
+  * no trace information will be returned.  The default trace level is
+  * MQTTASYNC_TRACE_MINIMUM.
+  * @param callback a pointer to the function which will handle the trace information
+  */
+LIBMQTT_API void MQTTAsync_setTraceCallback(MQTTAsync_traceCallback* callback);
+
+/**
+  * This function returns version information about the library.
+  * no trace information will be returned.  The default trace level is
+  * MQTTASYNC_TRACE_MINIMUM
+  * @return an array of strings describing the library.  The last entry is a NULL pointer.
+  */
+LIBMQTT_API MQTTAsync_nameValue* MQTTAsync_getVersionInfo(void);
+
+/**
+ * Returns a pointer to a string representation of the error code, or NULL.
+ * Do not free after use. Returns NULL if the error code is unknown.
+ * @param code the MQTTASYNC_ return code.
+ * @return a static string representation of the error code.
+ */
+LIBMQTT_API const char* MQTTAsync_strerror(int code);
+
+
+/*!
+  * @cond MQTTAsync_main
+  * @page async Threading
+  * The client application runs on several threads.
+  * Processing of handshaking and maintaining
+  * the network connection is performed in the background.
+  * This API is thread safe: functions may be called by multiple application
+  * threads.
+  * Notifications of status and message reception are provided to the client
+  * application using callbacks registered with the library by the call to
+  * MQTTAsync_setCallbacks() (see MQTTAsync_messageArrived(),
+  * MQTTAsync_connectionLost() and MQTTAsync_deliveryComplete()).
+  * In addition, some functions allow success and failure callbacks to be set
+  * for individual requests, in the ::MQTTAsync_responseOptions structure.  Applications
+  * can be written as a chain of callback functions.
+  *
+  * @page callbacks Callbacks
+  * Any function from this API may be used within a callback.  It is not advisable to
+  * use ::MQTTAsync_waitForCompletion within a callback, however, as it is the only
+  * API call that may take some time to complete, which may cause unpredictable
+  * behaviour.  All the other API calls are intended to complete quickly, starting
+  * a request in the background, with success or failure notified by other callbacks.
+  *
+  * If no callbacks are assigned, this will include the message arrived callback.
+  * This could be done if the application is a pure publisher, and does
+  * not subscribe to any topics.  If however messages are received, and no message
+  * arrived callback is set, then those messages will accumulate
+  * and take up memory, as there is no place for them to be delivered.
+  * A log message will be written to highlight the issue, but it is up
+  * to the application to protect against this situation.
+  *
+  * @page auto_reconnect Automatic Reconnect
+  * The ability for the client library to reconnect automatically in the event
+  * of a connection failure was added in 1.1.  The connection lost callback
+  * allows a flexible response to the loss of a connection, so almost any
+  * behaviour can be implemented in that way.  Automatic reconnect does have the
+  * advantage of being a little simpler to use.
+  *
+  * To switch on automatic reconnect, the connect options field
+  * automaticReconnect should be set to non-zero.  The minimum and maximum times
+  * before the next connection attempt can also be set, the defaults being 1 and
+  * 60 seconds.  At each failure to reconnect, the retry interval is doubled until
+  * the maximum value is reached, and there it stays until the connection is
+  * successfully re-established whereupon it is reset.
+  *
+  * When a reconnection attempt is successful, the ::MQTTAsync_connected callback
+  * function is invoked, if set by calling ::MQTTAsync_setConnected.  This allows
+  * the application to take any actions needed, such as amending subscriptions.
+  *
+  * @page offline_publish Publish While Disconnected
+  * This feature was not originally available because with persistence enabled,
+  * messages could be stored locally without ever knowing if they could be sent.
+  * The client application could have created the client with an erroneous broker
+  * address or port for instance.
+  *
+  * To enable messages to be published when the application is disconnected
+  * ::MQTTAsync_createWithOptions must be used instead of ::MQTTAsync_create to
+  * create the client object.  The ::MQTTAsync_createOptions field sendWhileDisconnected
+  * must be set to non-zero, and the maxBufferedMessages field set as required -
+  * the default being 100.
+  *
+  * ::MQTTAsync_getPendingTokens can be called to return the ids of the messages
+  * waiting to be sent, or for which the sending process has not completed.
+  *
+  * @page wildcard Subscription wildcards
+  * Every MQTT message includes a topic that classifies it. MQTT servers use
+  * topics to determine which subscribers should receive messages published to
+  * the server.
+  *
+  * Consider the server receiving messages from several environmental sensors.
+  * Each sensor publishes its measurement data as a message with an associated
+  * topic. Subscribing applications need to know which sensor originally
+  * published each received message. A unique topic is thus used to identify
+  * each sensor and measurement type. Topics such as SENSOR1TEMP,
+  * SENSOR1HUMIDITY, SENSOR2TEMP and so on achieve this but are not very
+  * flexible. If additional sensors are added to the system at a later date,
+  * subscribing applications must be modified to receive them.
+  *
+  * To provide more flexibility, MQTT supports a hierarchical topic namespace.
+  * This allows application designers to organize topics to simplify their
+  * management. Levels in the hierarchy are delimited by the '/' character,
+  * such as SENSOR/1/HUMIDITY. Publishers and subscribers use these
+  * hierarchical topics as already described.
+  *
+  * For subscriptions, two wildcard characters are supported:
+  * <ul>
+  * <li>A '#' character represents a complete sub-tree of the hierarchy and
+  * thus must be the last character in a subscription topic string, such as
+  * SENSOR/#. This will match any topic starting with SENSOR/, such as
+  * SENSOR/1/TEMP and SENSOR/2/HUMIDITY.</li>
+  * <li> A '+' character represents a single level of the hierarchy and is
+  * used between delimiters. For example, SENSOR/+/TEMP will match
+  * SENSOR/1/TEMP and SENSOR/2/TEMP.</li>
+  * </ul>
+  * Publishers are not allowed to use the wildcard characters in their topic
+  * names.
+  *
+  * Deciding on your topic hierarchy is an important step in your system design.
+  *
+  * @page qos Quality of service
+  * The MQTT protocol provides three qualities of service for delivering
+  * messages between clients and servers: "at most once", "at least once" and
+  * "exactly once".
+  *
+  * Quality of service (QoS) is an attribute of an individual message being
+  * published. An application sets the QoS for a specific message by setting the
+  * MQTTAsync_message.qos field to the required value.
+  *
+  * A subscribing client can set the maximum quality of service a server uses
+  * to send messages that match the client subscriptions. The
+  * MQTTAsync_subscribe() and MQTTAsync_subscribeMany() functions set this
+  * maximum. The QoS of a message forwarded to a subscriber thus might be
+  * different to the QoS given to the message by the original publisher.
+  * The lower of the two values is used to forward a message.
+  *
+  * The three levels are:
+  *
+  * <b>QoS0, At most once:</b> The message is delivered at most once, or it
+  * may not be delivered at all. Its delivery across the network is not
+  * acknowledged. The message is not stored. The message could be lost if the
+  * client is disconnected, or if the server fails. QoS0 is the fastest mode of
+  * transfer. It is sometimes called "fire and forget".
+  *
+  * The MQTT protocol does not require servers to forward publications at QoS0
+  * to a client. If the client is disconnected at the time the server receives
+  * the publication, the publication might be discarded, depending on the
+  * server implementation.
+  *
+  * <b>QoS1, At least once:</b> The message is always delivered at least once.
+  * It might be delivered multiple times if there is a failure before an
+  * acknowledgment is received by the sender. The message must be stored
+  * locally at the sender, until the sender receives confirmation that the
+  * message has been published by the receiver. The message is stored in case
+  * the message must be sent again.
+  *
+  * <b>QoS2, Exactly once:</b> The message is always delivered exactly once.
+  * The message must be stored locally at the sender, until the sender receives
+  * confirmation that the message has been published by the receiver. The
+  * message is stored in case the message must be sent again. QoS2 is the
+  * safest, but slowest mode of transfer. A more sophisticated handshaking
+  * and acknowledgement sequence is used than for QoS1 to ensure no duplication
+  * of messages occurs.
+  * @page publish Publication example
+@code
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "MQTTAsync.h"
+
+#if !defined(_WIN32)
+#include <unistd.h>
+#else
+#include <windows.h>
+#endif
+
+#if defined(_WRS_KERNEL)
+#include <OsWrapper.h>
+#endif
+
+#define ADDRESS     "tcp://mqtt.eclipseprojects.io:1883"
+#define CLIENTID    "ExampleClientPub"
+#define TOPIC       "MQTT Examples"
+#define PAYLOAD     "Hello World!"
+#define QOS         1
+#define TIMEOUT     10000L
+
+int finished = 0;
+
+void connlost(void *context, char *cause)
+{
+	MQTTAsync client = (MQTTAsync)context;
+	MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
+	int rc;
+
+	printf("\nConnection lost\n");
+	printf("     cause: %s\n", cause);
+
+	printf("Reconnecting\n");
+	conn_opts.keepAliveInterval = 20;
+	conn_opts.cleansession = 1;
+	if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
+	{
+		printf("Failed to start connect, return code %d\n", rc);
+ 		finished = 1;
+	}
+}
+
+void onDisconnectFailure(void* context, MQTTAsync_failureData* response)
+{
+	printf("Disconnect failed\n");
+	finished = 1;
+}
+
+void onDisconnect(void* context, MQTTAsync_successData* response)
+{
+	printf("Successful disconnection\n");
+	finished = 1;
+}
+
+void onSendFailure(void* context, MQTTAsync_failureData* response)
+{
+	MQTTAsync client = (MQTTAsync)context;
+	MQTTAsync_disconnectOptions opts = MQTTAsync_disconnectOptions_initializer;
+	int rc;
+
+	printf("Message send failed token %d error code %d\n", response->token, response->code);
+	opts.onSuccess = onDisconnect;
+	opts.onFailure = onDisconnectFailure;
+	opts.context = client;
+	if ((rc = MQTTAsync_disconnect(client, &opts)) != MQTTASYNC_SUCCESS)
+	{
+		printf("Failed to start disconnect, return code %d\n", rc);
+		exit(EXIT_FAILURE);
+	}
+}
+
+void onSend(void* context, MQTTAsync_successData* response)
+{
+	MQTTAsync client = (MQTTAsync)context;
+	MQTTAsync_disconnectOptions opts = MQTTAsync_disconnectOptions_initializer;
+	int rc;
+
+	printf("Message with token value %d delivery confirmed\n", response->token);
+	opts.onSuccess = onDisconnect;
+	opts.onFailure = onDisconnectFailure;
+	opts.context = client;
+	if ((rc = MQTTAsync_disconnect(client, &opts)) != MQTTASYNC_SUCCESS)
+	{
+		printf("Failed to start disconnect, return code %d\n", rc);
+		exit(EXIT_FAILURE);
+	}
+}
+
+
+void onConnectFailure(void* context, MQTTAsync_failureData* response)
+{
+	printf("Connect failed, rc %d\n", response ? response->code : 0);
+	finished = 1;
+}
+
+
+void onConnect(void* context, MQTTAsync_successData* response)
+{
+	MQTTAsync client = (MQTTAsync)context;
+	MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
+	MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
+	int rc;
+
+	printf("Successful connection\n");
+	opts.onSuccess = onSend;
+	opts.onFailure = onSendFailure;
+	opts.context = client;
+	pubmsg.payload = PAYLOAD;
+	pubmsg.payloadlen = (int)strlen(PAYLOAD);
+	pubmsg.qos = QOS;
+	pubmsg.retained = 0;
+	if ((rc = MQTTAsync_sendMessage(client, TOPIC, &pubmsg, &opts)) != MQTTASYNC_SUCCESS)
+	{
+		printf("Failed to start sendMessage, return code %d\n", rc);
+		exit(EXIT_FAILURE);
+	}
+}
+
+int messageArrived(void* context, char* topicName, int topicLen, MQTTAsync_message* m)
+{
+	// not expecting any messages
+	return 1;
+}
+
+int main(int argc, char* argv[])
+{
+	MQTTAsync client;
+	MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
+	int rc;
+
+	if ((rc = MQTTAsync_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL)) != MQTTASYNC_SUCCESS)
+	{
+		printf("Failed to create client object, return code %d\n", rc);
+		exit(EXIT_FAILURE);
+	}
+
+	if ((rc = MQTTAsync_setCallbacks(client, NULL, connlost, messageArrived, NULL)) != MQTTASYNC_SUCCESS)
+	{
+		printf("Failed to set callback, return code %d\n", rc);
+		exit(EXIT_FAILURE);
+	}
+
+	conn_opts.keepAliveInterval = 20;
+	conn_opts.cleansession = 1;
+	conn_opts.onSuccess = onConnect;
+	conn_opts.onFailure = onConnectFailure;
+	conn_opts.context = client;
+	if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
+	{
+		printf("Failed to start connect, return code %d\n", rc);
+		exit(EXIT_FAILURE);
+	}
+
+	printf("Waiting for publication of %s\n"
+         "on topic %s for client with ClientID: %s\n",
+         PAYLOAD, TOPIC, CLIENTID);
+	while (!finished)
+		#if defined(_WIN32)
+			Sleep(100);
+		#else
+			usleep(10000L);
+		#endif
+
+	MQTTAsync_destroy(&client);
+ 	return rc;
+}
+
+  * @endcode
+  * @page subscribe Subscription example
+@code
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "MQTTAsync.h"
+
+#if !defined(_WIN32)
+#include <unistd.h>
+#else
+#include <windows.h>
+#endif
+
+#if defined(_WRS_KERNEL)
+#include <OsWrapper.h>
+#endif
+
+#define ADDRESS     "tcp://mqtt.eclipseprojects.io:1883"
+#define CLIENTID    "ExampleClientSub"
+#define TOPIC       "MQTT Examples"
+#define PAYLOAD     "Hello World!"
+#define QOS         1
+#define TIMEOUT     10000L
+
+int disc_finished = 0;
+int subscribed = 0;
+int finished = 0;
+
+void connlost(void *context, char *cause)
+{
+	MQTTAsync client = (MQTTAsync)context;
+	MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
+	int rc;
+
+	printf("\nConnection lost\n");
+	if (cause)
+		printf("     cause: %s\n", cause);
+
+	printf("Reconnecting\n");
+	conn_opts.keepAliveInterval = 20;
+	conn_opts.cleansession = 1;
+	if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
+	{
+		printf("Failed to start connect, return code %d\n", rc);
+		finished = 1;
+	}
+}
+
+
+int msgarrvd(void *context, char *topicName, int topicLen, MQTTAsync_message *message)
+{
+    printf("Message arrived\n");
+    printf("     topic: %s\n", topicName);
+    printf("   message: %.*s\n", message->payloadlen, (char*)message->payload);
+    MQTTAsync_freeMessage(&message);
+    MQTTAsync_free(topicName);
+    return 1;
+}
+
+void onDisconnectFailure(void* context, MQTTAsync_failureData* response)
+{
+	printf("Disconnect failed, rc %d\n", response->code);
+	disc_finished = 1;
+}
+
+void onDisconnect(void* context, MQTTAsync_successData* response)
+{
+	printf("Successful disconnection\n");
+	disc_finished = 1;
+}
+
+void onSubscribe(void* context, MQTTAsync_successData* response)
+{
+	printf("Subscribe succeeded\n");
+	subscribed = 1;
+}
+
+void onSubscribeFailure(void* context, MQTTAsync_failureData* response)
+{
+	printf("Subscribe failed, rc %d\n", response->code);
+	finished = 1;
+}
+
+
+void onConnectFailure(void* context, MQTTAsync_failureData* response)
+{
+	printf("Connect failed, rc %d\n", response->code);
+	finished = 1;
+}
+
+
+void onConnect(void* context, MQTTAsync_successData* response)
+{
+	MQTTAsync client = (MQTTAsync)context;
+	MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
+	int rc;
+
+	printf("Successful connection\n");
+
+	printf("Subscribing to topic %s\nfor client %s using QoS%d\n\n"
+           "Press Q<Enter> to quit\n\n", TOPIC, CLIENTID, QOS);
+	opts.onSuccess = onSubscribe;
+	opts.onFailure = onSubscribeFailure;
+	opts.context = client;
+	if ((rc = MQTTAsync_subscribe(client, TOPIC, QOS, &opts)) != MQTTASYNC_SUCCESS)
+	{
+		printf("Failed to start subscribe, return code %d\n", rc);
+		finished = 1;
+	}
+}
+
+
+int main(int argc, char* argv[])
+{
+	MQTTAsync client;
+	MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
+	MQTTAsync_disconnectOptions disc_opts = MQTTAsync_disconnectOptions_initializer;
+	int rc;
+	int ch;
+
+	if ((rc = MQTTAsync_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL))
+			!= MQTTASYNC_SUCCESS)
+	{
+		printf("Failed to create client, return code %d\n", rc);
+		rc = EXIT_FAILURE;
+		goto exit;
+	}
+
+	if ((rc = MQTTAsync_setCallbacks(client, client, connlost, msgarrvd, NULL)) != MQTTASYNC_SUCCESS)
+	{
+		printf("Failed to set callbacks, return code %d\n", rc);
+		rc = EXIT_FAILURE;
+		goto destroy_exit;
+	}
+
+	conn_opts.keepAliveInterval = 20;
+	conn_opts.cleansession = 1;
+	conn_opts.onSuccess = onConnect;
+	conn_opts.onFailure = onConnectFailure;
+	conn_opts.context = client;
+	if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
+	{
+		printf("Failed to start connect, return code %d\n", rc);
+		rc = EXIT_FAILURE;
+		goto destroy_exit;
+	}
+
+	while (!subscribed && !finished)
+		#if defined(_WIN32)
+			Sleep(100);
+		#else
+			usleep(10000L);
+		#endif
+
+	if (finished)
+		goto exit;
+
+	do
+	{
+		ch = getchar();
+	} while (ch!='Q' && ch != 'q');
+
+	disc_opts.onSuccess = onDisconnect;
+	disc_opts.onFailure = onDisconnectFailure;
+	if ((rc = MQTTAsync_disconnect(client, &disc_opts)) != MQTTASYNC_SUCCESS)
+	{
+		printf("Failed to start disconnect, return code %d\n", rc);
+		rc = EXIT_FAILURE;
+		goto destroy_exit;
+	}
+ 	while (!disc_finished)
+ 	{
+		#if defined(_WIN32)
+			Sleep(100);
+		#else
+			usleep(10000L);
+		#endif
+ 	}
+
+destroy_exit:
+	MQTTAsync_destroy(&client);
+exit:
+ 	return rc;
+}
+
+  * @endcode
+* @page tracing Tracing
+  *
+  * Runtime tracing can be controlled by environment variables or API calls.
+  *
+  * #### Environment variables
+  *
+  * Tracing is switched on by setting the MQTT_C_CLIENT_TRACE environment variable.
+  * A value of ON, or stdout, prints to stdout, any other value is interpreted as a file name to use.
+  *
+  * The amount of trace detail is controlled with the MQTT_C_CLIENT_TRACE_LEVEL environment
+  * variable - valid values are ERROR, PROTOCOL, MINIMUM, MEDIUM and MAXIMUM
+  * (from least to most verbose).
+  *
+  * The variable MQTT_C_CLIENT_TRACE_MAX_LINES limits the number of lines of trace that are output
+  * to a file.  Two files are used at most, when they are full, the last one is overwritten with the
+  * new trace entries.  The default size is 1000 lines.
+  *
+  * #### Trace API calls
+  *
+  * MQTTAsync_traceCallback() is used to set a callback function which is called whenever trace
+  * information is available.  This will be the same information as that printed if the
+  * environment variables were used to control the trace.
+  *
+  * The MQTTAsync_setTraceLevel() calls is used to set the maximum level of trace entries that will be
+  * passed to the callback function.  The levels are:
+  * 1. ::MQTTASYNC_TRACE_MAXIMUM
+  * 2. ::MQTTASYNC_TRACE_MEDIUM
+  * 3. ::MQTTASYNC_TRACE_MINIMUM
+  * 4. ::MQTTASYNC_TRACE_PROTOCOL
+  * 5. ::MQTTASYNC_TRACE_ERROR
+  * 6. ::MQTTASYNC_TRACE_SEVERE
+  * 7. ::MQTTASYNC_TRACE_FATAL
+  *
+  * Selecting ::MQTTASYNC_TRACE_MAXIMUM will cause all trace entries at all levels to be returned.
+  * Choosing ::MQTTASYNC_TRACE_ERROR will cause ERROR, SEVERE and FATAL trace entries to be returned
+  * to the callback function.
+  *
+  * ### MQTT Packet Tracing
+  *
+  * A feature that can be very useful is printing the MQTT packets that are sent and received.  To
+  * achieve this, use the following environment variable settings:
+  * @code
+    MQTT_C_CLIENT_TRACE=ON
+    MQTT_C_CLIENT_TRACE_LEVEL=PROTOCOL
+  * @endcode
+  * The output you should see looks like this:
+  * @code
+    20130528 155936.813 3 stdout-subscriber -> CONNECT cleansession: 1 (0)
+    20130528 155936.813 3 stdout-subscriber <- CONNACK rc: 0
+    20130528 155936.813 3 stdout-subscriber -> SUBSCRIBE msgid: 1 (0)
+    20130528 155936.813 3 stdout-subscriber <- SUBACK msgid: 1
+    20130528 155941.818 3 stdout-subscriber -> DISCONNECT (0)
+  * @endcode
+  * where the fields are:
+  * 1. date
+  * 2. time
+  * 3. socket number
+  * 4. client id
+  * 5. direction (-> from client to server, <- from server to client)
+  * 6. packet details
+  *
+  * ### Default Level Tracing
+  *
+  * This is an extract of a default level trace of a call to connect:
+  * @code
+    19700101 010000.000 (1152206656) (0)> MQTTClient_connect:893
+    19700101 010000.000 (1152206656)  (1)> MQTTClient_connectURI:716
+    20130528 160447.479 Connecting to serverURI localhost:1883
+    20130528 160447.479 (1152206656)   (2)> MQTTProtocol_connect:98
+    20130528 160447.479 (1152206656)    (3)> MQTTProtocol_addressPort:48
+    20130528 160447.479 (1152206656)    (3)< MQTTProtocol_addressPort:73
+    20130528 160447.479 (1152206656)    (3)> Socket_new:599
+    20130528 160447.479 New socket 4 for localhost, port 1883
+    20130528 160447.479 (1152206656)     (4)> Socket_addSocket:163
+    20130528 160447.479 (1152206656)      (5)> Socket_setnonblocking:73
+    20130528 160447.479 (1152206656)      (5)< Socket_setnonblocking:78 (0)
+    20130528 160447.479 (1152206656)     (4)< Socket_addSocket:176 (0)
+    20130528 160447.479 (1152206656)     (4)> Socket_error:95
+    20130528 160447.479 (1152206656)     (4)< Socket_error:104 (115)
+    20130528 160447.479 Connect pending
+    20130528 160447.479 (1152206656)    (3)< Socket_new:683 (115)
+    20130528 160447.479 (1152206656)   (2)< MQTTProtocol_connect:131 (115)
+  * @endcode
+  * where the fields are:
+  * 1. date
+  * 2. time
+  * 3. thread id
+  * 4. function nesting level
+  * 5. function entry (>) or exit (<)
+  * 6. function name : line of source code file
+  * 7. return value (if there is one)
+  *
+  * ### Memory Allocation Tracing
+  *
+  * Setting the trace level to maximum causes memory allocations and frees to be traced along with
+  * the default trace entries, with messages like the following:
+  * @code
+    20130528 161819.657 Allocating 16 bytes in heap at file /home/icraggs/workspaces/mqrtc/mqttv3c/src/MQTTPacket.c line 177 ptr 0x179f930
+
+    20130528 161819.657 Freeing 16 bytes in heap at file /home/icraggs/workspaces/mqrtc/mqttv3c/src/MQTTPacket.c line 201, heap use now 896 bytes
+  * @endcode
+  * When the last MQTT client object is destroyed, if the trace is being recorded
+  * and all memory allocated by the client library has not been freed, an error message will be
+  * written to the trace.  This can help with fixing memory leaks.  The message will look like this:
+  * @code
+    20130528 163909.208 Some memory not freed at shutdown, possible memory leak
+    20130528 163909.208 Heap scan start, total 880 bytes
+    20130528 163909.208 Heap element size 32, line 354, file /home/icraggs/workspaces/mqrtc/mqttv3c/src/MQTTPacket.c, ptr 0x260cb00
+    20130528 163909.208   Content
+    20130528 163909.209 Heap scan end
+  * @endcode
+  * @endcond
+  */
+
+#if defined(__cplusplus)
+     }
+#endif
+
+#endif

+ 1980 - 0
library/include/MQTTClient.h

@@ -0,0 +1,1980 @@
+/*******************************************************************************
+ * Copyright (c) 2009, 2023 IBM Corp., Ian Craggs and others
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v2.0
+ * and Eclipse Distribution License v1.0 which accompany this distribution.
+ *
+ * The Eclipse Public License is available at
+ *    https://www.eclipse.org/legal/epl-2.0/
+ * and the Eclipse Distribution License is available at
+ *   http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ *    Ian Craggs - initial API and implementation and/or initial documentation
+ *    Ian Craggs, Allan Stockdill-Mander - SSL updates
+ *    Ian Craggs - multiple server connection support
+ *    Ian Craggs - MQTT 3.1.1 support
+ *    Ian Craggs - remove const from eyecatchers #168
+ *******************************************************************************/
+
+/**
+ * @cond MQTTClient_internal
+ * @mainpage MQTT Client Library Internals
+ * In the beginning there was one MQTT C client library, MQTTClient, as implemented in MQTTClient.c
+ * This library was designed to be easy to use for applications which didn't mind if some of the calls
+ * blocked for a while.  For instance, the MQTTClient_connect call will block until a successful
+ * connection has completed, or a connection has failed, which could be as long as the "connection
+ * timeout" interval, whose default is 30 seconds.
+ *
+ * However in mobile devices and other windowing environments, blocking on the GUI thread is a bad
+ * thing as it causes the user interface to freeze.  Hence a new API, MQTTAsync, implemented
+ * in MQTTAsync.c, was devised.  There are no blocking calls in this library, so it is well suited
+ * to GUI and mobile environments, at the expense of some extra complexity.
+ *
+ * Both libraries are designed to be sparing in the use of threads.  So multiple client objects are
+ * handled by one or two threads, with a select call in Socket_getReadySocket(), used to determine
+ * when a socket has incoming data.  This API is thread safe: functions may be called by multiple application
+ * threads, with the exception of ::MQTTClient_yield and ::MQTTClient_receive, which are intended
+ * for single threaded environments only.
+ *
+ * @endcond
+ * @cond MQTTClient_main
+ * @mainpage MQTT Client library for C (MQTTClient)
+ * &copy; Copyright 2009, 2023 IBM Corp., Ian Craggs and others
+ *
+ * @brief An MQTT client library in C.
+ *
+ * These pages describe the original more synchronous API which might be
+ * considered easier to use.  Some of the calls will block.  For the new
+ * totally asynchronous API where no calls block, which is especially suitable
+ * for use in windowed environments, see the
+ * <a href="../../MQTTAsync/html/index.html">MQTT C Client Asynchronous API Documentation</a>.
+ * The MQTTClient API is not thread safe, whereas the MQTTAsync API is.
+ *
+ * An MQTT client application connects to MQTT-capable servers.
+ * A typical client is responsible for collecting information from a telemetry
+ * device and publishing the information to the server. It can also subscribe
+ * to topics, receive messages, and use this information to control the
+ * telemetry device.
+ *
+ * MQTT clients implement the published MQTT v3 protocol. You can write your own
+ * API to the MQTT protocol using the programming language and platform of your
+ * choice. This can be time-consuming and error-prone.
+ *
+ * To simplify writing MQTT client applications, this library encapsulates
+ * the MQTT v3 protocol for you. Using this library enables a fully functional
+ * MQTT client application to be written in a few lines of code.
+ * The information presented here documents the API provided
+ * by the MQTT Client library for C.
+ *
+ * <b>Using the client</b><br>
+ * Applications that use the client library typically use a similar structure:
+ * <ul>
+ * <li>Create a client object</li>
+ * <li>Set the options to connect to an MQTT server</li>
+ * <li>Set up callback functions if multi-threaded (asynchronous mode)
+ * operation is being used (see @ref async).</li>
+ * <li>Subscribe to any topics the client needs to receive</li>
+ * <li>Repeat until finished:</li>
+ *     <ul>
+ *     <li>Publish any messages the client needs to</li>
+ *     <li>Handle any incoming messages</li>
+ *     </ul>
+ * <li>Disconnect the client</li>
+ * <li>Free any memory being used by the client</li>
+ * </ul>
+ * Some simple examples are shown here:
+ * <ul>
+ * <li>@ref pubsync</li>
+ * <li>@ref pubasync</li>
+ * <li>@ref subasync</li>
+ * </ul>
+ * Additional information about important concepts is provided here:
+ * <ul>
+ * <li>@ref async</li>
+ * <li>@ref callbacks</li>
+ * <li>@ref wildcard</li>
+ * <li>@ref qos</li>
+ * <li>@ref tracing</li>
+ * </ul>
+ * @endcond
+ */
+
+/*
+/// @cond EXCLUDE
+*/
+#if !defined(MQTTCLIENT_H)
+#define MQTTCLIENT_H
+
+#if defined(__cplusplus)
+ extern "C" {
+#endif
+
+#include <stdio.h>
+/*
+/// @endcond
+*/
+
+#include "MQTTExportDeclarations.h"
+
+#include "MQTTProperties.h"
+#include "MQTTReasonCodes.h"
+#include "MQTTSubscribeOpts.h"
+#if !defined(NO_PERSISTENCE)
+#include "MQTTClientPersistence.h"
+#endif
+
+/**
+ * Return code: No error. Indicates successful completion of an MQTT client
+ * operation.
+ */
+#define MQTTCLIENT_SUCCESS 0
+/**
+ * Return code: A generic error code indicating the failure of an MQTT client
+ * operation.
+ */
+#define MQTTCLIENT_FAILURE -1
+
+/* error code -2 is MQTTCLIENT_PERSISTENCE_ERROR */
+
+/**
+ * Return code: The client is disconnected.
+ */
+#define MQTTCLIENT_DISCONNECTED -3
+/**
+ * Return code: The maximum number of messages allowed to be simultaneously
+ * in-flight has been reached.
+ */
+#define MQTTCLIENT_MAX_MESSAGES_INFLIGHT -4
+/**
+ * Return code: An invalid UTF-8 string has been detected.
+ */
+#define MQTTCLIENT_BAD_UTF8_STRING -5
+/**
+ * Return code: A NULL parameter has been supplied when this is invalid.
+ */
+#define MQTTCLIENT_NULL_PARAMETER -6
+/**
+ * Return code: The topic has been truncated (the topic string includes
+ * embedded NULL characters). String functions will not access the full topic.
+ * Use the topic length value to access the full topic.
+ */
+#define MQTTCLIENT_TOPICNAME_TRUNCATED -7
+/**
+ * Return code: A structure parameter does not have the correct eyecatcher
+ * and version number.
+ */
+#define MQTTCLIENT_BAD_STRUCTURE -8
+/**
+ * Return code: A QoS value that falls outside of the acceptable range (0,1,2)
+ */
+#define MQTTCLIENT_BAD_QOS -9
+/**
+ * Return code: Attempting SSL connection using non-SSL version of library
+ */
+#define MQTTCLIENT_SSL_NOT_SUPPORTED -10
+ /**
+  * Return code: unrecognized MQTT version
+  */
+ #define MQTTCLIENT_BAD_MQTT_VERSION -11
+/**
+ * Return code: protocol prefix in serverURI should be:
+ * @li @em tcp:// or @em mqtt:// - Insecure TCP
+ * @li @em ssl:// or @em mqtts:// - Encrypted SSL/TLS
+ * @li @em ws:// - Insecure websockets
+ * @li @em wss:// - Secure web sockets
+ * The TLS enabled prefixes (ssl, mqtts, wss) are only valid if a TLS
+ * version of the library is linked with.
+ */
+#define MQTTCLIENT_BAD_PROTOCOL -14
+ /**
+  * Return code: option not applicable to the requested version of MQTT
+  */
+ #define MQTTCLIENT_BAD_MQTT_OPTION -15
+ /**
+  * Return code: call not applicable to the requested version of MQTT
+  */
+ #define MQTTCLIENT_WRONG_MQTT_VERSION -16
+ /**
+  * Return code: 0 length will topic on connect
+  */
+ #define MQTTCLIENT_0_LEN_WILL_TOPIC -17
+
+
+/**
+ * Default MQTT version to connect with.  Use 3.1.1 then fall back to 3.1
+ */
+#define MQTTVERSION_DEFAULT 0
+/**
+ * MQTT version to connect with: 3.1
+ */
+#define MQTTVERSION_3_1 3
+/**
+ * MQTT version to connect with: 3.1.1
+ */
+#define MQTTVERSION_3_1_1 4
+ /**
+  * MQTT version to connect with: 5
+  */
+ #define MQTTVERSION_5 5
+/**
+ * Bad return code from subscribe, as defined in the 3.1.1 specification
+ */
+#define MQTT_BAD_SUBSCRIBE 0x80
+
+/**
+ *  Initialization options
+ */
+typedef struct
+{
+	/** The eyecatcher for this structure.  Must be MQTG. */
+	char struct_id[4];
+	/** The version number of this structure.  Must be 0 */
+	int struct_version;
+	/** 1 = we do openssl init, 0 = leave it to the application */
+	int do_openssl_init;
+} MQTTClient_init_options;
+
+#define MQTTClient_init_options_initializer { {'M', 'Q', 'T', 'G'}, 0, 0 }
+
+/**
+ * Global init of mqtt library. Call once on program start to set global behaviour.
+ * do_openssl_init - if mqtt library should initialize OpenSSL (1) or rely on the caller to do it before using the library (0)
+ */
+LIBMQTT_API void MQTTClient_global_init(MQTTClient_init_options* inits);
+
+/**
+ * A handle representing an MQTT client. A valid client handle is available
+ * following a successful call to MQTTClient_create().
+ */
+typedef void* MQTTClient;
+/**
+ * A value representing an MQTT message. A delivery token is returned to the
+ * client application when a message is published. The token can then be used to
+ * check that the message was successfully delivered to its destination (see
+ * MQTTClient_publish(),
+ * MQTTClient_publishMessage(),
+ * MQTTClient_deliveryComplete(),
+ * MQTTClient_waitForCompletion() and
+ * MQTTClient_getPendingDeliveryTokens()).
+ */
+typedef int MQTTClient_deliveryToken;
+typedef int MQTTClient_token;
+
+/**
+ * A structure representing the payload and attributes of an MQTT message. The
+ * message topic is not part of this structure (see MQTTClient_publishMessage(),
+ * MQTTClient_publish(), MQTTClient_receive(), MQTTClient_freeMessage()
+ * and MQTTClient_messageArrived()).
+ */
+typedef struct
+{
+	/** The eyecatcher for this structure.  must be MQTM. */
+	char struct_id[4];
+	/** The version number of this structure.  Must be 0 or 1
+	 *  0 indicates no message properties */
+	int struct_version;
+	/** The length of the MQTT message payload in bytes. */
+	int payloadlen;
+	/** A pointer to the payload of the MQTT message. */
+	void* payload;
+	/**
+     * The quality of service (QoS) assigned to the message.
+     * There are three levels of QoS:
+     * <DL>
+     * <DT><B>QoS0</B></DT>
+     * <DD>Fire and forget - the message may not be delivered</DD>
+     * <DT><B>QoS1</B></DT>
+     * <DD>At least once - the message will be delivered, but may be
+     * delivered more than once in some circumstances.</DD>
+     * <DT><B>QoS2</B></DT>
+     * <DD>Once and one only - the message will be delivered exactly once.</DD>
+     * </DL>
+     */
+	int qos;
+	/**
+     * The retained flag serves two purposes depending on whether the message
+     * it is associated with is being published or received.
+     *
+     * <b>retained = true</b><br>
+     * For messages being published, a true setting indicates that the MQTT
+     * server should retain a copy of the message. The message will then be
+     * transmitted to new subscribers to a topic that matches the message topic.
+     * For subscribers registering a new subscription, the flag being true
+     * indicates that the received message is not a new one, but one that has
+     * been retained by the MQTT server.
+     *
+     * <b>retained = false</b> <br>
+     * For publishers, this indicates that this message should not be retained
+     * by the MQTT server. For subscribers, a false setting indicates this is
+     * a normal message, received as a result of it being published to the
+     * server.
+     */
+	int retained;
+	/**
+      * The dup flag indicates whether or not this message is a duplicate.
+      * It is only meaningful when receiving QoS1 messages. When true, the
+      * client application should take appropriate action to deal with the
+      * duplicate message.
+      */
+	int dup;
+	/** The message identifier is normally reserved for internal use by the
+      * MQTT client and server.
+      */
+	int msgid;
+	/**
+	 * The MQTT V5 properties associated with the message.
+	 */
+	MQTTProperties properties;
+} MQTTClient_message;
+
+#define MQTTClient_message_initializer { {'M', 'Q', 'T', 'M'}, 1, 0, NULL, 0, 0, 0, 0, MQTTProperties_initializer }
+
+/**
+ * This is a callback function. The client application
+ * must provide an implementation of this function to enable asynchronous
+ * receipt of messages. The function is registered with the client library by
+ * passing it as an argument to MQTTClient_setCallbacks(). It is
+ * called by the client library when a new message that matches a client
+ * subscription has been received from the server. This function is executed on
+ * a separate thread to the one on which the client application is running.
+ * @param context A pointer to the <i>context</i> value originally passed to
+ * MQTTClient_setCallbacks(), which contains any application-specific context.
+ * @param topicName The topic associated with the received message.
+ * @param topicLen The length of the topic if there are one
+ * more NULL characters embedded in <i>topicName</i>, otherwise <i>topicLen</i>
+ * is 0. If <i>topicLen</i> is 0, the value returned by <i>strlen(topicName)</i>
+ * can be trusted. If <i>topicLen</i> is greater than 0, the full topic name
+ * can be retrieved by accessing <i>topicName</i> as a byte array of length
+ * <i>topicLen</i>.
+ * @param message The MQTTClient_message structure for the received message.
+ * This structure contains the message payload and attributes.
+ * @return This function must return 0 or 1 indicating whether or not
+ * the message has been safely received by the client application. <br>
+ * Returning 1 indicates that the message has been successfully handled.
+ * To free the message storage, ::MQTTClient_freeMessage must be called.
+ * To free the topic name storage, ::MQTTClient_free must be called.<br>
+ * Returning 0 indicates that there was a problem. In this
+ * case, the client library will reinvoke MQTTClient_messageArrived() to
+ * attempt to deliver the message to the application again.
+ * Do not free the message and topic storage when returning 0, otherwise
+ * the redelivery will fail.
+ */
+typedef int MQTTClient_messageArrived(void* context, char* topicName, int topicLen, MQTTClient_message* message);
+
+/**
+ * This is a callback function. The client application
+ * must provide an implementation of this function to enable asynchronous
+ * notification of delivery of messages. The function is registered with the
+ * client library by passing it as an argument to MQTTClient_setCallbacks().
+ * It is called by the client library after the client application has
+ * published a message to the server. It indicates that the necessary
+ * handshaking and acknowledgements for the requested quality of service (see
+ * MQTTClient_message.qos) have been completed. This function is executed on a
+ * separate thread to the one on which the client application is running.
+ * <b>Note:</b>MQTTClient_deliveryComplete() is not called when messages are
+ * published at QoS0.
+ * @param context A pointer to the <i>context</i> value originally passed to
+ * MQTTClient_setCallbacks(), which contains any application-specific context.
+ * @param dt The ::MQTTClient_deliveryToken associated with
+ * the published message. Applications can check that all messages have been
+ * correctly published by matching the delivery tokens returned from calls to
+ * MQTTClient_publish() and MQTTClient_publishMessage() with the tokens passed
+ * to this callback.
+ */
+typedef void MQTTClient_deliveryComplete(void* context, MQTTClient_deliveryToken dt);
+
+/**
+ * This is a callback function. The client application
+ * must provide an implementation of this function to enable asynchronous
+ * notification of the loss of connection to the server. The function is
+ * registered with the client library by passing it as an argument to
+ * MQTTClient_setCallbacks(). It is called by the client library if the client
+ * loses its connection to the server. The client application must take
+ * appropriate action, such as trying to reconnect or reporting the problem.
+ * This function is executed on a separate thread to the one on which the
+ * client application is running.
+ * @param context A pointer to the <i>context</i> value originally passed to
+ * MQTTClient_setCallbacks(), which contains any application-specific context.
+ * @param cause The reason for the disconnection.
+ * Currently, <i>cause</i> is always set to NULL.
+ */
+typedef void MQTTClient_connectionLost(void* context, char* cause);
+
+/**
+ * This function sets the callback functions for a specific client.
+ * If your client application doesn't use a particular callback, set the
+ * relevant parameter to NULL. Calling MQTTClient_setCallbacks() puts the
+ * client into multi-threaded mode. Any necessary message acknowledgements and
+ * status communications are handled in the background without any intervention
+ * from the client application. See @ref async for more information.
+ *
+ * <b>Note:</b> The MQTT client must be disconnected when this function is
+ * called.
+ * @param handle A valid client handle from a successful call to
+ * MQTTClient_create().
+ * @param context A pointer to any application-specific context. The
+ * the <i>context</i> pointer is passed to each of the callback functions to
+ * provide access to the context information in the callback.
+ * @param cl A pointer to an MQTTClient_connectionLost() callback
+ * function. You can set this to NULL if your application doesn't handle
+ * disconnections.
+ * @param ma A pointer to an MQTTClient_messageArrived() callback
+ * function. This callback function must be set when you call
+ * MQTTClient_setCallbacks(), as otherwise there would be nowhere to deliver
+ * any incoming messages.
+ * @param dc A pointer to an MQTTClient_deliveryComplete() callback
+ * function. You can set this to NULL if your application publishes
+ * synchronously or if you do not want to check for successful delivery.
+ * @return ::MQTTCLIENT_SUCCESS if the callbacks were correctly set,
+ * ::MQTTCLIENT_FAILURE if an error occurred.
+ */
+LIBMQTT_API int MQTTClient_setCallbacks(MQTTClient handle, void* context, MQTTClient_connectionLost* cl,
+									MQTTClient_messageArrived* ma, MQTTClient_deliveryComplete* dc);
+
+
+/**
+ * This is a callback function, which will be called when the a disconnect
+ * packet is received from the server.  This applies to MQTT V5 and above only.
+ * @param context A pointer to the <i>context</i> value originally passed to
+ * ::MQTTClient_setDisconnected(), which contains any application-specific context.
+ * @param properties The MQTT V5 properties received with the disconnect, if any.
+ * @param reasonCode The MQTT V5 reason code received with the disconnect.
+ * Currently, <i>cause</i> is always set to NULL.
+ */
+typedef void MQTTClient_disconnected(void* context, MQTTProperties* properties,
+		enum MQTTReasonCodes reasonCode);
+
+/**
+ * Sets the MQTTClient_disconnected() callback function for a client.  This will be called
+ * if a disconnect packet is received from the server.  Only valid for MQTT V5 and above.
+ * @param handle A valid client handle from a successful call to
+ * MQTTClient_create().
+ * @param context A pointer to any application-specific context. The
+ * the <i>context</i> pointer is passed to each of the callback functions to
+ * provide access to the context information in the callback.
+ * @param co A pointer to an MQTTClient_disconnected() callback
+ * function.  NULL removes the callback setting.
+ * @return ::MQTTCLIENT_SUCCESS if the callbacks were correctly set,
+ * ::MQTTCLIENT_FAILURE if an error occurred.
+ */
+LIBMQTT_API int MQTTClient_setDisconnected(MQTTClient handle, void* context, MQTTClient_disconnected* co);
+
+/**
+ * This is a callback function, the MQTT V5 version of MQTTClient_deliveryComplete().
+ * The client application
+ * must provide an implementation of this function to enable asynchronous
+ * notification of the completed delivery of messages.
+ * It is called by the client library after the client application has
+ * published a message to the server. It indicates that the necessary
+ * handshaking and acknowledgements for the requested quality of service (see
+ * MQTTClient_message.qos) have been completed. This function is executed on a
+ * separate thread to the one on which the client application is running.
+ * <b>Note:</b> It is not called when messages are published at QoS0.
+ * @param context A pointer to the <i>context</i> value originally passed to
+ * MQTTClient_setCallbacks(), which contains any application-specific context.
+ * @param dt The ::MQTTClient_deliveryToken associated with
+ * the published message. Applications can check that all messages have been
+ * correctly published by matching the delivery tokens returned from calls to
+ * MQTTClient_publish() and MQTTClient_publishMessage() with the tokens passed
+ * to this callback.
+ * @param packet_type the last received packet type for this completion. For QoS 1
+ * always PUBACK.  For QoS 2 could be PUBREC or PUBCOMP.
+ * @param properties the MQTT V5 properties returned with the last packet from the server
+ * @param reasonCode the reason code returned from the server
+ */
+typedef void MQTTClient_published(void* context, int dt, int packet_type, MQTTProperties* properties,
+		enum MQTTReasonCodes reasonCode);
+
+LIBMQTT_API int MQTTClient_setPublished(MQTTClient handle, void* context, MQTTClient_published* co);
+
+/**
+ * This function creates an MQTT client ready for connection to the
+ * specified server and using the specified persistent storage (see
+ * MQTTClient_persistence). See also MQTTClient_destroy().
+ * @param handle A pointer to an ::MQTTClient handle. The handle is
+ * populated with a valid client reference following a successful return from
+ * this function.
+ * @param serverURI A null-terminated string specifying the server to
+ * which the client will connect. It takes the form <i>protocol://host:port</i>.
+ * Currently, <i>protocol</i> must be:
+ * <br>
+ * @em tcp:// or @em mqtt:// - Insecure TCP
+ * <br>
+ * @em ssl:// or @em mqtts:// - Encrypted SSL/TLS
+ * <br>
+ * @em ws:// - Insecure websockets
+ * <br>
+ * @em wss:// - Secure web sockets
+ * <br>
+ * The TLS enabled prefixes (ssl, mqtts, wss) are only valid if a TLS
+ * version of the library is linked with.
+ * For <i>host</i>, you can specify either an IP address or a host name. For
+ * instance, to connect to a server running on the local machines with the
+ * default MQTT port, specify <i>tcp://localhost:1883</i>.
+ * @param clientId The client identifier passed to the server when the
+ * client connects to it. It is a null-terminated UTF-8 encoded string.
+ * @param persistence_type The type of persistence to be used by the client:
+ * <br>
+ * ::MQTTCLIENT_PERSISTENCE_NONE: Use in-memory persistence. If the device or
+ * system on which the client is running fails or is switched off, the current
+ * state of any in-flight messages is lost and some messages may not be
+ * delivered even at QoS1 and QoS2.
+ * <br>
+ * ::MQTTCLIENT_PERSISTENCE_DEFAULT: Use the default (file system-based)
+ * persistence mechanism. Status about in-flight messages is held in persistent
+ * storage and provides some protection against message loss in the case of
+ * unexpected failure.
+ * <br>
+ * ::MQTTCLIENT_PERSISTENCE_USER: Use an application-specific persistence
+ * implementation. Using this type of persistence gives control of the
+ * persistence mechanism to the application. The application has to implement
+ * the MQTTClient_persistence interface.
+ * @param persistence_context If the application uses
+ * ::MQTTCLIENT_PERSISTENCE_NONE persistence, this argument is unused and should
+ * be set to NULL. For ::MQTTCLIENT_PERSISTENCE_DEFAULT persistence, it
+ * should be set to the location of the persistence directory (if set
+ * to NULL, the persistence directory used is the working directory).
+ * Applications that use ::MQTTCLIENT_PERSISTENCE_USER persistence set this
+ * argument to point to a valid MQTTClient_persistence structure.
+ * @return ::MQTTCLIENT_SUCCESS if the client is successfully created, otherwise
+ * an error code is returned.
+ */
+LIBMQTT_API int MQTTClient_create(MQTTClient* handle, const char* serverURI, const char* clientId,
+		int persistence_type, void* persistence_context);
+
+/** Options for the ::MQTTClient_createWithOptions call */
+typedef struct
+{
+	/** The eyecatcher for this structure.  must be MQCO. */
+	char struct_id[4];
+	/** The version number of this structure.  Must be 0 */
+	int struct_version;
+	/** Whether the MQTT version is 3.1, 3.1.1, or 5.  To use V5, this must be set.
+	 *  MQTT V5 has to be chosen here, because during the create call the message persistence
+	 *  is initialized, and we want to know whether the format of any persisted messages
+	 *  is appropriate for the MQTT version we are going to connect with.  Selecting 3.1 or
+	 *  3.1.1 and attempting to read 5.0 persisted messages will result in an error on create.  */
+	int MQTTVersion;
+} MQTTClient_createOptions;
+
+#define MQTTClient_createOptions_initializer { {'M', 'Q', 'C', 'O'}, 0, MQTTVERSION_DEFAULT }
+
+/**
+ * A version of :MQTTClient_create() with additional options.
+ * This function creates an MQTT client ready for connection to the
+ * specified server and using the specified persistent storage (see
+ * MQTTClient_persistence). See also MQTTClient_destroy().
+ * @param handle A pointer to an ::MQTTClient handle. The handle is
+ * populated with a valid client reference following a successful return from
+ * this function.
+ * @param serverURI A null-terminated string specifying the server to
+ * which the client will connect. It takes the form <i>protocol://host:port</i>.
+ * Currently, <i>protocol</i> must be <i>tcp</i> or <i>ssl</i>.
+ * For <i>host</i>, you can
+ * specify either an IP address or a host name. For instance, to connect to
+ * a server running on the local machines with the default MQTT port, specify
+ * <i>tcp://localhost:1883</i>.
+ * @param clientId The client identifier passed to the server when the
+ * client connects to it. It is a null-terminated UTF-8 encoded string.
+ * @param persistence_type The type of persistence to be used by the client:
+ * <br>
+ * ::MQTTCLIENT_PERSISTENCE_NONE: Use in-memory persistence. If the device or
+ * system on which the client is running fails or is switched off, the current
+ * state of any in-flight messages is lost and some messages may not be
+ * delivered even at QoS1 and QoS2.
+ * <br>
+ * ::MQTTCLIENT_PERSISTENCE_DEFAULT: Use the default (file system-based)
+ * persistence mechanism. Status about in-flight messages is held in persistent
+ * storage and provides some protection against message loss in the case of
+ * unexpected failure.
+ * <br>
+ * ::MQTTCLIENT_PERSISTENCE_USER: Use an application-specific persistence
+ * implementation. Using this type of persistence gives control of the
+ * persistence mechanism to the application. The application has to implement
+ * the MQTTClient_persistence interface.
+ * @param persistence_context If the application uses
+ * ::MQTTCLIENT_PERSISTENCE_NONE persistence, this argument is unused and should
+ * be set to NULL. For ::MQTTCLIENT_PERSISTENCE_DEFAULT persistence, it
+ * should be set to the location of the persistence directory (if set
+ * to NULL, the persistence directory used is the working directory).
+ * Applications that use ::MQTTCLIENT_PERSISTENCE_USER persistence set this
+ * argument to point to a valid MQTTClient_persistence structure.
+ * @param options additional options for the create.
+ * @return ::MQTTCLIENT_SUCCESS if the client is successfully created, otherwise
+ * an error code is returned.
+ */
+LIBMQTT_API int MQTTClient_createWithOptions(MQTTClient* handle, const char* serverURI, const char* clientId,
+		int persistence_type, void* persistence_context, MQTTClient_createOptions* options);
+
+/**
+ * MQTTClient_willOptions defines the MQTT "Last Will and Testament" (LWT) settings for
+ * the client. In the event that a client unexpectedly loses its connection to
+ * the server, the server publishes the LWT message to the LWT topic on
+ * behalf of the client. This allows other clients (subscribed to the LWT topic)
+ * to be made aware that the client has disconnected. To enable the LWT
+ * function for a specific client, a valid pointer to an MQTTClient_willOptions
+ * structure is passed in the MQTTClient_connectOptions structure used in the
+ * MQTTClient_connect() call that connects the client to the server. The pointer
+ * to MQTTClient_willOptions can be set to NULL if the LWT function is not
+ * required.
+ */
+typedef struct
+{
+	/** The eyecatcher for this structure.  must be MQTW. */
+	char struct_id[4];
+	/** The version number of this structure.  Must be 0 or 1
+		   0 means there is no binary payload option
+	 */
+	int struct_version;
+	/** The LWT topic to which the LWT message will be published. */
+	const char* topicName;
+	/** The LWT payload in string form. */
+	const char* message;
+	/**
+	 * The retained flag for the LWT message (see MQTTClient_message.retained).
+	 */
+	int retained;
+	/**
+	 * The quality of service setting for the LWT message (see
+	 * MQTTClient_message.qos and @ref qos).
+	 */
+	int qos;
+  /** The LWT payload in binary form. This is only checked and used if the message option is NULL */
+	struct
+	{
+		int len;            /**< binary payload length */
+		const void* data;  /**< binary payload data */
+	} payload;
+} MQTTClient_willOptions;
+
+#define MQTTClient_willOptions_initializer { {'M', 'Q', 'T', 'W'}, 1, NULL, NULL, 0, 0, {0, NULL} }
+
+#define MQTT_SSL_VERSION_DEFAULT 0
+#define MQTT_SSL_VERSION_TLS_1_0 1
+#define MQTT_SSL_VERSION_TLS_1_1 2
+#define MQTT_SSL_VERSION_TLS_1_2 3
+
+/**
+* MQTTClient_sslProperties defines the settings to establish an SSL/TLS connection using the
+* OpenSSL library. It covers the following scenarios:
+* - Server authentication: The client needs the digital certificate of the server. It is included
+*   in a store containting trusted material (also known as "trust store").
+* - Mutual authentication: Both client and server are authenticated during the SSL handshake. In
+*   addition to the digital certificate of the server in a trust store, the client will need its own
+*   digital certificate and the private key used to sign its digital certificate stored in a "key store".
+* - Anonymous connection: Both client and server do not get authenticated and no credentials are needed
+*   to establish an SSL connection. Note that this scenario is not fully secure since it is subject to
+*   man-in-the-middle attacks.
+*/
+typedef struct
+{
+	/** The eyecatcher for this structure.  Must be MQTS */
+	char struct_id[4];
+
+	/** The version number of this structure. Must be 0, 1, 2, 3, 4 or 5.
+	 * 0 means no sslVersion
+	 * 1 means no verify, CApath
+	 * 2 means no ssl_error_context, ssl_error_cb
+	 * 3 means no ssl_psk_cb, ssl_psk_context, disableDefaultTrustStore
+	 * 4 means no protos, protos_len
+	 */
+	int struct_version;
+
+	/** The file in PEM format containing the public digital certificates trusted by the client. */
+	const char* trustStore;
+
+	/** The file in PEM format containing the public certificate chain of the client. It may also include
+	* the client's private key.
+	*/
+	const char* keyStore;
+
+	/** If not included in the sslKeyStore, this setting points to the file in PEM format containing
+	* the client's private key.
+	*/
+	const char* privateKey;
+
+	/** The password to load the client's privateKey if encrypted. */
+	const char* privateKeyPassword;
+
+	/**
+	* The list of cipher suites that the client will present to the server during the SSL handshake. For a
+	* full explanation of the cipher list format, please see the OpenSSL on-line documentation:
+	* http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT
+	* If this setting is ommitted, its default value will be "ALL", that is, all the cipher suites -excluding
+	* those offering no encryption- will be considered.
+	* This setting can be used to set an SSL anonymous connection ("aNULL" string value, for instance).
+	*/
+	const char* enabledCipherSuites;
+
+    /** True/False option to enable verification of the server certificate **/
+    int enableServerCertAuth;
+
+    /** The SSL/TLS version to use. Specify one of MQTT_SSL_VERSION_DEFAULT (0),
+    * MQTT_SSL_VERSION_TLS_1_0 (1), MQTT_SSL_VERSION_TLS_1_1 (2) or MQTT_SSL_VERSION_TLS_1_2 (3).
+    * Only used if struct_version is >= 1.
+    */
+    int sslVersion;
+
+    /**
+     * Whether to carry out post-connect checks, including that a certificate
+     * matches the given host name.
+     * Exists only if struct_version >= 2
+     */
+    int verify;
+
+    /**
+     * From the OpenSSL documentation:
+     * If CApath is not NULL, it points to a directory containing CA certificates in PEM format.
+     * Exists only if struct_version >= 2
+	 */
+	const char* CApath;
+
+    /**
+     * Callback function for OpenSSL error handler ERR_print_errors_cb
+     * Exists only if struct_version >= 3
+     */
+    int (*ssl_error_cb) (const char *str, size_t len, void *u);
+
+    /**
+     * Application-specific contex for OpenSSL error handler ERR_print_errors_cb
+     * Exists only if struct_version >= 3
+     */
+    void* ssl_error_context;
+
+	/**
+	 * Callback function for setting TLS-PSK options. Parameters correspond to that of
+	 * SSL_CTX_set_psk_client_callback, except for u which is the pointer ssl_psk_context.
+	 * Exists only if struct_version >= 4
+	 */
+	unsigned int (*ssl_psk_cb) (const char *hint, char *identity, unsigned int max_identity_len, unsigned char *psk, unsigned int max_psk_len, void *u);
+
+	/**
+	 * Application-specific contex for ssl_psk_cb
+	 * Exists only if struct_version >= 4
+	 */
+	void* ssl_psk_context;
+
+	/**
+	 * Don't load default SSL CA. Should be used together with PSK to make sure
+	 * regular servers with certificate in place is not accepted.
+	 * Exists only if struct_version >= 4
+	 */
+	int disableDefaultTrustStore;
+
+	/**
+	 * The protocol-lists must be in wire-format, which is defined as a vector of non-empty, 8-bit length-prefixed, byte strings.
+	 * The length-prefix byte is not included in the length. Each string is limited to 255 bytes. A byte-string length of 0 is invalid.
+	 * A truncated byte-string is invalid.
+	 * Check documentation for SSL_CTX_set_alpn_protos
+	 * Exists only if struct_version >= 5
+	 */
+	const unsigned char *protos;
+
+	/**
+	 * The length of the vector protos vector
+	 * Exists only if struct_version >= 5
+	 */
+	unsigned int protos_len;
+} MQTTClient_SSLOptions;
+
+#define MQTTClient_SSLOptions_initializer { {'M', 'Q', 'T', 'S'}, 5, NULL, NULL, NULL, NULL, NULL, 1, MQTT_SSL_VERSION_DEFAULT, 0, NULL, NULL, NULL, NULL, NULL, 0, NULL, 0 }
+
+/**
+  * MQTTClient_libraryInfo is used to store details relating to the currently used
+  * library such as the version in use, the time it was built and relevant openSSL
+  * options.
+  * There is one static instance of this struct in MQTTClient.c
+  */
+
+typedef struct
+{
+	const char* name;
+	const char* value;
+} MQTTClient_nameValue;
+
+/**
+  * This function returns version information about the library.
+  * no trace information will be returned.
+  * @return an array of strings describing the library.  The last entry is a NULL pointer.
+  */
+LIBMQTT_API MQTTClient_nameValue* MQTTClient_getVersionInfo(void);
+
+/**
+ * MQTTClient_connectOptions defines several settings that control the way the
+ * client connects to an MQTT server.
+ *
+ * <b>Note:</b> Default values are not defined for members of
+ * MQTTClient_connectOptions so it is good practice to specify all settings.
+ * If the MQTTClient_connectOptions structure is defined as an automatic
+ * variable, all members are set to random values and thus must be set by the
+ * client application. If the MQTTClient_connectOptions structure is defined
+ * as a static variable, initialization (in compliant compilers) sets all
+ * values to 0 (NULL for pointers). A #keepAliveInterval setting of 0 prevents
+ * correct operation of the client and so you <b>must</b> at least set a value
+ * for #keepAliveInterval.
+ *
+ * Suitable default values are set in the following initializers:
+ * - MQTTClient_connectOptions_initializer: for MQTT 3.1.1 non-WebSockets
+ * - MQTTClient_connectOptions_initializer5: for MQTT 5.0 non-WebSockets
+ * - MQTTClient_connectOptions_initializer_ws: for MQTT 3.1.1 WebSockets
+ * - MQTTClient_connectOptions_initializer5_ws: for MQTT 5.0 WebSockets
+ */
+typedef struct
+{
+	/** The eyecatcher for this structure.  must be MQTC. */
+	char struct_id[4];
+	/** The version number of this structure.  Must be 0, 1, 2, 3, 4, 5, 6, 7 or 8.
+	 * 0 signifies no SSL options and no serverURIs
+	 * 1 signifies no serverURIs
+	 * 2 signifies no MQTTVersion
+	 * 3 signifies no returned values
+	 * 4 signifies no binary password option
+	 * 5 signifies no maxInflightMessages and cleanstart
+	 * 6 signifies no HTTP headers option
+	 * 7 signifies no HTTP proxy and HTTPS proxy options
+	 */
+	int struct_version;
+	/** The "keep alive" interval, measured in seconds, defines the maximum time
+   * that should pass without communication between the client and the server
+   * The client will ensure that at least one message travels across the
+   * network within each keep alive period.  In the absence of a data-related
+	 * message during the time period, the client sends a very small MQTT
+   * "ping" message, which the server will acknowledge. The keep alive
+   * interval enables the client to detect when the server is no longer
+	 * available without having to wait for the long TCP/IP timeout.
+	 */
+	int keepAliveInterval;
+	/**
+   * This is a boolean value. The cleansession setting controls the behaviour
+   * of both the client and the server at connection and disconnection time.
+   * The client and server both maintain session state information. This
+   * information is used to ensure "at least once" and "exactly once"
+   * delivery, and "exactly once" receipt of messages. Session state also
+   * includes subscriptions created by an MQTT client. You can choose to
+   * maintain or discard state information between sessions.
+   *
+   * When cleansession is true, the state information is discarded at
+   * connect and disconnect. Setting cleansession to false keeps the state
+   * information. When you connect an MQTT client application with
+   * MQTTClient_connect(), the client identifies the connection using the
+   * client identifier and the address of the server. The server checks
+   * whether session information for this client
+   * has been saved from a previous connection to the server. If a previous
+   * session still exists, and cleansession=true, then the previous session
+   * information at the client and server is cleared. If cleansession=false,
+   * the previous session is resumed. If no previous session exists, a new
+   * session is started.
+	 */
+	int cleansession;
+	/**
+   * This is a boolean value that controls how many messages can be in-flight
+   * simultaneously. Setting <i>reliable</i> to true means that a published
+   * message must be completed (acknowledgements received) before another
+   * can be sent. Attempts to publish additional messages receive an
+   * ::MQTTCLIENT_MAX_MESSAGES_INFLIGHT return code. Setting this flag to
+   * false allows up to 10 messages to be in-flight. This can increase
+   * overall throughput in some circumstances.
+	 */
+	int reliable;
+	/**
+   * This is a pointer to an MQTTClient_willOptions structure. If your
+   * application does not make use of the Last Will and Testament feature,
+   * set this pointer to NULL.
+   */
+	MQTTClient_willOptions* will;
+	/**
+   * MQTT servers that support the MQTT v3.1.1 protocol provide authentication
+   * and authorisation by user name and password. This is the user name
+   * parameter.
+   */
+	const char* username;
+	/**
+   * MQTT servers that support the MQTT v3.1.1 protocol provide authentication
+   * and authorisation by user name and password. This is the password
+   * parameter.
+   */
+	const char* password;
+	/**
+   * The time interval in seconds to allow a connect to complete.
+   */
+	int connectTimeout;
+	/**
+	 * The time interval in seconds after which unacknowledged publish requests are
+	 * retried during a TCP session.  With MQTT 3.1.1 and later, retries are
+	 * not required except on reconnect.  0 turns off in-session retries, and is the
+	 * recommended setting.  Adding retries to an already overloaded network only
+	 * exacerbates the problem.
+	 */
+	int retryInterval;
+	/**
+   * This is a pointer to an MQTTClient_SSLOptions structure. If your
+   * application does not make use of SSL, set this pointer to NULL.
+   */
+	MQTTClient_SSLOptions* ssl;
+	/**
+	 * The number of entries in the optional serverURIs array. Defaults to 0.
+	 */
+	int serverURIcount;
+	/**
+   * An optional array of null-terminated strings specifying the servers to
+   * which the client will connect. Each string takes the form <i>protocol://host:port</i>.
+   * <i>protocol</i> must be <i>tcp</i>, <i>ssl</i>, <i>ws</i> or <i>wss</i>.
+   * The TLS enabled prefixes (ssl, wss) are only valid if a TLS version of the library
+   * is linked with.
+   * For <i>host</i>, you can
+   * specify either an IP address or a host name. For instance, to connect to
+   * a server running on the local machines with the default MQTT port, specify
+   * <i>tcp://localhost:1883</i>.
+   * If this list is empty (the default), the server URI specified on MQTTClient_create()
+   * is used.
+   */
+	char* const* serverURIs;
+	/**
+	 * Sets the version of MQTT to be used on the connect.
+	 * MQTTVERSION_DEFAULT (0) = default: start with 3.1.1, and if that fails, fall back to 3.1
+	 * MQTTVERSION_3_1 (3) = only try version 3.1
+	 * MQTTVERSION_3_1_1 (4) = only try version 3.1.1
+	 * MQTTVERSION_5 (5) = only try version 5.0
+	 */
+	int MQTTVersion;
+	/**
+	 * Returned from the connect when the MQTT version used to connect is 3.1.1
+	 */
+	struct
+	{
+		const char* serverURI;     /**< the serverURI connected to */
+		int MQTTVersion;     /**< the MQTT version used to connect with */
+		int sessionPresent;  /**< if the MQTT version is 3.1.1, the value of sessionPresent returned in the connack */
+	} returned;
+	/**
+   * Optional binary password.  Only checked and used if the password option is NULL
+   */
+	struct
+	{
+		int len;           /**< binary password length */
+		const void* data;  /**< binary password data */
+	} binarypwd;
+	/**
+	 * The maximum number of messages in flight
+	 */
+	int maxInflightMessages;
+	/*
+	 * MQTT V5 clean start flag.  Only clears state at the beginning of the session.
+	 */
+	int cleanstart;
+	/**
+	 * HTTP headers for websockets
+	 */
+	const MQTTClient_nameValue* httpHeaders;
+	/**
+	 * HTTP proxy
+	 */
+	const char* httpProxy;
+	/**
+	 * HTTPS proxy
+	 */
+	const char* httpsProxy;
+} MQTTClient_connectOptions;
+
+/** Initializer for connect options for MQTT 3.1.1 non-WebSocket connections */
+#define MQTTClient_connectOptions_initializer { {'M', 'Q', 'T', 'C'}, 8, 60, 1, 1, NULL, NULL, NULL, 30, 0, NULL,\
+0, NULL, MQTTVERSION_DEFAULT, {NULL, 0, 0}, {0, NULL}, -1, 0, NULL, NULL, NULL}
+
+/** Initializer for connect options for MQTT 5.0 non-WebSocket connections */
+#define MQTTClient_connectOptions_initializer5 { {'M', 'Q', 'T', 'C'}, 8, 60, 0, 1, NULL, NULL, NULL, 30, 0, NULL,\
+0, NULL, MQTTVERSION_5, {NULL, 0, 0}, {0, NULL}, -1, 1, NULL, NULL, NULL}
+
+/** Initializer for connect options for MQTT 3.1.1 WebSockets connections.
+  * The keepalive interval is set to 45 seconds to avoid webserver 60 second inactivity timeouts.
+  */
+#define MQTTClient_connectOptions_initializer_ws { {'M', 'Q', 'T', 'C'}, 8, 45, 1, 1, NULL, NULL, NULL, 30, 0, NULL,\
+0, NULL, MQTTVERSION_DEFAULT, {NULL, 0, 0}, {0, NULL}, -1, 0, NULL, NULL, NULL}
+
+/** Initializer for connect options for MQTT 5.0 WebSockets connections.
+  * The keepalive interval is set to 45 seconds to avoid webserver 60 second inactivity timeouts.
+  */
+#define MQTTClient_connectOptions_initializer5_ws { {'M', 'Q', 'T', 'C'}, 8, 45, 0, 1, NULL, NULL, NULL, 30, 0, NULL,\
+0, NULL, MQTTVERSION_5, {NULL, 0, 0}, {0, NULL}, -1, 1, NULL, NULL, NULL}
+
+/**
+  * This function attempts to connect a previously-created client (see
+  * MQTTClient_create()) to an MQTT server using the specified options. If you
+  * want to enable asynchronous message and status notifications, you must call
+  * MQTTClient_setCallbacks() prior to MQTTClient_connect().
+  * @param handle A valid client handle from a successful call to
+  * MQTTClient_create().
+  * @param options A pointer to a valid MQTTClient_connectOptions
+  * structure.
+  * @return ::MQTTCLIENT_SUCCESS if the client successfully connects to the
+  * server. An error code is returned if the client was unable to connect to
+  * the server.
+  * Error codes greater than 0 are returned by the MQTT protocol:<br><br>
+  * <b>1</b>: Connection refused: Unacceptable protocol version<br>
+  * <b>2</b>: Connection refused: Identifier rejected<br>
+  * <b>3</b>: Connection refused: Server unavailable<br>
+  * <b>4</b>: Connection refused: Bad user name or password<br>
+  * <b>5</b>: Connection refused: Not authorized<br>
+  * <b>6-255</b>: Reserved for future use<br>
+  */
+LIBMQTT_API int MQTTClient_connect(MQTTClient handle, MQTTClient_connectOptions* options);
+
+/** MQTT version 5.0 response information */
+typedef struct MQTTResponse
+{
+	int version;                        /* the version number of this structure */
+	enum MQTTReasonCodes reasonCode;    /* the MQTT 5.0 reason code returned */
+	int reasonCodeCount;	            /* the number of reason codes.  Used for subscribeMany5 and unsubscribeMany5 */
+	enum MQTTReasonCodes* reasonCodes;  /* a list of reason codes.  Used for subscribeMany5 and unsubscribeMany5 */
+	MQTTProperties* properties;         /* optionally, the MQTT 5.0 properties returned */
+} MQTTResponse;
+
+#define MQTTResponse_initializer {1, MQTTREASONCODE_SUCCESS, 0, NULL, NULL}
+
+/**
+ * Frees the storage associated with the MQTT response.
+ * @param response the response structure to be freed
+ */
+LIBMQTT_API void MQTTResponse_free(MQTTResponse response);
+
+/**
+  * Attempts to connect a previously-created client (see
+  * MQTTClient_create()) to an MQTT server using MQTT version 5.0 and the specified options. If you
+  * want to enable asynchronous message and status notifications, you must call
+  * MQTTClient_setCallbacks() prior to MQTTClient_connect().
+  * @param handle A valid client handle from a successful call to
+  * MQTTClient_create().
+  * @param options A pointer to a valid MQTTClient_connectOptions
+  * structure.
+  * @param connectProperties the MQTT 5.0 connect properties to use
+  * @param willProperties the MQTT 5.0 properties to set on the will message
+  * @return the MQTT 5.0 response information: error codes and properties.
+  */
+LIBMQTT_API MQTTResponse MQTTClient_connect5(MQTTClient handle, MQTTClient_connectOptions* options,
+		MQTTProperties* connectProperties, MQTTProperties* willProperties);
+
+/**
+  * This function attempts to disconnect the client from the MQTT
+  * server. In order to allow the client time to complete handling of messages
+  * that are in-flight when this function is called, a timeout period is
+  * specified. When the timeout period has expired, the client disconnects even
+  * if there are still outstanding message acknowledgements.
+  * The next time the client connects to the same server, any QoS 1 or 2
+  * messages which have not completed will be retried depending on the
+  * cleansession settings for both the previous and the new connection (see
+  * MQTTClient_connectOptions.cleansession and MQTTClient_connect()).
+  * @param handle A valid client handle from a successful call to
+  * MQTTClient_create().
+  * @param timeout The client delays disconnection for up to this time (in
+  * milliseconds) in order to allow in-flight message transfers to complete.
+  * @return ::MQTTCLIENT_SUCCESS if the client successfully disconnects from
+  * the server. An error code is returned if the client was unable to disconnect
+  * from the server
+  */
+LIBMQTT_API int MQTTClient_disconnect(MQTTClient handle, int timeout);
+
+LIBMQTT_API int MQTTClient_disconnect5(MQTTClient handle, int timeout, enum MQTTReasonCodes reason, MQTTProperties* props);
+
+/**
+  * This function allows the client application to test whether or not a
+  * client is currently connected to the MQTT server.
+  * @param handle A valid client handle from a successful call to
+  * MQTTClient_create().
+  * @return Boolean true if the client is connected, otherwise false.
+  */
+LIBMQTT_API int MQTTClient_isConnected(MQTTClient handle);
+
+
+/* Subscribe is synchronous.  QoS list parameter is changed on return to granted QoSs.
+   Returns return code, MQTTCLIENT_SUCCESS == success, non-zero some sort of error (TBD) */
+
+/**
+  * This function attempts to subscribe a client to a single topic, which may
+  * contain wildcards (see @ref wildcard). This call also specifies the
+  * @ref qos requested for the subscription
+  * (see also MQTTClient_subscribeMany()).
+  * @param handle A valid client handle from a successful call to
+  * MQTTClient_create().
+  * @param topic The subscription topic, which may include wildcards.
+  * @param qos The requested quality of service for the subscription.
+  * @return ::MQTTCLIENT_SUCCESS if the subscription request is successful.
+  * An error code is returned if there was a problem registering the
+  * subscription.
+  */
+LIBMQTT_API int MQTTClient_subscribe(MQTTClient handle, const char* topic, int qos);
+
+/**
+  * This function attempts to subscribe an MQTT version 5.0 client to a single topic, which may
+  * contain wildcards (see @ref wildcard). This call also specifies the
+  * @ref qos requested for the subscription
+  * (see also MQTTClient_subscribeMany()).
+  * @param handle A valid client handle from a successful call to
+  * MQTTClient_create().
+  * @param topic The subscription topic, which may include wildcards.
+  * @param qos The requested quality of service for the subscription.
+  * @param opts the MQTT 5.0 subscribe options to be used
+  * @param props the MQTT 5.0 properties to be used
+  * @return the MQTT 5.0 response information: error codes and properties.
+  */
+LIBMQTT_API MQTTResponse MQTTClient_subscribe5(MQTTClient handle, const char* topic, int qos,
+		MQTTSubscribe_options* opts, MQTTProperties* props);
+
+/**
+  * This function attempts to subscribe a client to a list of topics, which may
+  * contain wildcards (see @ref wildcard). This call also specifies the
+  * @ref qos requested for each topic (see also MQTTClient_subscribe()).
+  * @param handle A valid client handle from a successful call to
+  * MQTTClient_create().
+  * @param count The number of topics for which the client is requesting
+  * subscriptions.
+  * @param topic An array (of length <i>count</i>) of pointers to
+  * topics, each of which may include wildcards.
+  * @param qos An array (of length <i>count</i>) of @ref qos
+  * values. qos[n] is the requested QoS for topic[n].
+  * @return ::MQTTCLIENT_SUCCESS if the subscription request is successful.
+  * An error code is returned if there was a problem registering the
+  * subscriptions.
+  */
+LIBMQTT_API int MQTTClient_subscribeMany(MQTTClient handle, int count, char* const* topic, int* qos);
+
+/**
+  * This function attempts to subscribe an MQTT version 5.0 client to a list of topics, which may
+  * contain wildcards (see @ref wildcard). This call also specifies the
+  * @ref qos requested for each topic (see also MQTTClient_subscribe()).
+  * @param handle A valid client handle from a successful call to
+  * MQTTClient_create().
+  * @param count The number of topics for which the client is requesting
+  * subscriptions.
+  * @param topic An array (of length <i>count</i>) of pointers to
+  * topics, each of which may include wildcards.
+  * @param qos An array (of length <i>count</i>) of @ref qos
+  * values. qos[n] is the requested QoS for topic[n].
+  * @param opts the MQTT 5.0 subscribe options to be used
+  * @param props the MQTT 5.0 properties to be used
+  * @return the MQTT 5.0 response information: error codes and properties.
+  */
+LIBMQTT_API MQTTResponse MQTTClient_subscribeMany5(MQTTClient handle, int count, char* const* topic,
+		int* qos, MQTTSubscribe_options* opts, MQTTProperties* props);
+
+/**
+  * This function attempts to remove an existing subscription made by the
+  * specified client.
+  * @param handle A valid client handle from a successful call to
+  * MQTTClient_create().
+  * @param topic The topic for the subscription to be removed, which may
+  * include wildcards (see @ref wildcard).
+  * @return ::MQTTCLIENT_SUCCESS if the subscription is removed.
+  * An error code is returned if there was a problem removing the
+  * subscription.
+  */
+LIBMQTT_API int MQTTClient_unsubscribe(MQTTClient handle, const char* topic);
+
+/**
+  * This function attempts to remove an existing subscription made by the
+  * specified client using MQTT 5.0.
+  * @param handle A valid client handle from a successful call to
+  * MQTTClient_create().
+  * @param topic The topic for the subscription to be removed, which may
+  * include wildcards (see @ref wildcard).
+  * @param props the MQTT 5.0 properties to be used
+  * @return the MQTT 5.0 response information: error codes and properties.
+  */
+LIBMQTT_API MQTTResponse MQTTClient_unsubscribe5(MQTTClient handle, const char* topic, MQTTProperties* props);
+
+/**
+  * This function attempts to remove existing subscriptions to a list of topics
+  * made by the specified client.
+  * @param handle A valid client handle from a successful call to
+  * MQTTClient_create().
+  * @param count The number subscriptions to be removed.
+  * @param topic An array (of length <i>count</i>) of pointers to the topics of
+  * the subscriptions to be removed, each of which may include wildcards.
+  * @return ::MQTTCLIENT_SUCCESS if the subscriptions are removed.
+  * An error code is returned if there was a problem removing the subscriptions.
+  */
+LIBMQTT_API int MQTTClient_unsubscribeMany(MQTTClient handle, int count, char* const* topic);
+
+/**
+  * This function attempts to remove existing subscriptions to a list of topics
+  * made by the specified client using MQTT version 5.0.
+  * @param handle A valid client handle from a successful call to
+  * MQTTClient_create().
+  * @param count The number subscriptions to be removed.
+  * @param topic An array (of length <i>count</i>) of pointers to the topics of
+  * the subscriptions to be removed, each of which may include wildcards.
+  * @param props the MQTT 5.0 properties to be used
+  * @return the MQTT 5.0 response information: error codes and properties.
+  */
+LIBMQTT_API MQTTResponse MQTTClient_unsubscribeMany5(MQTTClient handle, int count, char* const* topic, MQTTProperties* props);
+
+/**
+  * This function attempts to publish a message to a given topic (see also
+  * MQTTClient_publishMessage()). An ::MQTTClient_deliveryToken is issued when
+  * this function returns successfully. If the client application needs to
+  * test for succesful delivery of QoS1 and QoS2 messages, this can be done
+  * either asynchronously or synchronously (see @ref async,
+  * ::MQTTClient_waitForCompletion and MQTTClient_deliveryComplete()).
+  * @param handle A valid client handle from a successful call to
+  * MQTTClient_create().
+  * @param topicName The topic associated with this message.
+  * @param payloadlen The length of the payload in bytes.
+  * @param payload A pointer to the byte array payload of the message.
+  * @param qos The @ref qos of the message.
+  * @param retained The retained flag for the message.
+  * @param dt A pointer to an ::MQTTClient_deliveryToken. This is populated
+  * with a token representing the message when the function returns
+  * successfully. If your application does not use delivery tokens, set this
+  * argument to NULL.
+  * @return ::MQTTCLIENT_SUCCESS if the message is accepted for publication.
+  * An error code is returned if there was a problem accepting the message.
+  */
+LIBMQTT_API int MQTTClient_publish(MQTTClient handle, const char* topicName, int payloadlen, const void* payload, int qos, int retained,
+		MQTTClient_deliveryToken* dt);
+
+/**
+  * Attempts to publish a message to a given topic using MQTT version 5.0 (see also
+  * MQTTClient_publishMessage5()). An ::MQTTClient_deliveryToken is issued when
+  * this function returns successfully. If the client application needs to
+  * test for succesful delivery of QoS1 and QoS2 messages, this can be done
+  * either asynchronously or synchronously (see @ref async,
+  * ::MQTTClient_waitForCompletion and MQTTClient_deliveryComplete()).
+  * @param handle A valid client handle from a successful call to
+  * MQTTClient_create().
+  * @param topicName The topic associated with this message.
+  * @param payloadlen The length of the payload in bytes.
+  * @param payload A pointer to the byte array payload of the message.
+  * @param qos The @ref qos of the message.
+  * @param retained The retained flag for the message.
+  * @param properties the MQTT 5.0 properties to be used
+  * @param dt A pointer to an ::MQTTClient_deliveryToken. This is populated
+  * with a token representing the message when the function returns
+  * successfully. If your application does not use delivery tokens, set this
+  * argument to NULL.
+  * @return the MQTT 5.0 response information: error codes and properties.
+  */
+LIBMQTT_API MQTTResponse MQTTClient_publish5(MQTTClient handle, const char* topicName, int payloadlen, const void* payload,
+		int qos, int retained, MQTTProperties* properties, MQTTClient_deliveryToken* dt);
+/**
+  * This function attempts to publish a message to a given topic (see also
+  * MQTTClient_publish()). An ::MQTTClient_deliveryToken is issued when
+  * this function returns successfully. If the client application needs to
+  * test for succesful delivery of QoS1 and QoS2 messages, this can be done
+  * either asynchronously or synchronously (see @ref async,
+  * ::MQTTClient_waitForCompletion and MQTTClient_deliveryComplete()).
+  * @param handle A valid client handle from a successful call to
+  * MQTTClient_create().
+  * @param topicName The topic associated with this message.
+  * @param msg A pointer to a valid MQTTClient_message structure containing
+  * the payload and attributes of the message to be published.
+  * @param dt A pointer to an ::MQTTClient_deliveryToken. This is populated
+  * with a token representing the message when the function returns
+  * successfully. If your application does not use delivery tokens, set this
+  * argument to NULL.
+  * @return ::MQTTCLIENT_SUCCESS if the message is accepted for publication.
+  * An error code is returned if there was a problem accepting the message.
+  */
+LIBMQTT_API int MQTTClient_publishMessage(MQTTClient handle, const char* topicName, MQTTClient_message* msg, MQTTClient_deliveryToken* dt);
+
+
+/**
+  * Attempts to publish a message to the given topic using MQTT version 5.0
+  * (see also
+  * MQTTClient_publish5()). An ::MQTTClient_deliveryToken is issued when
+  * this function returns successfully. If the client application needs to
+  * test for succesful delivery of QoS1 and QoS2 messages, this can be done
+  * either asynchronously or synchronously (see @ref async,
+  * ::MQTTClient_waitForCompletion and MQTTClient_deliveryComplete()).
+  * @param handle A valid client handle from a successful call to
+  * MQTTClient_create().
+  * @param topicName The topic associated with this message.
+  * @param msg A pointer to a valid MQTTClient_message structure containing
+  * the payload and attributes of the message to be published.
+  * @param dt A pointer to an ::MQTTClient_deliveryToken. This is populated
+  * with a token representing the message when the function returns
+  * successfully. If your application does not use delivery tokens, set this
+  * argument to NULL.
+  * @return the MQTT 5.0 response information: error codes and properties.
+  */
+LIBMQTT_API MQTTResponse MQTTClient_publishMessage5(MQTTClient handle, const char* topicName, MQTTClient_message* msg,
+		MQTTClient_deliveryToken* dt);
+
+/**
+  * This function is called by the client application to synchronize execution
+  * of the main thread with completed publication of a message. When called,
+  * MQTTClient_waitForCompletion() blocks execution until the message has been
+  * successful delivered or the specified timeout has expired. See @ref async.
+  * @param handle A valid client handle from a successful call to
+  * MQTTClient_create().
+  * @param dt The ::MQTTClient_deliveryToken that represents the message being
+  * tested for successful delivery. Delivery tokens are issued by the
+  * publishing functions MQTTClient_publish() and MQTTClient_publishMessage().
+  * @param timeout The maximum time to wait in milliseconds.
+  * @return ::MQTTCLIENT_SUCCESS if the message was successfully delivered.
+  * An error code is returned if the timeout expires or there was a problem
+  * checking the token.
+  */
+LIBMQTT_API int MQTTClient_waitForCompletion(MQTTClient handle, MQTTClient_deliveryToken dt, unsigned long timeout);
+
+
+/**
+  * This function sets a pointer to an array of delivery tokens for
+  * messages that are currently in-flight (pending completion).
+  *
+  * <b>Important note:</b> The memory used to hold the array of tokens is
+  * malloc()'d in this function. The client application is responsible for
+  * freeing this memory when it is no longer required.
+  * @param handle A valid client handle from a successful call to
+  * MQTTClient_create().
+  * @param tokens The address of a pointer to an ::MQTTClient_deliveryToken.
+  * When the function returns successfully, the pointer is set to point to an
+  * array of tokens representing messages pending completion. The last member of
+  * the array is set to -1 to indicate there are no more tokens. If no tokens
+  * are pending, the pointer is set to NULL.
+  * @return ::MQTTCLIENT_SUCCESS if the function returns successfully.
+  * An error code is returned if there was a problem obtaining the list of
+  * pending tokens.
+  */
+LIBMQTT_API int MQTTClient_getPendingDeliveryTokens(MQTTClient handle, MQTTClient_deliveryToken **tokens);
+
+/**
+  * When implementing a single-threaded client, call this function periodically
+  * to allow processing of message retries and to send MQTT keepalive pings.
+  * If the application is calling MQTTClient_receive() regularly, then it is
+  * not necessary to call this function.
+  */
+LIBMQTT_API void MQTTClient_yield(void);
+
+/**
+  * This function performs a synchronous receive of incoming messages. It should
+  * be used only when the client application has not set callback methods to
+  * support asynchronous receipt of messages (see @ref async and
+  * MQTTClient_setCallbacks()). Using this function allows a single-threaded
+  * client subscriber application to be written. When called, this function
+  * blocks until the next message arrives or the specified timeout expires
+  *(see also MQTTClient_yield()).
+  *
+  * <b>Important note:</b> The application must free() the memory allocated
+  * to the topic and the message when processing is complete (see
+  * MQTTClient_freeMessage()).
+  * @param handle A valid client handle from a successful call to
+  * MQTTClient_create().
+  * @param topicName The address of a pointer to a topic. This function
+  * allocates the memory for the topic and returns it to the application
+  * by setting <i>topicName</i> to point to the topic.
+  * @param topicLen The length of the topic. If the return code from this
+  * function is ::MQTTCLIENT_TOPICNAME_TRUNCATED, the topic contains embedded
+  * NULL characters and the full topic should be retrieved by using
+  * <i>topicLen</i>.
+  * @param message The address of a pointer to the received message. This
+  * function allocates the memory for the message and returns it to the
+  * application by setting <i>message</i> to point to the received message.
+  * The pointer is set to NULL if the timeout expires.
+  * @param timeout The length of time to wait for a message in milliseconds.
+  * @return ::MQTTCLIENT_SUCCESS or ::MQTTCLIENT_TOPICNAME_TRUNCATED if a
+  * message is received. ::MQTTCLIENT_SUCCESS can also indicate that the
+  * timeout expired, in which case <i>message</i> is NULL. An error code is
+  * returned if there was a problem trying to receive a message.
+  */
+LIBMQTT_API int MQTTClient_receive(MQTTClient handle, char** topicName, int* topicLen, MQTTClient_message** message,
+		unsigned long timeout);
+
+/**
+  * This function frees memory allocated to an MQTT message, including the
+  * additional memory allocated to the message payload. The client application
+  * calls this function when the message has been fully processed. <b>Important
+  * note:</b> This function does not free the memory allocated to a message
+  * topic string. It is the responsibility of the client application to free
+  * this memory using the MQTTClient_free() library function.
+  * @param msg The address of a pointer to the ::MQTTClient_message structure
+  * to be freed.
+  */
+LIBMQTT_API void MQTTClient_freeMessage(MQTTClient_message** msg);
+
+/**
+  * This function frees memory allocated by the MQTT C client library, especially the
+  * topic name. This is needed on Windows when the client libary and application
+  * program have been compiled with different versions of the C compiler.  It is
+  * thus good policy to always use this function when freeing any MQTT C client-
+  * allocated memory.
+  * @param ptr The pointer to the client library storage to be freed.
+  */
+LIBMQTT_API void MQTTClient_free(void* ptr);
+
+/**
+  * This function is used to allocate memory to be used or freed by the MQTT C client library,
+  * especially the data in user persistence. This is needed on Windows when the client library
+  * and application program have been compiled with different versions of the C compiler.
+  * @param size The size of the memory to be allocated.
+  */
+LIBMQTT_API void* MQTTClient_malloc(size_t size);
+
+/**
+  * This function frees the memory allocated to an MQTT client (see
+  * MQTTClient_create()). It should be called when the client is no longer
+  * required.
+  * @param handle A pointer to the handle referring to the ::MQTTClient
+  * structure to be freed.
+  */
+LIBMQTT_API void MQTTClient_destroy(MQTTClient* handle);
+
+
+enum MQTTCLIENT_TRACE_LEVELS
+{
+	MQTTCLIENT_TRACE_MAXIMUM = 1,
+	MQTTCLIENT_TRACE_MEDIUM,
+	MQTTCLIENT_TRACE_MINIMUM,
+	MQTTCLIENT_TRACE_PROTOCOL,
+	MQTTCLIENT_TRACE_ERROR,
+	MQTTCLIENT_TRACE_SEVERE,
+	MQTTCLIENT_TRACE_FATAL,
+};
+
+
+/**
+  * This function sets the level of trace information which will be
+  * returned in the trace callback.
+  * @param level the trace level required
+  */
+LIBMQTT_API void MQTTClient_setTraceLevel(enum MQTTCLIENT_TRACE_LEVELS level);
+
+
+/**
+  * This is a callback function prototype which must be implemented if you want
+  * to receive trace information. Do not invoke any other Paho API calls in this
+  * callback function - unpredictable behavior may result.
+  * @param level the trace level of the message returned
+  * @param message the trace message.  This is a pointer to a static buffer which
+  * will be overwritten on each call.  You must copy the data if you want to keep
+  * it for later.
+  */
+typedef void MQTTClient_traceCallback(enum MQTTCLIENT_TRACE_LEVELS level, char* message);
+
+/**
+  * This function sets the trace callback if needed.  If set to NULL,
+  * no trace information will be returned.  The default trace level is
+  * MQTTASYNC_TRACE_MINIMUM.
+  * @param callback a pointer to the function which will handle the trace information
+  */
+LIBMQTT_API void MQTTClient_setTraceCallback(MQTTClient_traceCallback* callback);
+
+/**
+  * Sets the timeout value for un/subscribe commands when waiting for the un/suback response from
+  * the server.  Values less than 5000 are not allowed.
+  * @param handle A valid client handle from a successful call to MQTTClient_create().
+  * @param milliSeconds the maximum number of milliseconds to wait
+  * @return MQTTCLIENT_SUCCESS or MQTTCLIENT_FAILURE
+  */
+LIBMQTT_API int MQTTClient_setCommandTimeout(MQTTClient handle, unsigned long milliSeconds);
+
+/**
+ * Returns a pointer to the string representation of the error or NULL.
+ *
+ * Do not free after use. Returns NULL if the error code is unknown.
+ */
+LIBMQTT_API const char* MQTTClient_strerror(int code);
+
+#if defined(__cplusplus)
+     }
+#endif
+
+#endif
+
+/*!
+  * @cond MQTTClient_main
+  * @page async Asynchronous vs synchronous client applications
+  * This client library supports two modes of operation. These are referred to
+  * as <b>synchronous</b> and <b>asynchronous</b> modes. If your application
+  * calls MQTTClient_setCallbacks(), this puts the client into asynchronous
+  * mode, otherwise it operates in synchronous mode.
+  *
+  * In synchronous mode, the client application runs on a single thread.
+  * Messages are published using the MQTTClient_publish() and
+  * MQTTClient_publishMessage() functions. To determine that a QoS1 or QoS2
+  * (see @ref qos) message has been successfully delivered, the application
+  * must call the MQTTClient_waitForCompletion() function. An example showing
+  * synchronous publication is shown in @ref pubsync. Receiving messages in
+  * synchronous mode uses the MQTTClient_receive() function. Client applications
+  * must call either MQTTClient_receive() or MQTTClient_yield() relatively
+  * frequently in order to allow processing of acknowledgements and the MQTT
+  * "pings" that keep the network connection to the server alive.
+  *
+  * In asynchronous mode, the client application runs on several threads. The
+  * main program calls functions in the client library to publish and subscribe,
+  * just as for the synchronous mode. Processing of handshaking and maintaining
+  * the network connection is performed in the background, however.
+  * Notifications of status and message reception are provided to the client
+  * application using callbacks registered with the library by the call to
+  * MQTTClient_setCallbacks() (see MQTTClient_messageArrived(),
+  * MQTTClient_connectionLost() and MQTTClient_deliveryComplete()).
+  * This API is not thread safe however - it is not possible to call it from multiple
+  * threads without synchronization.  You can use the MQTTAsync API for that.
+  *
+  * @page callbacks Callbacks
+  * You must not call a function from this API from within a callback otherwise
+  * a deadlock might result.  The only exception to this is the ability to call
+  * connect within the connection lost callback, to allow a reconnect.
+  *
+  * When using MQTT 5.0, you can also call connect from within the disconnected
+  * callback, which is invoked when the MQTT server sends a disconnect packet.
+  * This server behaviour is allowed in MQTT 5.0, but not in MQTT 3.1.1, so the
+  * disconnected callback will never be invoked if you use MQTT 3.1.1.
+  *
+  * In particular, you must make a publish call within the message arrived callback.
+  * These restrictions are all lifted in the
+  * <a href="../../MQTTAsync/html/index.html">MQTTAsync API</a>.
+  *
+  * If no callbacks are assigned, this will include the message arrived callback.
+  * This could be done if the application is a pure publisher, and does
+  * not subscribe to any topics.  If however messages are received, and no message
+  * arrived callback is set, or receive not called, then those messages will accumulate
+  * and take up memory, as there is no place for them to be delivered.
+  * It is up to the application to protect against this situation.
+  *
+  * @page wildcard Subscription wildcards
+  * Every MQTT message includes a topic that classifies it. MQTT servers use
+  * topics to determine which subscribers should receive messages published to
+  * the server.
+  *
+  * Consider the server receiving messages from several environmental sensors.
+  * Each sensor publishes its measurement data as a message with an associated
+  * topic. Subscribing applications need to know which sensor originally
+  * published each received message. A unique topic is thus used to identify
+  * each sensor and measurement type. Topics such as SENSOR1TEMP,
+  * SENSOR1HUMIDITY, SENSOR2TEMP and so on achieve this but are not very
+  * flexible. If additional sensors are added to the system at a later date,
+  * subscribing applications must be modified to receive them.
+  *
+  * To provide more flexibility, MQTT supports a hierarchical topic namespace.
+  * This allows application designers to organize topics to simplify their
+  * management. Levels in the hierarchy are delimited by the '/' character,
+  * such as SENSOR/1/HUMIDITY. Publishers and subscribers use these
+  * hierarchical topics as already described.
+  *
+  * For subscriptions, two wildcard characters are supported:
+  * <ul>
+  * <li>A '#' character represents a complete sub-tree of the hierarchy and
+  * thus must be the last character in a subscription topic string, such as
+  * SENSOR/#. This will match any topic starting with SENSOR/, such as
+  * SENSOR/1/TEMP and SENSOR/2/HUMIDITY.</li>
+  * <li> A '+' character represents a single level of the hierarchy and is
+  * used between delimiters. For example, SENSOR/+/TEMP will match
+  * SENSOR/1/TEMP and SENSOR/2/TEMP.</li>
+  * </ul>
+  * Publishers are not allowed to use the wildcard characters in their topic
+  * names.
+  *
+  * Deciding on your topic hierarchy is an important step in your system design.
+  *
+  * @page qos Quality of service
+  * The MQTT protocol provides three qualities of service for delivering
+  * messages between clients and servers: "at most once", "at least once" and
+  * "exactly once".
+  *
+  * Quality of service (QoS) is an attribute of an individual message being
+  * published. An application sets the QoS for a specific message by setting the
+  * MQTTClient_message.qos field to the required value.
+  *
+  * A subscribing client can set the maximum quality of service a server uses
+  * to send messages that match the client subscriptions. The
+  * MQTTClient_subscribe() and MQTTClient_subscribeMany() functions set this
+  * maximum. The QoS of a message forwarded to a subscriber thus might be
+  * different to the QoS given to the message by the original publisher.
+  * The lower of the two values is used to forward a message.
+  *
+  * The three levels are:
+  *
+  * <b>QoS0, At most once:</b> The message is delivered at most once, or it
+  * may not be delivered at all. Its delivery across the network is not
+  * acknowledged. The message is not stored. The message could be lost if the
+  * client is disconnected, or if the server fails. QoS0 is the fastest mode of
+  * transfer. It is sometimes called "fire and forget".
+  *
+  * The MQTT protocol does not require servers to forward publications at QoS0
+  * to a client. If the client is disconnected at the time the server receives
+  * the publication, the publication might be discarded, depending on the
+  * server implementation.
+  *
+  * <b>QoS1, At least once:</b> The message is always delivered at least once.
+  * It might be delivered multiple times if there is a failure before an
+  * acknowledgment is received by the sender. The message must be stored
+  * locally at the sender, until the sender receives confirmation that the
+  * message has been published by the receiver. The message is stored in case
+  * the message must be sent again.
+  *
+  * <b>QoS2, Exactly once:</b> The message is always delivered exactly once.
+  * The message must be stored locally at the sender, until the sender receives
+  * confirmation that the message has been published by the receiver. The
+  * message is stored in case the message must be sent again. QoS2 is the
+  * safest, but slowest mode of transfer. A more sophisticated handshaking
+  * and acknowledgement sequence is used than for QoS1 to ensure no duplication
+  * of messages occurs.
+  * @page pubsync Synchronous publication example
+@code
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "MQTTClient.h"
+
+#define ADDRESS     "tcp://mqtt.eclipseprojects.io:1883"
+#define CLIENTID    "ExampleClientPub"
+#define TOPIC       "MQTT Examples"
+#define PAYLOAD     "Hello World!"
+#define QOS         1
+#define TIMEOUT     10000L
+
+int main(int argc, char* argv[])
+{
+    MQTTClient client;
+    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
+    MQTTClient_message pubmsg = MQTTClient_message_initializer;
+    MQTTClient_deliveryToken token;
+    int rc;
+
+    if ((rc = MQTTClient_create(&client, ADDRESS, CLIENTID,
+        MQTTCLIENT_PERSISTENCE_NONE, NULL)) != MQTTCLIENT_SUCCESS)
+    {
+         printf("Failed to create client, return code %d\n", rc);
+         exit(EXIT_FAILURE);
+    }
+
+    conn_opts.keepAliveInterval = 20;
+    conn_opts.cleansession = 1;
+    if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
+    {
+        printf("Failed to connect, return code %d\n", rc);
+        exit(EXIT_FAILURE);
+    }
+
+    pubmsg.payload = PAYLOAD;
+    pubmsg.payloadlen = (int)strlen(PAYLOAD);
+    pubmsg.qos = QOS;
+    pubmsg.retained = 0;
+    if ((rc = MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token)) != MQTTCLIENT_SUCCESS)
+    {
+         printf("Failed to publish message, return code %d\n", rc);
+         exit(EXIT_FAILURE);
+    }
+
+    printf("Waiting for up to %d seconds for publication of %s\n"
+            "on topic %s for client with ClientID: %s\n",
+            (int)(TIMEOUT/1000), PAYLOAD, TOPIC, CLIENTID);
+    rc = MQTTClient_waitForCompletion(client, token, TIMEOUT);
+    printf("Message with delivery token %d delivered\n", token);
+
+    if ((rc = MQTTClient_disconnect(client, 10000)) != MQTTCLIENT_SUCCESS)
+    	printf("Failed to disconnect, return code %d\n", rc);
+    MQTTClient_destroy(&client);
+    return rc;
+}
+
+  * @endcode
+  *
+  * @page pubasync Asynchronous publication example
+@code{.c}
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "MQTTClient.h"
+
+#if !defined(_WIN32)
+#include <unistd.h>
+#else
+#include <windows.h>
+#endif
+
+#define ADDRESS     "tcp://mqtt.eclipseprojects.io:1883"
+#define CLIENTID    "ExampleClientPub"
+#define TOPIC       "MQTT Examples"
+#define PAYLOAD     "Hello World!"
+#define QOS         1
+#define TIMEOUT     10000L
+
+MQTTClient_deliveryToken deliveredtoken;
+
+void delivered(void *context, MQTTClient_deliveryToken dt)
+{
+    printf("Message with token value %d delivery confirmed\n", dt);
+    deliveredtoken = dt;
+}
+
+int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
+{
+    printf("Message arrived\n");
+    printf("     topic: %s\n", topicName);
+    printf("   message: %.*s\n", message->payloadlen, (char*)message->payload);
+    MQTTClient_freeMessage(&message);
+    MQTTClient_free(topicName);
+    return 1;
+}
+
+void connlost(void *context, char *cause)
+{
+    printf("\nConnection lost\n");
+    printf("     cause: %s\n", cause);
+}
+
+int main(int argc, char* argv[])
+{
+    MQTTClient client;
+    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
+    MQTTClient_message pubmsg = MQTTClient_message_initializer;
+    MQTTClient_deliveryToken token;
+    int rc;
+
+    if ((rc = MQTTClient_create(&client, ADDRESS, CLIENTID,
+        MQTTCLIENT_PERSISTENCE_NONE, NULL)) != MQTTCLIENT_SUCCESS)
+    {
+        printf("Failed to create client, return code %d\n", rc);
+        rc = EXIT_FAILURE;
+        goto exit;
+    }
+
+    if ((rc = MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered)) != MQTTCLIENT_SUCCESS)
+    {
+        printf("Failed to set callbacks, return code %d\n", rc);
+        rc = EXIT_FAILURE;
+        goto destroy_exit;
+    }
+
+    conn_opts.keepAliveInterval = 20;
+    conn_opts.cleansession = 1;
+    if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
+    {
+        printf("Failed to connect, return code %d\n", rc);
+        rc = EXIT_FAILURE;
+        goto destroy_exit;
+    }
+
+    pubmsg.payload = PAYLOAD;
+    pubmsg.payloadlen = (int)strlen(PAYLOAD);
+    pubmsg.qos = QOS;
+    pubmsg.retained = 0;
+    deliveredtoken = 0;
+    if ((rc = MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token)) != MQTTCLIENT_SUCCESS)
+    {
+    	printf("Failed to publish message, return code %d\n", rc);
+    	rc = EXIT_FAILURE;
+    }
+    else
+    {
+    	printf("Waiting for publication of %s\n"
+            "on topic %s for client with ClientID: %s\n",
+            PAYLOAD, TOPIC, CLIENTID);
+    	while (deliveredtoken != token)
+    	{
+			#if defined(_WIN32)
+				Sleep(100);
+			#else
+				usleep(10000L);
+			#endif
+    	}
+    }
+
+    if ((rc = MQTTClient_disconnect(client, 10000)) != MQTTCLIENT_SUCCESS)
+    {
+    	printf("Failed to disconnect, return code %d\n", rc);
+    	rc = EXIT_FAILURE;
+    }
+
+destroy_exit:
+    MQTTClient_destroy(&client);
+
+exit:
+    return rc;
+}
+
+  * @endcode
+  * @page subasync Asynchronous subscription example
+@code
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "MQTTClient.h"
+
+#define ADDRESS     "tcp://mqtt.eclipseprojects.io:1883"
+#define CLIENTID    "ExampleClientSub"
+#define TOPIC       "MQTT Examples"
+#define PAYLOAD     "Hello World!"
+#define QOS         1
+#define TIMEOUT     10000L
+
+volatile MQTTClient_deliveryToken deliveredtoken;
+
+void delivered(void *context, MQTTClient_deliveryToken dt)
+{
+    printf("Message with token value %d delivery confirmed\n", dt);
+    deliveredtoken = dt;
+}
+
+int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
+{
+    printf("Message arrived\n");
+    printf("     topic: %s\n", topicName);
+    printf("   message: %.*s\n", message->payloadlen, (char*)message->payload);
+    MQTTClient_freeMessage(&message);
+    MQTTClient_free(topicName);
+    return 1;
+}
+
+void connlost(void *context, char *cause)
+{
+    printf("\nConnection lost\n");
+    printf("     cause: %s\n", cause);
+}
+
+int main(int argc, char* argv[])
+{
+    MQTTClient client;
+    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
+    int rc;
+
+    if ((rc = MQTTClient_create(&client, ADDRESS, CLIENTID,
+        MQTTCLIENT_PERSISTENCE_NONE, NULL)) != MQTTCLIENT_SUCCESS)
+    {
+        printf("Failed to create client, return code %d\n", rc);
+        rc = EXIT_FAILURE;
+        goto exit;
+    }
+
+    if ((rc = MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered)) != MQTTCLIENT_SUCCESS)
+    {
+        printf("Failed to set callbacks, return code %d\n", rc);
+        rc = EXIT_FAILURE;
+        goto destroy_exit;
+    }
+
+    conn_opts.keepAliveInterval = 20;
+    conn_opts.cleansession = 1;
+    if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
+    {
+        printf("Failed to connect, return code %d\n", rc);
+        rc = EXIT_FAILURE;
+        goto destroy_exit;
+    }
+
+    printf("Subscribing to topic %s\nfor client %s using QoS%d\n\n"
+           "Press Q<Enter> to quit\n\n", TOPIC, CLIENTID, QOS);
+    if ((rc = MQTTClient_subscribe(client, TOPIC, QOS)) != MQTTCLIENT_SUCCESS)
+    {
+    	printf("Failed to subscribe, return code %d\n", rc);
+    	rc = EXIT_FAILURE;
+    }
+    else
+    {
+    	int ch;
+    	do
+    	{
+        	ch = getchar();
+    	} while (ch!='Q' && ch != 'q');
+
+        if ((rc = MQTTClient_unsubscribe(client, TOPIC)) != MQTTCLIENT_SUCCESS)
+        {
+        	printf("Failed to unsubscribe, return code %d\n", rc);
+        	rc = EXIT_FAILURE;
+        }
+    }
+
+    if ((rc = MQTTClient_disconnect(client, 10000)) != MQTTCLIENT_SUCCESS)
+    {
+    	printf("Failed to disconnect, return code %d\n", rc);
+    	rc = EXIT_FAILURE;
+    }
+destroy_exit:
+    MQTTClient_destroy(&client);
+exit:
+    return rc;
+}
+
+  * @endcode
+  * @page tracing Tracing
+  *
+  * Runtime tracing is controlled by environment variables.
+  *
+  * Tracing is switched on by setting MQTT_C_CLIENT_TRACE.  A value of ON, or stdout, prints to
+  * stdout, any other value is interpreted as a file name to use.
+  *
+  * The amount of trace detail is controlled with the MQTT_C_CLIENT_TRACE_LEVEL environment
+  * variable - valid values are ERROR, PROTOCOL, MINIMUM, MEDIUM and MAXIMUM
+  * (from least to most verbose).
+  *
+  * The variable MQTT_C_CLIENT_TRACE_MAX_LINES limits the number of lines of trace that are output
+  * to a file.  Two files are used at most, when they are full, the last one is overwritten with the
+  * new trace entries.  The default size is 1000 lines.
+  *
+  * ### MQTT Packet Tracing
+  *
+  * A feature that can be very useful is printing the MQTT packets that are sent and received.  To
+  * achieve this, use the following environment variable settings:
+  * @code
+    MQTT_C_CLIENT_TRACE=ON
+    MQTT_C_CLIENT_TRACE_LEVEL=PROTOCOL
+  * @endcode
+  * The output you should see looks like this:
+  * @code
+    20130528 155936.813 3 stdout-subscriber -> CONNECT cleansession: 1 (0)
+    20130528 155936.813 3 stdout-subscriber <- CONNACK rc: 0
+    20130528 155936.813 3 stdout-subscriber -> SUBSCRIBE msgid: 1 (0)
+    20130528 155936.813 3 stdout-subscriber <- SUBACK msgid: 1
+    20130528 155941.818 3 stdout-subscriber -> DISCONNECT (0)
+  * @endcode
+  * where the fields are:
+  * 1. date
+  * 2. time
+  * 3. socket number
+  * 4. client id
+  * 5. direction (-> from client to server, <- from server to client)
+  * 6. packet details
+  *
+  * ### Default Level Tracing
+  *
+  * This is an extract of a default level trace of a call to connect:
+  * @code
+    19700101 010000.000 (1152206656) (0)> MQTTClient_connect:893
+    19700101 010000.000 (1152206656)  (1)> MQTTClient_connectURI:716
+    20130528 160447.479 Connecting to serverURI localhost:1883
+    20130528 160447.479 (1152206656)   (2)> MQTTProtocol_connect:98
+    20130528 160447.479 (1152206656)    (3)> MQTTProtocol_addressPort:48
+    20130528 160447.479 (1152206656)    (3)< MQTTProtocol_addressPort:73
+    20130528 160447.479 (1152206656)    (3)> Socket_new:599
+    20130528 160447.479 New socket 4 for localhost, port 1883
+    20130528 160447.479 (1152206656)     (4)> Socket_addSocket:163
+    20130528 160447.479 (1152206656)      (5)> Socket_setnonblocking:73
+    20130528 160447.479 (1152206656)      (5)< Socket_setnonblocking:78 (0)
+    20130528 160447.479 (1152206656)     (4)< Socket_addSocket:176 (0)
+    20130528 160447.479 (1152206656)     (4)> Socket_error:95
+    20130528 160447.479 (1152206656)     (4)< Socket_error:104 (115)
+    20130528 160447.479 Connect pending
+    20130528 160447.479 (1152206656)    (3)< Socket_new:683 (115)
+    20130528 160447.479 (1152206656)   (2)< MQTTProtocol_connect:131 (115)
+  * @endcode
+  * where the fields are:
+  * 1. date
+  * 2. time
+  * 3. thread id
+  * 4. function nesting level
+  * 5. function entry (>) or exit (<)
+  * 6. function name : line of source code file
+  * 7. return value (if there is one)
+  *
+  * ### Memory Allocation Tracing
+  *
+  * Setting the trace level to maximum causes memory allocations and frees to be traced along with
+  * the default trace entries, with messages like the following:
+  * @code
+    20130528 161819.657 Allocating 16 bytes in heap at file /home/icraggs/workspaces/mqrtc/mqttv3c/src/MQTTPacket.c line 177 ptr 0x179f930
+
+    20130528 161819.657 Freeing 16 bytes in heap at file /home/icraggs/workspaces/mqrtc/mqttv3c/src/MQTTPacket.c line 201, heap use now 896 bytes
+  * @endcode
+  * When the last MQTT client object is destroyed, if the trace is being recorded
+  * and all memory allocated by the client library has not been freed, an error message will be
+  * written to the trace.  This can help with fixing memory leaks.  The message will look like this:
+  * @code
+    20130528 163909.208 Some memory not freed at shutdown, possible memory leak
+    20130528 163909.208 Heap scan start, total 880 bytes
+    20130528 163909.208 Heap element size 32, line 354, file /home/icraggs/workspaces/mqrtc/mqttv3c/src/MQTTPacket.c, ptr 0x260cb00
+    20130528 163909.208   Content
+    20130528 163909.209 Heap scan end
+  * @endcode
+  * @endcond
+  */

+ 277 - 0
library/include/MQTTClientPersistence.h

@@ -0,0 +1,277 @@
+/*******************************************************************************
+ * Copyright (c) 2009, 2020 IBM Corp.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v2.0
+ * and Eclipse Distribution License v1.0 which accompany this distribution. 
+ *
+ * The Eclipse Public License is available at 
+ *    https://www.eclipse.org/legal/epl-2.0/
+ * and the Eclipse Distribution License is available at 
+ *   http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ *    Ian Craggs - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+
+/**
+ * @file
+ * \brief This structure represents a persistent data store, used to store 
+ * outbound and inbound messages, in order to achieve reliable messaging.
+ *
+ * The MQTT Client persists QoS1 and QoS2 messages in order to meet the
+ * assurances of delivery associated with these @ref qos levels. The messages 
+ * are saved in persistent storage
+ * The type and context of the persistence implementation are specified when 
+ * the MQTT client is created (see MQTTClient_create()). The default 
+ * persistence type (::MQTTCLIENT_PERSISTENCE_DEFAULT) uses a file system-based
+ * persistence mechanism. The <i>persistence_context</i> argument passed to 
+ * MQTTClient_create() when using the default peristence is a string 
+ * representing the location of the persistence directory. If the context 
+ * argument is NULL, the working directory will be used. 
+ *
+ * To use memory-based persistence, an application passes 
+ * ::MQTTCLIENT_PERSISTENCE_NONE as the <i>persistence_type</i> to 
+ * MQTTClient_create(). This can lead to message loss in certain situations, 
+ * but can be appropriate in some cases (see @ref qos).
+ *
+ * Client applications can provide their own persistence mechanism by passing
+ * ::MQTTCLIENT_PERSISTENCE_USER as the <i>persistence_type</i>. To implement a
+ * custom persistence mechanism, the application must pass an initialized
+ * ::MQTTClient_persistence structure as the <i>persistence_context</i> 
+ * argument to MQTTClient_create().
+ *
+ * If the functions defined return an ::MQTTCLIENT_PERSISTENCE_ERROR then the 
+ * state of the persisted data should remain as it was prior to the function 
+ * being called. For example, if Persistence_put() returns 
+ * ::MQTTCLIENT_PERSISTENCE_ERROR, then it is assumed tha tthe persistent store
+ * does not contain the data that was passed to the function. Similarly,  if 
+ * Persistence_remove() returns ::MQTTCLIENT_PERSISTENCE_ERROR then it is 
+ * assumed that the data to be removed is still held in the persistent store.
+ *
+ * It is up to the persistence implementation to log any error information that
+ * may be required to diagnose a persistence mechanism failure.
+ */
+
+/*
+/// @cond EXCLUDE
+*/
+#if !defined(MQTTCLIENTPERSISTENCE_H)
+#define MQTTCLIENTPERSISTENCE_H
+/*
+/// @endcond
+*/
+
+/**
+  * This <i>persistence_type</i> value specifies the default file system-based 
+  * persistence mechanism (see MQTTClient_create()).
+  */
+#define MQTTCLIENT_PERSISTENCE_DEFAULT 0
+/**
+  * This <i>persistence_type</i> value specifies a memory-based 
+  * persistence mechanism (see MQTTClient_create()).
+  */
+#define MQTTCLIENT_PERSISTENCE_NONE 1
+/**
+  * This <i>persistence_type</i> value specifies an application-specific 
+  * persistence mechanism (see MQTTClient_create()).
+  */
+#define MQTTCLIENT_PERSISTENCE_USER 2
+
+/** 
+  * Application-specific persistence functions must return this error code if 
+  * there is a problem executing the function. 
+  */
+#define MQTTCLIENT_PERSISTENCE_ERROR -2
+
+/**
+  * @brief Initialize the persistent store.
+  * 
+  * Either open the existing persistent store for this client ID or create a new
+  * one if one doesn't exist. If the persistent store is already open, return 
+  * without taking any action.
+  *
+  * An application can use the same client identifier to connect to many
+  * different servers. The <i>clientid</i> in conjunction with the 
+  * <i>serverURI</i> uniquely identifies the persistence store required.
+  *
+  * @param handle The address of a pointer to a handle for this persistence 
+  * implementation. This function must set handle to a valid reference to the 
+  * persistence following a successful return. 
+  * The handle pointer is passed as an argument to all the other
+  * persistence functions. It may include the context parameter and/or any other
+  * data for use by the persistence functions.
+  * @param clientID The client identifier for which the persistent store should 
+  * be opened.
+  * @param serverURI The connection string specified when the MQTT client was
+  * created (see MQTTClient_create()).
+  * @param context A pointer to any data required to initialize the persistent
+  * store (see ::MQTTClient_persistence).
+  * @return Return 0 if the function completes successfully, otherwise return
+  * ::MQTTCLIENT_PERSISTENCE_ERROR.
+  */
+typedef int (*Persistence_open)(void** handle, const char* clientID, const char* serverURI, void* context);
+
+/**
+  * @brief Close the persistent store referred to by the handle.
+  *
+  * @param handle The handle pointer from a successful call to 
+  * Persistence_open().
+  * @return Return 0 if the function completes successfully, otherwise return
+  * ::MQTTCLIENT_PERSISTENCE_ERROR.
+  */
+typedef int (*Persistence_close)(void* handle); 
+
+/**
+  * @brief Put the specified data into the persistent store.
+  *
+  * @param handle The handle pointer from a successful call to 
+  * Persistence_open().
+  * @param key A string used as the key for the data to be put in the store. The
+  * key is later used to retrieve data from the store with Persistence_get().
+  * @param bufcount The number of buffers to write to the persistence store.
+  * @param buffers An array of pointers to the data buffers associated with 
+  * this <i>key</i>.
+  * @param buflens An array of lengths of the data buffers. <i>buflen[n]</i> 
+  * gives the length of <i>buffer[n]</i>.
+  * @return Return 0 if the function completes successfully, otherwise return
+  * ::MQTTCLIENT_PERSISTENCE_ERROR.
+  */
+typedef int (*Persistence_put)(void* handle, char* key, int bufcount, char* buffers[], int buflens[]);
+
+/**
+  * @brief Retrieve the specified data from the persistent store. 
+  *
+  * @param handle The handle pointer from a successful call to 
+  * Persistence_open().
+  * @param key A string that is the key for the data to be retrieved. This is 
+  * the same key used to save the data to the store with Persistence_put().
+  * @param buffer The address of a pointer to a buffer. This function sets the
+  * pointer to point at the retrieved data, if successful.
+  * @param buflen The address of an int that is set to the length of 
+  * <i>buffer</i> by this function if successful.
+  * @return Return 0 if the function completes successfully, otherwise return
+  * ::MQTTCLIENT_PERSISTENCE_ERROR.
+  */
+typedef int (*Persistence_get)(void* handle, char* key, char** buffer, int* buflen);
+
+/**
+  * @brief Remove the data for the specified key from the store.
+  *
+  * @param handle The handle pointer from a successful call to 
+  * Persistence_open().
+  * @param key A string that is the key for the data to be removed from the
+  * store. This is the same key used to save the data to the store with 
+  * Persistence_put().
+  * @return Return 0 if the function completes successfully, otherwise return
+  * ::MQTTCLIENT_PERSISTENCE_ERROR.
+  */
+typedef int (*Persistence_remove)(void* handle, char* key);
+
+/**
+  * @brief Returns the keys in this persistent data store.
+  *
+  * @param handle The handle pointer from a successful call to 
+  * Persistence_open().
+  * @param keys The address of a pointer to pointers to strings. Assuming
+  * successful execution, this function allocates memory to hold the returned
+  * keys (strings used to store the data with Persistence_put()). It also 
+  * allocates memory to hold an array of pointers to these strings. <i>keys</i>
+  * is set to point to the array of pointers to strings.
+  * @param nkeys A pointer to the number of keys in this persistent data store. 
+  * This function sets the number of keys, if successful.
+  * @return Return 0 if the function completes successfully, otherwise return
+  * ::MQTTCLIENT_PERSISTENCE_ERROR.
+  */
+typedef int (*Persistence_keys)(void* handle, char*** keys, int* nkeys);
+
+/**
+  * @brief Clears the persistence store, so that it no longer contains any 
+  * persisted data.
+  *
+  * @param handle The handle pointer from a successful call to 
+  * Persistence_open().
+  * @return Return 0 if the function completes successfully, otherwise return
+  * ::MQTTCLIENT_PERSISTENCE_ERROR.
+  */
+typedef int (*Persistence_clear)(void* handle);
+
+/**
+  * @brief Returns whether any data has been persisted using the specified key.
+  *
+  * @param handle The handle pointer from a successful call to 
+  * Persistence_open().
+  * @param key The string to be tested for existence in the store.
+  * @return Return 0 if the key was found in the store, otherwise return
+  * ::MQTTCLIENT_PERSISTENCE_ERROR.
+  */
+typedef int (*Persistence_containskey)(void* handle, char* key);
+
+/**
+  * @brief A structure containing the function pointers to a persistence 
+  * implementation and the context or state that will be shared across all 
+  * the persistence functions.
+  */
+typedef struct {
+  /** 
+    * A pointer to any data required to initialize the persistent store.
+    */
+	void* context;
+  /** 
+    * A function pointer to an implementation of Persistence_open().
+    */
+	Persistence_open popen;
+  /** 
+    * A function pointer to an implementation of Persistence_close().
+    */
+	Persistence_close pclose;
+  /**
+    * A function pointer to an implementation of Persistence_put().
+    */
+	Persistence_put pput;
+  /** 
+    * A function pointer to an implementation of Persistence_get().
+    */
+	Persistence_get pget;
+  /** 
+    * A function pointer to an implementation of Persistence_remove().
+    */
+	Persistence_remove premove;
+  /** 
+    * A function pointer to an implementation of Persistence_keys().
+    */
+	Persistence_keys pkeys;
+  /** 
+    * A function pointer to an implementation of Persistence_clear().
+    */
+	Persistence_clear pclear;
+  /** 
+    * A function pointer to an implementation of Persistence_containskey().
+    */
+	Persistence_containskey pcontainskey;
+} MQTTClient_persistence;
+
+
+/**
+ * A callback which is invoked just before a write to persistence.  This can be
+ * used to transform the data, for instance to encrypt it.
+ * @param context The context as set in ::MQTTAsync_setBeforePersistenceWrite
+ * @param bufcount The number of buffers to write to the persistence store.
+ * @param buffers An array of pointers to the data buffers.
+ * @param buflens An array of lengths of the data buffers.
+ * @return Return 0 if the function completes successfully, otherwise non 0.
+ */
+typedef int MQTTPersistence_beforeWrite(void* context, int bufcount, char* buffers[], int buflens[]);
+
+
+/**
+ * A callback which is invoked just after a read from persistence.  This can be
+ * used to transform the data, for instance to decrypt it.
+ * @param context The context as set in ::MQTTAsync_setAfterPersistenceRead
+ * @param buffer The address of a pointer to a buffer.
+ * @param buflen The address of an int that is the length of the buffer.
+ * @return Return 0 if the function completes successfully, otherwise non 0.
+ */
+typedef int MQTTPersistence_afterRead(void* context, char** buffer, int* buflen);
+
+#endif

+ 36 - 0
library/include/MQTTExportDeclarations.h

@@ -0,0 +1,36 @@
+/*******************************************************************************
+ * Copyright (c) 2020, 2020 Andreas Walter
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v2.0
+ * and Eclipse Distribution License v1.0 which accompany this distribution.
+ *
+ * The Eclipse Public License is available at
+ *    https://www.eclipse.org/legal/epl-2.0/
+ * and the Eclipse Distribution License is available at
+ *   http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ *    Andreas Walter - initially moved export declarations into separate fle
+ *******************************************************************************/
+
+#if !defined(EXPORTDECLARATIONS_H)
+#define EXPORTDECLARATIONS_H
+
+#if defined(_WIN32) || defined(_WIN64)
+#   if defined(PAHO_MQTT_EXPORTS)
+#       define LIBMQTT_API __declspec(dllexport)
+#   elif defined(PAHO_MQTT_IMPORTS)
+#       define LIBMQTT_API __declspec(dllimport)
+#   else
+#       define LIBMQTT_API
+#   endif
+#else
+#    if defined(PAHO_MQTT_EXPORTS)
+#       define LIBMQTT_API  __attribute__ ((visibility ("default")))
+#    else
+#       define LIBMQTT_API extern
+#    endif
+#endif
+
+#endif

+ 222 - 0
library/include/MQTTProperties.h

@@ -0,0 +1,222 @@
+/*******************************************************************************
+ * Copyright (c) 2017, 2023 IBM Corp. and others
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v2.0
+ * and Eclipse Distribution License v1.0 which accompany this distribution.
+ *
+ * The Eclipse Public License is available at
+ *    https://www.eclipse.org/legal/epl-2.0/
+ * and the Eclipse Distribution License is available at
+ *   http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ *    Ian Craggs - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+
+#if !defined(MQTTPROPERTIES_H)
+#define MQTTPROPERTIES_H
+
+#include "MQTTExportDeclarations.h"
+
+#define MQTT_INVALID_PROPERTY_ID -2
+
+/** The one byte MQTT V5 property indicator */
+enum MQTTPropertyCodes {
+  MQTTPROPERTY_CODE_PAYLOAD_FORMAT_INDICATOR = 1,  /**< The value is 1 */
+  MQTTPROPERTY_CODE_MESSAGE_EXPIRY_INTERVAL = 2,   /**< The value is 2 */
+  MQTTPROPERTY_CODE_CONTENT_TYPE = 3,              /**< The value is 3 */
+  MQTTPROPERTY_CODE_RESPONSE_TOPIC = 8,            /**< The value is 8 */
+  MQTTPROPERTY_CODE_CORRELATION_DATA = 9,          /**< The value is 9 */
+  MQTTPROPERTY_CODE_SUBSCRIPTION_IDENTIFIER = 11,  /**< The value is 11 */
+  MQTTPROPERTY_CODE_SESSION_EXPIRY_INTERVAL = 17,  /**< The value is 17 */
+  MQTTPROPERTY_CODE_ASSIGNED_CLIENT_IDENTIFER = 18,/**< The value is 18 */
+  MQTTPROPERTY_CODE_SERVER_KEEP_ALIVE = 19,        /**< The value is 19 */
+  MQTTPROPERTY_CODE_AUTHENTICATION_METHOD = 21,    /**< The value is 21 */
+  MQTTPROPERTY_CODE_AUTHENTICATION_DATA = 22,      /**< The value is 22 */
+  MQTTPROPERTY_CODE_REQUEST_PROBLEM_INFORMATION = 23,/**< The value is 23 */
+  MQTTPROPERTY_CODE_WILL_DELAY_INTERVAL = 24,      /**< The value is 24 */
+  MQTTPROPERTY_CODE_REQUEST_RESPONSE_INFORMATION = 25,/**< The value is 25 */
+  MQTTPROPERTY_CODE_RESPONSE_INFORMATION = 26,     /**< The value is 26 */
+  MQTTPROPERTY_CODE_SERVER_REFERENCE = 28,         /**< The value is 28 */
+  MQTTPROPERTY_CODE_REASON_STRING = 31,            /**< The value is 31 */
+  MQTTPROPERTY_CODE_RECEIVE_MAXIMUM = 33,          /**< The value is 33*/
+  MQTTPROPERTY_CODE_TOPIC_ALIAS_MAXIMUM = 34,      /**< The value is 34 */
+  MQTTPROPERTY_CODE_TOPIC_ALIAS = 35,              /**< The value is 35 */
+  MQTTPROPERTY_CODE_MAXIMUM_QOS = 36,              /**< The value is 36 */
+  MQTTPROPERTY_CODE_RETAIN_AVAILABLE = 37,         /**< The value is 37 */
+  MQTTPROPERTY_CODE_USER_PROPERTY = 38,            /**< The value is 38 */
+  MQTTPROPERTY_CODE_MAXIMUM_PACKET_SIZE = 39,      /**< The value is 39 */
+  MQTTPROPERTY_CODE_WILDCARD_SUBSCRIPTION_AVAILABLE = 40,/**< The value is 40 */
+  MQTTPROPERTY_CODE_SUBSCRIPTION_IDENTIFIERS_AVAILABLE = 41,/**< The value is 41 */
+  MQTTPROPERTY_CODE_SHARED_SUBSCRIPTION_AVAILABLE = 42/**< The value is 241 */
+};
+
+/**
+ * Returns a printable string description of an MQTT V5 property code.
+ * @param value an MQTT V5 property code.
+ * @return the printable string description of the input property code.
+ * NULL if the code was not found.
+ */
+LIBMQTT_API const char* MQTTPropertyName(enum MQTTPropertyCodes value);
+
+/** The one byte MQTT V5 property type */
+enum MQTTPropertyTypes {
+  MQTTPROPERTY_TYPE_BYTE,
+  MQTTPROPERTY_TYPE_TWO_BYTE_INTEGER,
+  MQTTPROPERTY_TYPE_FOUR_BYTE_INTEGER,
+  MQTTPROPERTY_TYPE_VARIABLE_BYTE_INTEGER,
+  MQTTPROPERTY_TYPE_BINARY_DATA,
+  MQTTPROPERTY_TYPE_UTF_8_ENCODED_STRING,
+  MQTTPROPERTY_TYPE_UTF_8_STRING_PAIR
+};
+
+/**
+ * Returns the MQTT V5 type code of an MQTT V5 property.
+ * @param value an MQTT V5 property code.
+ * @return the MQTT V5 type code of the input property. -1 if the code was not found.
+ */
+LIBMQTT_API int MQTTProperty_getType(enum MQTTPropertyCodes value);
+
+/**
+ * The data for a length delimited string
+ */
+typedef struct
+{
+	int len; /**< the length of the string */
+	char* data; /**< pointer to the string data */
+} MQTTLenString;
+
+
+/**
+ * Structure to hold an MQTT version 5 property of any type
+ */
+typedef struct
+{
+  enum MQTTPropertyCodes identifier; /**<  The MQTT V5 property id. A multi-byte integer. */
+  /** The value of the property, as a union of the different possible types. */
+  union {
+    unsigned char byte;       /**< holds the value of a byte property type */
+    unsigned short integer2;  /**< holds the value of a 2 byte integer property type */
+    unsigned int integer4;    /**< holds the value of a 4 byte integer property type */
+    struct {
+      MQTTLenString data;  /**< The value of a string property, or the name of a user property. */
+      MQTTLenString value; /**< The value of a user property. */
+    };
+  } value;
+} MQTTProperty;
+
+/**
+ * MQTT version 5 property list
+ */
+typedef struct MQTTProperties
+{
+  int count;     /**< number of property entries in the array */
+  int max_count; /**< max number of properties that the currently allocated array can store */
+  int length;    /**< mbi: byte length of all properties */
+  MQTTProperty *array;  /**< array of properties */
+} MQTTProperties;
+
+#define MQTTProperties_initializer {0, 0, 0, NULL}
+
+/**
+ * Returns the length of the properties structure when serialized ready for network transmission.
+ * @param props an MQTT V5 property structure.
+ * @return the length in bytes of the properties when serialized.
+ */
+int MQTTProperties_len(MQTTProperties* props);
+
+/**
+ * Add a property pointer to the property array. Memory is allocated in this function,
+ * so MQTTClient_create or MQTTAsync_create must be called first to initialize the
+ * internal heap tracking. Alternatively MQTTAsync_global_init() can be called first
+ * or build with the HIGH_PERFORMANCE option which disables the heap tracking.
+ * @param props The property list to add the property to.
+ * @param prop The property to add to the list.
+ * @return 0 on success, -1 on failure.
+ */
+LIBMQTT_API int MQTTProperties_add(MQTTProperties* props, const MQTTProperty* prop);
+
+/**
+ * Serialize the given property list to a character buffer, e.g. for writing to the network.
+ * @param pptr pointer to the buffer - move the pointer as we add data
+ * @param properties pointer to the property list, can be NULL
+ * @return whether the write succeeded or not: number of bytes written, or < 0 on failure.
+ */
+int MQTTProperties_write(char** pptr, const MQTTProperties* properties);
+
+/**
+ * Reads a property list from a character buffer into an array.
+ * @param properties pointer to the property list to be filled. Should be initalized but empty.
+ * @param pptr pointer to the character buffer.
+ * @param enddata pointer to the end of the character buffer so we don't read beyond.
+ * @return 1 if the properties were read successfully.
+ */
+int MQTTProperties_read(MQTTProperties* properties, char** pptr, char* enddata);
+
+/**
+ * Free all memory allocated to the property list, including any to individual properties.
+ * @param properties pointer to the property list.
+ */
+LIBMQTT_API void MQTTProperties_free(MQTTProperties* properties);
+
+/**
+ * Copy the contents of a property list, allocating additional memory if needed.
+ * @param props pointer to the property list.
+ * @return the duplicated property list.
+ */
+LIBMQTT_API MQTTProperties MQTTProperties_copy(const MQTTProperties* props);
+
+/**
+ * Checks if property list contains a specific property.
+ * @param props pointer to the property list.
+ * @param propid the property id to check for.
+ * @return 1 if found, 0 if not.
+ */
+LIBMQTT_API int MQTTProperties_hasProperty(MQTTProperties *props, enum MQTTPropertyCodes propid);
+
+/**
+ * Returns the number of instances of a property id. Most properties can exist only once.
+ * User properties and subscription ids can exist more than once.
+ * @param props pointer to the property list.
+ * @param propid the property id to check for.
+ * @return the number of times found.  Can be 0.
+ */
+LIBMQTT_API int MQTTProperties_propertyCount(MQTTProperties *props, enum MQTTPropertyCodes propid);
+
+/**
+ * Returns the integer value of a specific property.  The property given must be a numeric type.
+ * @param props pointer to the property list.
+ * @param propid the property id to check for.
+ * @return the integer value of the property. -9999999 on failure.
+ */
+LIBMQTT_API int MQTTProperties_getNumericValue(MQTTProperties *props, enum MQTTPropertyCodes propid);
+
+/**
+ * Returns the integer value of a specific property when it's not the only instance.
+ * The property given must be a numeric type.
+ * @param props pointer to the property list.
+ * @param propid the property id to check for.
+ * @param index the instance number, starting at 0.
+ * @return the integer value of the property. -9999999 on failure.
+ */
+LIBMQTT_API int MQTTProperties_getNumericValueAt(MQTTProperties *props, enum MQTTPropertyCodes propid, int index);
+
+/**
+ * Returns a pointer to the property structure for a specific property.
+ * @param props pointer to the property list.
+ * @param propid the property id to check for.
+ * @return the pointer to the property structure if found.  NULL if not found.
+ */
+LIBMQTT_API MQTTProperty* MQTTProperties_getProperty(MQTTProperties *props, enum MQTTPropertyCodes propid);
+
+/**
+ * Returns a pointer to the property structure for a specific property when it's not the only instance.
+ * @param props pointer to the property list.
+ * @param propid the property id to check for.
+ * @param index the instance number, starting at 0.
+ * @return the pointer to the property structure if found.  NULL if not found.
+ */
+LIBMQTT_API MQTTProperty* MQTTProperties_getPropertyAt(MQTTProperties *props, enum MQTTPropertyCodes propid, int index);
+
+#endif /* MQTTPROPERTIES_H */

+ 79 - 0
library/include/MQTTReasonCodes.h

@@ -0,0 +1,79 @@
+/*******************************************************************************
+ * Copyright (c) 2017, 2020 IBM Corp. and others
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v2.0
+ * and Eclipse Distribution License v1.0 which accompany this distribution.
+ *
+ * The Eclipse Public License is available at
+ *    https://www.eclipse.org/legal/epl-2.0/
+ * and the Eclipse Distribution License is available at
+ *   http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ *    Ian Craggs - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+
+#if !defined(MQTTREASONCODES_H)
+#define MQTTREASONCODES_H
+
+#include "MQTTExportDeclarations.h"
+
+/** The MQTT V5 one byte reason code */
+enum MQTTReasonCodes {
+  MQTTREASONCODE_SUCCESS = 0,
+  MQTTREASONCODE_NORMAL_DISCONNECTION = 0,
+  MQTTREASONCODE_GRANTED_QOS_0 = 0,
+  MQTTREASONCODE_GRANTED_QOS_1 = 1,
+  MQTTREASONCODE_GRANTED_QOS_2 = 2,
+  MQTTREASONCODE_DISCONNECT_WITH_WILL_MESSAGE = 4,
+  MQTTREASONCODE_NO_MATCHING_SUBSCRIBERS = 16,
+  MQTTREASONCODE_NO_SUBSCRIPTION_FOUND = 17,
+  MQTTREASONCODE_CONTINUE_AUTHENTICATION = 24,
+  MQTTREASONCODE_RE_AUTHENTICATE = 25,
+  MQTTREASONCODE_UNSPECIFIED_ERROR = 128,
+  MQTTREASONCODE_MALFORMED_PACKET = 129,
+  MQTTREASONCODE_PROTOCOL_ERROR = 130,
+  MQTTREASONCODE_IMPLEMENTATION_SPECIFIC_ERROR = 131,
+  MQTTREASONCODE_UNSUPPORTED_PROTOCOL_VERSION = 132,
+  MQTTREASONCODE_CLIENT_IDENTIFIER_NOT_VALID = 133,
+  MQTTREASONCODE_BAD_USER_NAME_OR_PASSWORD = 134,
+  MQTTREASONCODE_NOT_AUTHORIZED = 135,
+  MQTTREASONCODE_SERVER_UNAVAILABLE = 136,
+  MQTTREASONCODE_SERVER_BUSY = 137,
+  MQTTREASONCODE_BANNED = 138,
+  MQTTREASONCODE_SERVER_SHUTTING_DOWN = 139,
+  MQTTREASONCODE_BAD_AUTHENTICATION_METHOD = 140,
+  MQTTREASONCODE_KEEP_ALIVE_TIMEOUT = 141,
+  MQTTREASONCODE_SESSION_TAKEN_OVER = 142,
+  MQTTREASONCODE_TOPIC_FILTER_INVALID = 143,
+  MQTTREASONCODE_TOPIC_NAME_INVALID = 144,
+  MQTTREASONCODE_PACKET_IDENTIFIER_IN_USE = 145,
+  MQTTREASONCODE_PACKET_IDENTIFIER_NOT_FOUND = 146,
+  MQTTREASONCODE_RECEIVE_MAXIMUM_EXCEEDED = 147,
+  MQTTREASONCODE_TOPIC_ALIAS_INVALID = 148,
+  MQTTREASONCODE_PACKET_TOO_LARGE = 149,
+  MQTTREASONCODE_MESSAGE_RATE_TOO_HIGH = 150,
+  MQTTREASONCODE_QUOTA_EXCEEDED = 151,
+  MQTTREASONCODE_ADMINISTRATIVE_ACTION = 152,
+  MQTTREASONCODE_PAYLOAD_FORMAT_INVALID = 153,
+  MQTTREASONCODE_RETAIN_NOT_SUPPORTED = 154,
+  MQTTREASONCODE_QOS_NOT_SUPPORTED = 155,
+  MQTTREASONCODE_USE_ANOTHER_SERVER = 156,
+  MQTTREASONCODE_SERVER_MOVED = 157,
+  MQTTREASONCODE_SHARED_SUBSCRIPTIONS_NOT_SUPPORTED = 158,
+  MQTTREASONCODE_CONNECTION_RATE_EXCEEDED = 159,
+  MQTTREASONCODE_MAXIMUM_CONNECT_TIME = 160,
+  MQTTREASONCODE_SUBSCRIPTION_IDENTIFIERS_NOT_SUPPORTED = 161,
+  MQTTREASONCODE_WILDCARD_SUBSCRIPTIONS_NOT_SUPPORTED = 162
+};
+
+/**
+ * Returns a printable string description of an MQTT V5 reason code.
+ * @param value an MQTT V5 reason code.
+ * @return the printable string description of the input reason code.
+ * NULL if the code was not found.
+ */
+LIBMQTT_API const char* MQTTReasonCode_toString(enum MQTTReasonCodes value);
+
+#endif

+ 46 - 0
library/include/MQTTSubscribeOpts.h

@@ -0,0 +1,46 @@
+/*******************************************************************************
+ * Copyright (c) 2018 IBM Corp.
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v2.0
+ * and Eclipse Distribution License v1.0 which accompany this distribution.
+ *
+ * The Eclipse Public License is available at
+ *    https://www.eclipse.org/legal/epl-2.0/
+ * and the Eclipse Distribution License is available at
+ *   http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ *    Ian Craggs - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+
+#if !defined(SUBOPTS_H)
+#define SUBOPTS_H
+
+/** The MQTT V5 subscribe options, apart from QoS which existed before V5. */
+typedef struct MQTTSubscribe_options
+{
+	/** The eyecatcher for this structure. Must be MQSO. */
+	char struct_id[4];
+	/** The version number of this structure.  Must be 0.
+	 */
+	int struct_version;
+	/** To not receive our own publications, set to 1.
+	 *  0 is the original MQTT behaviour - all messages matching the subscription are received.
+	 */
+	unsigned char noLocal;
+	/** To keep the retain flag as on the original publish message, set to 1.
+	 *  If 0, defaults to the original MQTT behaviour where the retain flag is only set on
+	 *  publications sent by a broker if in response to a subscribe request.
+	 */
+	unsigned char retainAsPublished;
+	/** 0 - send retained messages at the time of the subscribe (original MQTT behaviour)
+	 *  1 - send retained messages on subscribe only if the subscription is new
+	 *  2 - do not send retained messages at all
+	 */
+	unsigned char retainHandling;
+} MQTTSubscribe_options;
+
+#define MQTTSubscribe_options_initializer { {'M', 'Q', 'S', 'O'}, 0, 0, 0, 0 }
+
+#endif

二进制
library/include/boost/.DS_Store


+ 27 - 0
library/include/boost/accumulators/accumulators.hpp

@@ -0,0 +1,27 @@
+///////////////////////////////////////////////////////////////////////////////
+/// \file accumulators.hpp
+/// Includes all of the Accumulators Framework
+//
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_ACCUMULATORS_HPP_EAN_28_10_2005
+#define BOOST_ACCUMULATORS_ACCUMULATORS_HPP_EAN_28_10_2005
+
+#include <boost/accumulators/framework/accumulator_set.hpp>
+#include <boost/accumulators/framework/accumulator_concept.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/framework/external.hpp>
+#include <boost/accumulators/framework/features.hpp>
+#include <boost/accumulators/framework/parameters/accumulator.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/framework/parameters/weight.hpp>
+#include <boost/accumulators/framework/parameters/weights.hpp>
+#include <boost/accumulators/framework/accumulators/external_accumulator.hpp>
+#include <boost/accumulators/framework/accumulators/droppable_accumulator.hpp>
+#include <boost/accumulators/framework/accumulators/reference_accumulator.hpp>
+#include <boost/accumulators/framework/accumulators/value_accumulator.hpp>
+
+#endif

+ 232 - 0
library/include/boost/accumulators/accumulators_fwd.hpp

@@ -0,0 +1,232 @@
+///////////////////////////////////////////////////////////////////////////////
+// accumulators_fwd.hpp
+//
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_ACCUMULATORS_FWD_HPP_EAN_28_10_2005
+#define BOOST_ACCUMULATORS_ACCUMULATORS_FWD_HPP_EAN_28_10_2005
+
+#include <boost/config.hpp>
+#include <boost/core/enable_if.hpp>
+#include <boost/parameter/is_argument_pack.hpp>
+#include <boost/mpl/apply_fwd.hpp> // for mpl::na
+#include <boost/mpl/limits/vector.hpp>
+#include <boost/preprocessor/cat.hpp>
+#include <boost/preprocessor/arithmetic/inc.hpp>
+#include <boost/preprocessor/repetition/enum_params_with_a_default.hpp>
+#include <boost/preprocessor/repetition/enum_trailing_params.hpp>
+#include <boost/preprocessor/repetition/enum_trailing_binary_params.hpp>
+#include <boost/preprocessor/repetition/repeat_from_to.hpp>
+#include <boost/accumulators/numeric/functional_fwd.hpp>
+
+#ifndef BOOST_ACCUMULATORS_MAX_FEATURES
+  /// The maximum number of accumulators that may be put in an accumulator_set.
+  /// Defaults to BOOST_MPL_LIMIT_VECTOR_SIZE (which defaults to 20).
+# define BOOST_ACCUMULATORS_MAX_FEATURES BOOST_MPL_LIMIT_VECTOR_SIZE
+#endif
+
+#if BOOST_ACCUMULATORS_MAX_FEATURES > BOOST_MPL_LIMIT_VECTOR_SIZE
+# error BOOST_ACCUMULATORS_MAX_FEATURES cannot be larger than BOOST_MPL_LIMIT_VECTOR_SIZE
+#endif
+
+#ifndef BOOST_ACCUMULATORS_MAX_ARGS
+  /// The maximum number of arguments that may be specified to an accumulator_set's
+  /// accumulation function. Defaults to 15.
+# define BOOST_ACCUMULATORS_MAX_ARGS 15
+#endif
+
+#if BOOST_WORKAROUND(__GNUC__, == 3) \
+ || BOOST_WORKAROUND(__EDG_VERSION__, BOOST_TESTED_AT(306))
+# define BOOST_ACCUMULATORS_BROKEN_CONST_OVERLOADS
+#endif
+
+#ifdef BOOST_ACCUMULATORS_BROKEN_CONST_OVERLOADS
+# include <boost/type_traits/is_const.hpp>
+# define BOOST_ACCUMULATORS_PROTO_DISABLE_IF_IS_CONST(T)\
+    , typename boost::disable_if<boost::is_const<T> >::type * = 0
+#else
+# define BOOST_ACCUMULATORS_PROTO_DISABLE_IF_IS_CONST(T)
+#endif
+
+#define BOOST_ACCUMULATORS_GCC_VERSION                                                              \
+  (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
+
+namespace boost { namespace accumulators
+{
+
+///////////////////////////////////////////////////////////////////////////////
+// Named parameters tags
+//
+namespace tag
+{
+    struct sample;
+    struct weight;
+    struct accumulator;
+    struct weights;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// User-level features
+//
+namespace tag
+{
+    template<typename ValueType, typename Tag>
+    struct value;
+
+    template<typename Tag>
+    struct value_tag;
+
+    template<typename Referent, typename Tag>
+    struct reference;
+
+    template<typename Tag>
+    struct reference_tag;
+
+    template<typename Type, typename Tag = void, typename AccumulatorSet = void>
+    struct external;
+
+    template<typename Feature>
+    struct droppable;
+}
+
+template<typename Accumulator>
+struct droppable_accumulator_base;
+
+template<typename Accumulator>
+struct droppable_accumulator;
+
+template<typename Accumulator>
+struct with_cached_result;
+
+template<typename Sample, typename Features, typename Weight = void>
+struct accumulator_set;
+
+template<typename Feature>
+struct extractor;
+
+template<typename Feature>
+struct feature_of;
+
+template<typename Feature>
+struct as_feature;
+
+template<typename Feature>
+struct as_weighted_feature;
+
+template<BOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT(BOOST_ACCUMULATORS_MAX_FEATURES, typename Feature, mpl::na)>
+struct depends_on;
+
+template<BOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT(BOOST_ACCUMULATORS_MAX_FEATURES, typename Feature, mpl::na)>
+struct features;
+
+template<typename Feature, typename AccumulatorSet>
+typename mpl::apply<AccumulatorSet, Feature>::type const &
+find_accumulator(AccumulatorSet const &acc);
+
+template<typename Feature, typename AccumulatorSet>
+typename mpl::apply<AccumulatorSet, Feature>::type::result_type
+extract_result(AccumulatorSet const &acc);
+
+namespace detail
+{
+    struct _enabler
+    {
+    };
+}
+
+// ... other overloads generated by Boost.Preprocessor:
+
+/// INTERNAL ONLY
+///
+#define BOOST_ACCUMULATORS_EXTRACT_RESULT_FWD(z, n, _)                      \
+    template<                                                               \
+        typename Feature                                                    \
+      , typename AccumulatorSet                                             \
+        BOOST_PP_ENUM_TRAILING_PARAMS_Z(z, n, typename A)                   \
+    >                                                                       \
+    typename mpl::apply<AccumulatorSet, Feature>::type::result_type         \
+    extract_result(                                                         \
+        AccumulatorSet const &acc                                           \
+        BOOST_PP_ENUM_TRAILING_BINARY_PARAMS_Z(z, n, A, const &a)           \
+      , typename boost::enable_if<                                          \
+            parameter::is_argument_pack<A0>                                 \
+          , detail::_enabler                                                \
+        >::type = detail::_enabler()                                        \
+    );                                                                      \
+    template<                                                               \
+        typename Feature                                                    \
+      , typename AccumulatorSet                                             \
+        BOOST_PP_ENUM_TRAILING_PARAMS_Z(z, n, typename A)                   \
+    >                                                                       \
+    typename mpl::apply<AccumulatorSet, Feature>::type::result_type         \
+    extract_result(                                                         \
+        AccumulatorSet const &acc                                           \
+        BOOST_PP_ENUM_TRAILING_BINARY_PARAMS_Z(z, n, A, const &a)           \
+      , typename boost::disable_if<                                         \
+            parameter::is_argument_pack<A0>                                 \
+          , detail::_enabler                                                \
+        >::type = detail::_enabler()                                        \
+    );
+
+/// INTERNAL ONLY
+///
+BOOST_PP_REPEAT_FROM_TO(
+    1
+  , BOOST_PP_INC(BOOST_ACCUMULATORS_MAX_ARGS)
+  , BOOST_ACCUMULATORS_EXTRACT_RESULT_FWD
+  , _
+)
+
+#undef BOOST_ACCUMULATORS_EXTRACT_RESULT_FWD
+
+#ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED
+template<typename Feature, typename AccumulatorSet, typename A1, typename A2 ...>
+typename mpl::apply<AccumulatorSet, Feature>::type::result_type
+extract_result(AccumulatorSet const &acc, A1 const &a1, A2 const &a2 ...);
+#endif
+
+namespace impl
+{
+    using namespace numeric::operators;
+
+    template<typename Accumulator, typename Tag>
+    struct external_impl;
+}
+
+namespace detail
+{
+    template<typename Accumulator>
+    struct feature_tag;
+
+    template<typename Feature, typename Sample, typename Weight>
+    struct to_accumulator;
+
+    struct accumulator_set_base;
+
+    template<typename T>
+    struct is_accumulator_set;
+
+    inline void ignore_variable(void const *) {}
+}
+
+}} // namespace boost::accumulators
+
+#define BOOST_ACCUMULATORS_IGNORE_GLOBAL(X)                             \
+    namespace detail                                                    \
+    {                                                                   \
+        struct BOOST_PP_CAT(ignore_, X)                                 \
+        {                                                               \
+            void ignore()                                               \
+            {                                                           \
+                boost::accumulators::detail::ignore_variable(&X);       \
+            }                                                           \
+        };                                                              \
+    }                                                                   \
+    /**/
+
+#include <boost/parameter/nested_keyword.hpp>
+
+#endif  // include guard
+

+ 65 - 0
library/include/boost/accumulators/framework/accumulator_base.hpp

@@ -0,0 +1,65 @@
+///////////////////////////////////////////////////////////////////////////////
+// accumulator_base.hpp
+//
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATORS_BASE_HPP_EAN_28_10_2005
+#define BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATORS_BASE_HPP_EAN_28_10_2005
+
+#include <boost/mpl/placeholders.hpp>
+#include <boost/mpl/joint_view.hpp>
+#include <boost/mpl/single_view.hpp>
+#include <boost/mpl/fold.hpp>
+#include <boost/mpl/contains.hpp>
+#include <boost/mpl/empty_sequence.hpp>
+#include <boost/accumulators/framework/accumulator_concept.hpp>
+
+namespace boost { namespace accumulators
+{
+
+namespace detail
+{
+    typedef void void_;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// dont_care
+//
+struct dont_care
+{
+    template<typename Args>
+    dont_care(Args const &)
+    {
+    }
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// accumulator_base
+//
+struct accumulator_base
+{
+    // hidden if defined in derived classes
+    detail::void_ operator ()(dont_care)
+    {
+    }
+
+    typedef mpl::false_ is_droppable;
+
+    detail::void_ add_ref(dont_care)
+    {
+    }
+
+    detail::void_ drop(dont_care)
+    {
+    }
+
+    detail::void_ on_drop(dont_care)
+    {
+    }
+};
+
+}} // namespace boost::accumulators
+
+#endif

+ 29 - 0
library/include/boost/accumulators/framework/accumulator_concept.hpp

@@ -0,0 +1,29 @@
+///////////////////////////////////////////////////////////////////////////////
+// accumulator_concept.hpp
+//
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATOR_CONCEPT_HPP_EAN_28_10_2005
+#define BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATOR_CONCEPT_HPP_EAN_28_10_2005
+
+#include <boost/concept_check.hpp>
+
+namespace boost { namespace accumulators
+{
+
+template<typename Stat>
+struct accumulator_concept
+{
+    void constraints()
+    {
+        // TODO: define the stat concept
+    }
+
+    Stat stat;
+};
+
+}} // namespace boost::accumulators
+
+#endif

+ 549 - 0
library/include/boost/accumulators/framework/accumulator_set.hpp

@@ -0,0 +1,549 @@
+///////////////////////////////////////////////////////////////////////////////
+// accumulator_set.hpp
+//
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATOR_SET_HPP_EAN_28_10_2005
+#define BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATOR_SET_HPP_EAN_28_10_2005
+
+#include <boost/version.hpp>
+#include <boost/mpl/bool.hpp>
+#include <boost/mpl/if.hpp>
+#include <boost/mpl/apply.hpp>
+#include <boost/mpl/assert.hpp>
+#include <boost/mpl/protect.hpp>
+#include <boost/mpl/identity.hpp>
+#include <boost/mpl/is_sequence.hpp>
+#include <boost/type_traits/is_same.hpp>
+#include <boost/type_traits/is_base_of.hpp>
+#include <boost/type_traits/remove_const.hpp>
+#include <boost/type_traits/remove_reference.hpp>
+#include <boost/core/enable_if.hpp>
+#include <boost/parameter/is_argument_pack.hpp>
+#include <boost/preprocessor/repetition/repeat_from_to.hpp>
+#include <boost/preprocessor/repetition/enum_params.hpp>
+#include <boost/preprocessor/repetition/enum_binary_params.hpp>
+#include <boost/preprocessor/repetition/enum_trailing_params.hpp>
+#include <boost/accumulators/accumulators_fwd.hpp>
+#include <boost/accumulators/framework/depends_on.hpp>
+#include <boost/accumulators/framework/accumulator_concept.hpp>
+#include <boost/accumulators/framework/parameters/accumulator.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/framework/accumulators/external_accumulator.hpp>
+#include <boost/accumulators/framework/accumulators/droppable_accumulator.hpp>
+#include <boost/fusion/include/any.hpp>
+#include <boost/fusion/include/find_if.hpp>
+#include <boost/fusion/include/for_each.hpp>
+#include <boost/fusion/include/filter_view.hpp>
+
+namespace boost { namespace accumulators
+{
+
+namespace detail
+{
+    ///////////////////////////////////////////////////////////////////////////////
+    // accumulator_visitor
+    //   wrap a boost::parameter argument pack in a Fusion extractor object
+    template<typename Args>
+    struct accumulator_visitor
+    {
+        explicit accumulator_visitor(Args const &a)
+          : args(a)
+        {
+        }
+
+        accumulator_visitor(accumulator_visitor const &other)
+          : args(other.args)
+        {
+        }
+
+        template<typename Accumulator>
+        void operator ()(Accumulator &accumulator) const
+        {
+            accumulator(this->args);
+        }
+
+    private:
+        BOOST_DELETED_FUNCTION(accumulator_visitor &operator =(accumulator_visitor const &))
+        Args const &args;
+    };
+
+    template<typename Args>
+    inline accumulator_visitor<Args> const make_accumulator_visitor(Args const &args)
+    {
+        return accumulator_visitor<Args>(args);
+    }
+
+    ///////////////////////////////////////////////////////////////////////////////
+    // accumulator_set_base
+    struct accumulator_set_base
+    {
+    };
+
+    ///////////////////////////////////////////////////////////////////////////////
+    // is_accumulator_set
+    template<typename T>
+    struct is_accumulator_set
+      : mpl::if_<
+            boost::is_base_of<
+                accumulator_set_base
+              , typename boost::remove_const<
+                    typename boost::remove_reference<T>::type
+                >::type
+            >
+          , mpl::true_
+          , mpl::false_
+        >::type
+    {
+    };
+
+    // function object that serialize an accumulator
+    template<typename Archive>
+    struct serialize_accumulator
+    {
+        serialize_accumulator(Archive & _ar, const unsigned int _file_version) :
+            ar(_ar), file_version(_file_version)
+        {}
+
+        template<typename Accumulator>
+        void operator ()(Accumulator &accumulator)
+        {
+            accumulator.serialize(ar, file_version);
+        }
+
+    private:
+        Archive& ar;
+        const unsigned int file_version;
+    };
+
+} // namespace detail
+
+#ifdef _MSC_VER
+#pragma warning(push)
+#pragma warning(disable: 4355) // warning C4355: 'this' : used in base member initializer list
+#endif
+
+///////////////////////////////////////////////////////////////////////////////
+/// \brief A set of accumulators.
+///
+/// accumulator_set resolves the dependencies between features and ensures that
+/// the accumulators in the set are updated in the proper order.
+///
+/// acccumulator_set provides a general mechanism to visit the accumulators
+/// in the set in order, with or without a filter. You can also fetch a reference
+/// to an accumulator that corresponds to a feature.
+///
+template<typename Sample, typename Features, typename Weight>
+struct accumulator_set
+  : detail::accumulator_set_base
+{
+    typedef Sample sample_type;     ///< The type of the samples that will be accumulated
+    typedef Features features_type; ///< An MPL sequence of the features that should be accumulated.
+    typedef Weight weight_type;     ///< The type of the weight parameter. Must be a scalar. Defaults to void.
+
+    /// INTERNAL ONLY
+    ///
+    typedef
+        typename detail::make_accumulator_tuple<
+            Features
+          , Sample
+          , Weight
+        >::type
+    accumulators_mpl_vector;
+
+    // generate a fusion::list of accumulators
+    /// INTERNAL ONLY
+    ///
+    typedef
+        typename detail::meta::make_acc_list<
+            accumulators_mpl_vector
+        >::type
+    accumulators_type;
+
+    /// INTERNAL ONLY
+    ///
+    //BOOST_MPL_ASSERT((mpl::is_sequence<accumulators_type>));
+
+    ///////////////////////////////////////////////////////////////////////////////
+    /// default-construct all contained accumulators
+    accumulator_set()
+      : accumulators(
+            detail::make_acc_list(
+                accumulators_mpl_vector()
+              , (boost::accumulators::accumulator = *this)
+            )
+        )
+    {
+        // Add-ref the Features that the user has specified
+        this->template visit_if<detail::contains_feature_of_<Features> >(
+            detail::make_add_ref_visitor(boost::accumulators::accumulator = *this)
+        );
+    }
+
+    /// \overload
+    ///
+    /// \param a1 Optional named parameter to be passed to all the accumulators
+    template<typename A1>
+    explicit accumulator_set(
+        A1 const &a1
+      , typename boost::enable_if<
+            parameter::is_argument_pack<A1>
+          , detail::_enabler
+        >::type = detail::_enabler()
+    ) : accumulators(
+            detail::make_acc_list(
+                accumulators_mpl_vector()
+              , (boost::accumulators::accumulator = *this, a1)
+            )
+        )
+    {
+        // Add-ref the Features that the user has specified
+        this->template visit_if<detail::contains_feature_of_<Features> >(
+            detail::make_add_ref_visitor(boost::accumulators::accumulator = *this)
+        );
+    }
+
+    /// \overload
+    ///
+    /// \param a1 Optional sample parameter to be passed to all the accumulators
+    template<typename A1>
+    explicit accumulator_set(
+        A1 const &a1
+      , typename boost::disable_if<
+            parameter::is_argument_pack<A1>
+          , detail::_enabler
+        >::type = detail::_enabler()
+    ) : accumulators(
+            detail::make_acc_list(
+                accumulators_mpl_vector()
+              , (
+                    boost::accumulators::accumulator = *this
+                  , boost::accumulators::sample = a1
+                )
+            )
+        )
+    {
+        // Add-ref the Features that the user has specified
+        this->template visit_if<detail::contains_feature_of_<Features> >(
+            detail::make_add_ref_visitor(boost::accumulators::accumulator = *this)
+        );
+    }
+
+    // ... other overloads generated by Boost.Preprocessor:
+
+    /// INTERNAL ONLY
+    ///
+#define BOOST_ACCUMULATORS_ACCUMULATOR_SET_CTOR(z, n, _)                                \
+    template<BOOST_PP_ENUM_PARAMS_Z(z, n, typename A)>                                  \
+    accumulator_set(                                                                    \
+        BOOST_PP_ENUM_BINARY_PARAMS_Z(z, n, A, const &a)                                \
+      , typename boost::enable_if<                                                      \
+            parameter::is_argument_pack<A0>                                             \
+          , detail::_enabler                                                            \
+        >::type = detail::_enabler()                                                    \
+    ) : accumulators(                                                                   \
+            detail::make_acc_list(                                                      \
+                accumulators_mpl_vector()                                               \
+              , (                                                                       \
+                    boost::accumulators::accumulator = *this                            \
+                    BOOST_PP_ENUM_TRAILING_PARAMS_Z(z, n, a)                            \
+                )                                                                       \
+            )                                                                           \
+        )                                                                               \
+    {                                                                                   \
+        /* Add-ref the Features that the user has specified */                          \
+        this->template visit_if<detail::contains_feature_of_<Features> >(               \
+            detail::make_add_ref_visitor(boost::accumulators::accumulator = *this)      \
+        );                                                                              \
+    }                                                                                   \
+    template<BOOST_PP_ENUM_PARAMS_Z(z, n, typename A)>                                  \
+    accumulator_set(                                                                    \
+        BOOST_PP_ENUM_BINARY_PARAMS_Z(z, n, A, const &a)                                \
+      , typename boost::disable_if<                                                     \
+            parameter::is_argument_pack<A0>                                             \
+          , detail::_enabler                                                            \
+        >::type = detail::_enabler()                                                    \
+    ) : accumulators(                                                                   \
+            detail::make_acc_list(                                                      \
+                accumulators_mpl_vector()                                               \
+              , (                                                                       \
+                    boost::accumulators::accumulator = *this                            \
+                  , boost::accumulators::sample = BOOST_PP_ENUM_PARAMS_Z(z, n, a)       \
+                )                                                                       \
+            )                                                                           \
+        )                                                                               \
+    {                                                                                   \
+        /* Add-ref the Features that the user has specified */                          \
+        this->template visit_if<detail::contains_feature_of_<Features> >(               \
+            detail::make_add_ref_visitor(boost::accumulators::accumulator = *this)      \
+        );                                                                              \
+    }
+
+    /// INTERNAL ONLY
+    ///
+    BOOST_PP_REPEAT_FROM_TO(
+        2
+      , BOOST_PP_INC(BOOST_ACCUMULATORS_MAX_ARGS)
+      , BOOST_ACCUMULATORS_ACCUMULATOR_SET_CTOR
+      , _
+    )
+
+    #ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED
+    /// \overload
+    ///
+    template<typename A1, typename A2, ...>
+    accumulator_set(A1 const &a1, A2 const &a2, ...);
+    #endif
+
+    // ... other overloads generated by Boost.Preprocessor below ...
+
+    ///////////////////////////////////////////////////////////////////////////////
+    /// Visitation
+    /// \param func UnaryFunction which is invoked with each accumulator in turn.
+    template<typename UnaryFunction>
+    void visit(UnaryFunction const &func)
+    {
+        fusion::for_each(this->accumulators, func);
+    }
+
+    ///////////////////////////////////////////////////////////////////////////////
+    /// Conditional visitation
+    /// \param func UnaryFunction which is invoked with each accumulator in turn,
+    ///     provided the accumulator satisfies the MPL predicate FilterPred.
+    template<typename FilterPred, typename UnaryFunction>
+    void visit_if(UnaryFunction const &func)
+    {
+        fusion::filter_view<accumulators_type, FilterPred> filtered_accs(this->accumulators);
+        fusion::for_each(filtered_accs, func);
+    }
+    
+    ///////////////////////////////////////////////////////////////////////////////
+    /// The return type of the operator() overloads is void.
+    typedef void result_type;
+
+    ///////////////////////////////////////////////////////////////////////////////
+    /// Accumulation
+    /// \param a1 Optional named parameter to be passed to all the accumulators
+    void operator ()()
+    {
+        this->visit(
+            detail::make_accumulator_visitor(
+                boost::accumulators::accumulator = *this
+            )
+        );
+    }
+
+    // ... other overloads generated by Boost.Preprocessor:
+
+    /// INTERNAL ONLY
+    ///
+#define BOOST_ACCUMULATORS_ACCUMULATOR_SET_FUN_OP(z, n, _)                              \
+    template<BOOST_PP_ENUM_PARAMS_Z(z, n, typename A)>                                  \
+    void operator ()(                                                                   \
+        BOOST_PP_ENUM_BINARY_PARAMS_Z(z, n, A, const &a)                                \
+      , typename boost::enable_if<                                                      \
+            parameter::is_argument_pack<A0>                                             \
+          , detail::_enabler                                                            \
+        >::type = detail::_enabler()                                                    \
+    )                                                                                   \
+    {                                                                                   \
+        this->visit(                                                                    \
+            detail::make_accumulator_visitor(                                           \
+                (                                                                       \
+                    boost::accumulators::accumulator = *this                            \
+                    BOOST_PP_ENUM_TRAILING_PARAMS_Z(z, n, a)                            \
+                )                                                                       \
+            )                                                                           \
+        );                                                                              \
+    }                                                                                   \
+    template<BOOST_PP_ENUM_PARAMS_Z(z, n, typename A)>                                  \
+    void operator ()(                                                                   \
+        BOOST_PP_ENUM_BINARY_PARAMS_Z(z, n, A, const &a)                                \
+      , typename boost::disable_if<                                                     \
+            parameter::is_argument_pack<A0>                                             \
+          , detail::_enabler                                                            \
+        >::type = detail::_enabler()                                                    \
+    )                                                                                   \
+    {                                                                                   \
+        this->visit(                                                                    \
+            detail::make_accumulator_visitor(                                           \
+                (                                                                       \
+                    boost::accumulators::accumulator = *this                            \
+                  , boost::accumulators::sample = BOOST_PP_ENUM_PARAMS_Z(z, n, a)       \
+                )                                                                       \
+            )                                                                           \
+        );                                                                              \
+    }
+
+    /// INTERNAL ONLY
+    ///
+    BOOST_PP_REPEAT_FROM_TO(
+        1
+      , BOOST_PP_INC(BOOST_ACCUMULATORS_MAX_ARGS)
+      , BOOST_ACCUMULATORS_ACCUMULATOR_SET_FUN_OP
+      , _
+    )
+
+    #ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED
+    /// \overload
+    ///
+    template<typename A1, typename A2, ...>
+    void operator ()(A1 const &a1, A2 const &a2, ...);
+    #endif
+
+    ///////////////////////////////////////////////////////////////////////////////
+    /// Extraction
+    template<typename Feature>
+    struct apply
+      : fusion::result_of::value_of<
+            typename fusion::result_of::find_if<
+                accumulators_type
+              , detail::matches_feature<Feature>
+            >::type
+        >
+    {
+    };
+
+    ///////////////////////////////////////////////////////////////////////////////
+    /// Extraction
+    template<typename Feature>
+    typename apply<Feature>::type &extract()
+    {
+        return *fusion::find_if<detail::matches_feature<Feature> >(this->accumulators);
+    }
+
+    /// \overload
+    template<typename Feature>
+    typename apply<Feature>::type const &extract() const
+    {
+        return *fusion::find_if<detail::matches_feature<Feature> >(this->accumulators);
+    }
+
+    ///////////////////////////////////////////////////////////////////////////////
+    /// Drop
+    template<typename Feature>
+    void drop()
+    {
+        // You can only drop the features that you have specified explicitly
+        typedef typename apply<Feature>::type the_accumulator;
+        BOOST_MPL_ASSERT((detail::contains_feature_of<Features, the_accumulator>));
+
+        typedef
+            typename feature_of<typename as_feature<Feature>::type>::type
+        the_feature;
+
+        (*fusion::find_if<detail::matches_feature<Feature> >(this->accumulators))
+            .drop(boost::accumulators::accumulator = *this);
+
+        // Also drop accumulators that this feature depends on
+        typedef typename the_feature::dependencies dependencies;
+        this->template visit_if<detail::contains_feature_of_<dependencies> >(
+            detail::make_drop_visitor(boost::accumulators::accumulator = *this)
+        );
+    }
+
+    // make the accumulator set serializeable
+    template<class Archive>
+    void serialize(Archive & ar, const unsigned int file_version)
+    {
+        detail::serialize_accumulator<Archive> serializer(ar, file_version);
+        fusion::for_each(this->accumulators, serializer);
+    }
+
+private:
+
+    accumulators_type accumulators;
+};
+
+#ifdef _MSC_VER
+#pragma warning(pop)
+#endif
+
+///////////////////////////////////////////////////////////////////////////////
+// find_accumulator
+//   find an accumulator in an accumulator_set corresponding to a feature
+template<typename Feature, typename AccumulatorSet>
+typename mpl::apply<AccumulatorSet, Feature>::type &
+find_accumulator(AccumulatorSet &acc BOOST_ACCUMULATORS_PROTO_DISABLE_IF_IS_CONST(AccumulatorSet))
+{
+    return acc.template extract<Feature>();
+}
+
+/// \overload
+template<typename Feature, typename AccumulatorSet>
+typename mpl::apply<AccumulatorSet, Feature>::type const &
+find_accumulator(AccumulatorSet const &acc)
+{
+    return acc.template extract<Feature>();
+}
+
+template<typename Feature, typename AccumulatorSet>
+typename mpl::apply<AccumulatorSet, Feature>::type::result_type
+extract_result(AccumulatorSet const &acc)
+{
+    return find_accumulator<Feature>(acc).result(
+        boost::accumulators::accumulator = acc
+    );
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// extract_result
+//   extract a result from an accumulator set
+/// INTERNAL ONLY
+///
+#define BOOST_ACCUMULATORS_EXTRACT_RESULT_FUN(z, n, _)                      \
+    template<                                                               \
+        typename Feature                                                    \
+      , typename AccumulatorSet                                             \
+        BOOST_PP_ENUM_TRAILING_PARAMS_Z(z, n, typename A)                   \
+    >                                                                       \
+    typename mpl::apply<AccumulatorSet, Feature>::type::result_type         \
+    extract_result(                                                         \
+        AccumulatorSet const &acc                                           \
+        BOOST_PP_ENUM_TRAILING_BINARY_PARAMS_Z(z, n, A, const &a)           \
+      , typename boost::enable_if<                                          \
+            parameter::is_argument_pack<A0>                                 \
+          , detail::_enabler                                                \
+        >::type                                                             \
+    )                                                                       \
+    {                                                                       \
+        return find_accumulator<Feature>(acc).result(                       \
+            (                                                               \
+                boost::accumulators::accumulator = acc                      \
+                BOOST_PP_ENUM_TRAILING_PARAMS_Z(z, n, a)                    \
+            )                                                               \
+        );                                                                  \
+    }                                                                       \
+    template<                                                               \
+        typename Feature                                                    \
+      , typename AccumulatorSet                                             \
+        BOOST_PP_ENUM_TRAILING_PARAMS_Z(z, n, typename A)                   \
+    >                                                                       \
+    typename mpl::apply<AccumulatorSet, Feature>::type::result_type         \
+    extract_result(                                                         \
+        AccumulatorSet const &acc                                           \
+        BOOST_PP_ENUM_TRAILING_BINARY_PARAMS_Z(z, n, A, const &a)           \
+      , typename boost::disable_if<                                         \
+            parameter::is_argument_pack<A0>                                 \
+          , detail::_enabler                                                \
+        >::type                                                             \
+    )                                                                       \
+    {                                                                       \
+        return find_accumulator<Feature>(acc).result((                      \
+            boost::accumulators::accumulator = acc                          \
+          , boost::accumulators::sample = BOOST_PP_ENUM_PARAMS_Z(z, n, a)   \
+        ));                                                                 \
+    }
+
+BOOST_PP_REPEAT_FROM_TO(
+    1
+  , BOOST_PP_INC(BOOST_ACCUMULATORS_MAX_ARGS)
+  , BOOST_ACCUMULATORS_EXTRACT_RESULT_FUN
+  , _
+)
+
+}} // namespace boost::accumulators
+
+#endif

+ 333 - 0
library/include/boost/accumulators/framework/accumulators/droppable_accumulator.hpp

@@ -0,0 +1,333 @@
+///////////////////////////////////////////////////////////////////////////////
+// droppable_accumulator.hpp
+//
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATORS_DROPPABLE_ACCUMULATOR_HPP_EAN_13_12_2005
+#define BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATORS_DROPPABLE_ACCUMULATOR_HPP_EAN_13_12_2005
+
+#include <new>
+#include <boost/assert.hpp>
+#include <boost/mpl/apply.hpp>
+#include <boost/aligned_storage.hpp>
+#include <boost/accumulators/framework/depends_on.hpp> // for feature_of
+#include <boost/accumulators/framework/parameters/accumulator.hpp> // for accumulator
+
+namespace boost { namespace accumulators
+{
+
+    template<typename Accumulator>
+    struct droppable_accumulator;
+
+    namespace detail
+    {
+        ///////////////////////////////////////////////////////////////////////////////
+        // add_ref_visitor
+        //   a fusion function object for add_ref'ing accumulators
+        template<typename Args>
+        struct add_ref_visitor
+        {
+            explicit add_ref_visitor(Args const &args)
+              : args_(args)
+            {
+            }
+
+            add_ref_visitor(add_ref_visitor const &other)
+              : args_(other.args_)
+            {
+            }
+
+            template<typename Accumulator>
+            void operator ()(Accumulator &acc) const
+            {
+                typedef typename Accumulator::feature_tag::dependencies dependencies;
+
+                acc.add_ref(this->args_);
+
+                // Also add_ref accumulators that this feature depends on
+                this->args_[accumulator].template
+                    visit_if<detail::contains_feature_of_<dependencies> >(
+                        *this
+                );
+            }
+
+        private:
+            BOOST_DELETED_FUNCTION(add_ref_visitor &operator =(add_ref_visitor const &))
+            Args const &args_;
+        };
+
+        template<typename Args>
+        add_ref_visitor<Args> make_add_ref_visitor(Args const &args)
+        {
+            return add_ref_visitor<Args>(args);
+        }
+
+        ///////////////////////////////////////////////////////////////////////////////
+        // drop_visitor
+        //   a fusion function object for dropping accumulators
+        template<typename Args>
+        struct drop_visitor
+        {
+            explicit drop_visitor(Args const &args)
+              : args_(args)
+            {
+            }
+
+            template<typename Accumulator>
+            void operator ()(Accumulator &acc) const
+            {
+                if(typename Accumulator::is_droppable())
+                {
+                    typedef typename Accumulator::feature_tag::dependencies dependencies;
+
+                    acc.drop(this->args_);
+                    // Also drop accumulators that this feature depends on
+                    this->args_[accumulator].template
+                        visit_if<detail::contains_feature_of_<dependencies> >(
+                            *this
+                    );
+                }
+            }
+
+        private:
+            BOOST_DELETED_FUNCTION(drop_visitor &operator =(drop_visitor const &))
+            Args const &args_;
+        };
+
+        template<typename Args>
+        drop_visitor<Args> make_drop_visitor(Args const &args)
+        {
+            return drop_visitor<Args>(args);
+        }
+    }
+
+    //////////////////////////////////////////////////////////////////////////
+    // droppable_accumulator_base
+    template<typename Accumulator>
+    struct droppable_accumulator_base
+      : Accumulator
+    {
+        typedef droppable_accumulator_base base;
+        typedef mpl::true_ is_droppable;
+        typedef typename Accumulator::result_type result_type;
+
+        template<typename Args>
+        droppable_accumulator_base(Args const &args)
+          : Accumulator(args)
+          , ref_count_(0)
+        {
+        }
+
+        droppable_accumulator_base(droppable_accumulator_base const &that)
+          : Accumulator(*static_cast<Accumulator const *>(&that))
+          , ref_count_(that.ref_count_)
+        {
+        }
+
+        template<typename Args>
+        void operator ()(Args const &args)
+        {
+            if(!this->is_dropped())
+            {
+                this->Accumulator::operator ()(args);
+            }
+        }
+
+        template<typename Args>
+        void add_ref(Args const &)
+        {
+            ++this->ref_count_;
+        }
+
+        template<typename Args>
+        void drop(Args const &args)
+        {
+            BOOST_ASSERT(0 < this->ref_count_);
+            if(1 == this->ref_count_)
+            {
+                static_cast<droppable_accumulator<Accumulator> *>(this)->on_drop(args);
+            }
+            --this->ref_count_;
+        }
+
+        bool is_dropped() const
+        {
+            return 0 == this->ref_count_;
+        }
+
+    private:
+        int ref_count_;
+    };
+
+    //////////////////////////////////////////////////////////////////////////
+    // droppable_accumulator
+    //   this can be specialized for any type that needs special handling
+    template<typename Accumulator>
+    struct droppable_accumulator
+      : droppable_accumulator_base<Accumulator>
+    {
+        template<typename Args>
+        droppable_accumulator(Args const &args)
+          : droppable_accumulator::base(args)
+        {
+        }
+
+        droppable_accumulator(droppable_accumulator const &that)
+          : droppable_accumulator::base(*static_cast<typename droppable_accumulator::base const *>(&that))
+        {
+        }
+    };
+
+    //////////////////////////////////////////////////////////////////////////
+    // with_cached_result
+    template<typename Accumulator>
+    struct with_cached_result
+      : Accumulator
+    {
+        typedef typename Accumulator::result_type result_type;
+
+        template<typename Args>
+        with_cached_result(Args const &args)
+          : Accumulator(args)
+          , cache()
+        {
+        }
+
+        with_cached_result(with_cached_result const &that)
+          : Accumulator(*static_cast<Accumulator const *>(&that))
+          , cache()
+        {
+            if(that.has_result())
+            {
+                this->set(that.get());
+            }
+        }
+
+        ~with_cached_result()
+        {
+            // Since this is a base class of droppable_accumulator_base,
+            // this destructor is called before any of droppable_accumulator_base's
+            // members get cleaned up, including is_dropped, so the following
+            // call to has_result() is valid.
+            if(this->has_result())
+            {
+                this->get().~result_type();
+            }
+        }
+
+        template<typename Args>
+        void on_drop(Args const &args)
+        {
+            // cache the result at the point this calculation was dropped
+            BOOST_ASSERT(!this->has_result());
+            this->set(this->Accumulator::result(args));
+        }
+
+        template<typename Args>
+        result_type result(Args const &args) const
+        {
+            return this->has_result() ? this->get() : this->Accumulator::result(args);
+        }
+
+    private:
+        BOOST_DELETED_FUNCTION(with_cached_result &operator =(with_cached_result const &))
+
+        void set(result_type const &r)
+        {
+            ::new(this->cache.address()) result_type(r);
+        }
+
+        result_type const &get() const
+        {
+            return *static_cast<result_type const *>(this->cache.address());
+        }
+
+        bool has_result() const
+        {
+            typedef with_cached_result<Accumulator> this_type;
+            typedef droppable_accumulator_base<this_type> derived_type;
+            return static_cast<derived_type const *>(this)->is_dropped();
+        }
+
+        aligned_storage<sizeof(result_type)> cache;
+    };
+
+    namespace tag
+    {
+        template<typename Feature>
+        struct as_droppable
+        {
+            typedef droppable<Feature> type;
+        };
+
+        template<typename Feature>
+        struct as_droppable<droppable<Feature> >
+        {
+            typedef droppable<Feature> type;
+        };
+
+        //////////////////////////////////////////////////////////////////////////
+        // droppable
+        template<typename Feature>
+        struct droppable
+          : as_feature<Feature>::type
+        {
+            typedef typename as_feature<Feature>::type feature_type;
+            typedef typename feature_type::dependencies tmp_dependencies_;
+
+            typedef
+                typename mpl::transform<
+                    typename feature_type::dependencies
+                  , as_droppable<mpl::_1>
+                >::type
+            dependencies;
+
+            struct impl
+            {
+                template<typename Sample, typename Weight>
+                struct apply
+                {
+                    typedef
+                        droppable_accumulator<
+                            typename mpl::apply2<typename feature_type::impl, Sample, Weight>::type
+                        >
+                    type;
+                };
+            };
+        };
+    }
+
+    // make droppable<tag::feature(modifier)> work
+    template<typename Feature>
+    struct as_feature<tag::droppable<Feature> >
+    {
+        typedef tag::droppable<typename as_feature<Feature>::type> type;
+    };
+
+    // make droppable<tag::mean> work with non-void weights (should become
+    // droppable<tag::weighted_mean>
+    template<typename Feature>
+    struct as_weighted_feature<tag::droppable<Feature> >
+    {
+        typedef tag::droppable<typename as_weighted_feature<Feature>::type> type;
+    };
+
+    // for the purposes of feature-based dependency resolution,
+    // droppable<Foo> provides the same feature as Foo
+    template<typename Feature>
+    struct feature_of<tag::droppable<Feature> >
+      : feature_of<Feature>
+    {
+    };
+
+    // Note: Usually, the extractor is pulled into the accumulators namespace with
+    // a using directive, not the tag. But the droppable<> feature doesn't have an
+    // extractor, so we can put the droppable tag in the accumulators namespace
+    // without fear of a name conflict.
+    using tag::droppable;
+
+}} // namespace boost::accumulators
+
+#endif

+ 108 - 0
library/include/boost/accumulators/framework/accumulators/external_accumulator.hpp

@@ -0,0 +1,108 @@
+///////////////////////////////////////////////////////////////////////////////
+// external_accumulator.hpp
+//
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATORS_EXTERNAL_ACCUMULATOR_HPP_EAN_01_12_2005
+#define BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATORS_EXTERNAL_ACCUMULATOR_HPP_EAN_01_12_2005
+
+#include <boost/mpl/placeholders.hpp>
+#include <boost/parameter/keyword.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/framework/depends_on.hpp> // for feature_tag
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/accumulators/reference_accumulator.hpp>
+
+namespace boost { namespace accumulators { namespace impl
+{
+
+    //////////////////////////////////////////////////////////////////////////
+    // external_impl
+    /// INTERNAL ONLY
+    ///
+    template<typename Accumulator, typename Tag>
+    struct external_impl
+      : accumulator_base
+    {
+        typedef typename Accumulator::result_type result_type;
+        typedef typename detail::feature_tag<Accumulator>::type feature_tag;
+
+        external_impl(dont_care) {}
+
+        template<typename Args>
+        result_type result(Args const &args) const
+        {
+            return this->extract_(args, args[parameter::keyword<Tag>::instance | 0]);
+        }
+
+    private:
+
+        template<typename Args>
+        static result_type extract_(Args const &args, int)
+        {
+            // No named parameter passed to the extractor. Maybe the external
+            // feature is held by reference<>.
+            extractor<feature_tag> extract;
+            return extract(accumulators::reference_tag<Tag>(args));
+        }
+
+        template<typename Args, typename AccumulatorSet>
+        static result_type extract_(Args const &, AccumulatorSet const &acc)
+        {
+            // OK, a named parameter for this external feature was passed to the
+            // extractor, so use that.
+            extractor<feature_tag> extract;
+            return extract(acc);
+        }
+    };
+
+} // namespace impl
+
+namespace tag
+{
+    //////////////////////////////////////////////////////////////////////////
+    // external
+    template<typename Feature, typename Tag, typename AccumulatorSet>
+    struct external
+      : depends_on<reference<AccumulatorSet, Tag> >
+    {
+        typedef
+            accumulators::impl::external_impl<
+                detail::to_accumulator<Feature, mpl::_1, mpl::_2>
+              , Tag
+            >
+        impl;
+    };
+
+    template<typename Feature, typename Tag>
+    struct external<Feature, Tag, void>
+      : depends_on<>
+    {
+        typedef
+            accumulators::impl::external_impl<
+                detail::to_accumulator<Feature, mpl::_1, mpl::_2>
+              , Tag
+            >
+        impl;
+    };
+}
+
+// for the purposes of feature-based dependency resolution,
+// external_accumulator<Feature, Tag> provides the same feature as Feature
+template<typename Feature, typename Tag, typename AccumulatorSet>
+struct feature_of<tag::external<Feature, Tag, AccumulatorSet> >
+  : feature_of<Feature>
+{
+};
+
+// Note: Usually, the extractor is pulled into the accumulators namespace with
+// a using directive, not the tag. But the external<> feature doesn't have an
+// extractor, so we can put the external tag in the accumulators namespace
+// without fear of a name conflict.
+using tag::external;
+
+}} // namespace boost::accumulators
+
+#endif

+ 89 - 0
library/include/boost/accumulators/framework/accumulators/reference_accumulator.hpp

@@ -0,0 +1,89 @@
+///////////////////////////////////////////////////////////////////////////////
+// reference_accumulator.hpp
+//
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATORS_REFERENCE_ACCUMULATOR_HPP_EAN_03_23_2006
+#define BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATORS_REFERENCE_ACCUMULATOR_HPP_EAN_03_23_2006
+
+#include <boost/ref.hpp>
+#include <boost/mpl/always.hpp>
+#include <boost/parameter/keyword.hpp>
+#include <boost/accumulators/framework/depends_on.hpp> // for feature_tag
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+
+namespace boost { namespace accumulators
+{
+
+namespace impl
+{
+    //////////////////////////////////////////////////////////////////////////
+    // reference_accumulator_impl
+    //
+    template<typename Referent, typename Tag>
+    struct reference_accumulator_impl
+      : accumulator_base
+    {
+        typedef Referent &result_type;
+
+        template<typename Args>
+        reference_accumulator_impl(Args const &args)
+          : ref(args[parameter::keyword<Tag>::instance])
+        {
+        }
+
+        result_type result(dont_care) const
+        {
+            return this->ref;
+        }
+
+    private:
+        reference_wrapper<Referent> ref;
+    };
+} // namespace impl
+
+namespace tag
+{
+    //////////////////////////////////////////////////////////////////////////
+    // reference_tag
+    template<typename Tag>
+    struct reference_tag
+    {
+    };
+
+    //////////////////////////////////////////////////////////////////////////
+    // reference
+    template<typename Referent, typename Tag>
+    struct reference
+      : depends_on<>
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef mpl::always<accumulators::impl::reference_accumulator_impl<Referent, Tag> > impl;
+    };
+}
+
+namespace extract
+{
+    BOOST_ACCUMULATORS_DEFINE_EXTRACTOR(tag, reference, (typename)(typename))
+    BOOST_ACCUMULATORS_DEFINE_EXTRACTOR(tag, reference_tag, (typename))
+}
+
+using extract::reference;
+using extract::reference_tag;
+
+// Map all reference<V,T> features to reference_tag<T> so
+// that references can be extracted using reference_tag<T>
+// without specifying the referent type.
+template<typename ValueType, typename Tag>
+struct feature_of<tag::reference<ValueType, Tag> >
+  : feature_of<tag::reference_tag<Tag> >
+{
+};
+
+}} // namespace boost::accumulators
+
+#endif

+ 89 - 0
library/include/boost/accumulators/framework/accumulators/value_accumulator.hpp

@@ -0,0 +1,89 @@
+///////////////////////////////////////////////////////////////////////////////
+// value_accumulator.hpp
+//
+//  Copyright 2005 Eric Niebler, Daniel Egloff. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATORS_VALUE_ACCUMULATOR_HPP_EAN_03_23_2006
+#define BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATORS_VALUE_ACCUMULATOR_HPP_EAN_03_23_2006
+
+#include <boost/mpl/always.hpp>
+#include <boost/parameter/keyword.hpp>
+#include <boost/accumulators/framework/depends_on.hpp> // for feature_tag
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+
+namespace boost { namespace accumulators
+{
+
+namespace impl
+{
+
+    //////////////////////////////////////////////////////////////////////////
+    // value_accumulator_impl
+    template<typename ValueType, typename Tag>
+    struct value_accumulator_impl
+      : accumulator_base
+    {
+        typedef ValueType result_type;
+
+        template<typename Args>
+        value_accumulator_impl(Args const &args)
+          : val(args[parameter::keyword<Tag>::instance])
+        {
+        }
+
+        result_type result(dont_care) const
+        {
+            return this->val;
+        }
+
+    private:
+        ValueType val;
+    };
+
+} // namespace impl
+
+namespace tag
+{
+    //////////////////////////////////////////////////////////////////////////
+    // value_tag
+    template<typename Tag>
+    struct value_tag
+    {
+    };
+
+    //////////////////////////////////////////////////////////////////////////
+    // value
+    template<typename ValueType, typename Tag>
+    struct value
+      : depends_on<>
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef mpl::always<accumulators::impl::value_accumulator_impl<ValueType, Tag> > impl;
+    };
+}
+
+namespace extract
+{
+    BOOST_ACCUMULATORS_DEFINE_EXTRACTOR(tag, value, (typename)(typename))
+    BOOST_ACCUMULATORS_DEFINE_EXTRACTOR(tag, value_tag, (typename))
+}
+
+using extract::value;
+using extract::value_tag;
+
+// Map all value<V,T> features to value_tag<T> so
+// that values can be extracted using value_tag<T>
+// without specifying the value type.
+template<typename ValueType, typename Tag>
+struct feature_of<tag::value<ValueType, Tag> >
+  : feature_of<tag::value_tag<Tag> >
+{
+};
+
+}} // namespace boost::accumulators
+
+#endif

+ 461 - 0
library/include/boost/accumulators/framework/depends_on.hpp

@@ -0,0 +1,461 @@
+///////////////////////////////////////////////////////////////////////////////
+// depends_on.hpp
+//
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_FRAMEWORK_DEPENDS_ON_HPP_EAN_28_10_2005
+#define BOOST_ACCUMULATORS_FRAMEWORK_DEPENDS_ON_HPP_EAN_28_10_2005
+
+#include <boost/version.hpp>
+#include <boost/mpl/end.hpp>
+#include <boost/mpl/map.hpp>
+#include <boost/mpl/set.hpp>
+#include <boost/mpl/copy.hpp>
+#include <boost/mpl/fold.hpp>
+#include <boost/mpl/size.hpp>
+#include <boost/mpl/sort.hpp>
+#include <boost/mpl/insert.hpp>
+#include <boost/mpl/assert.hpp>
+#include <boost/mpl/remove.hpp>
+#include <boost/mpl/vector.hpp>
+#include <boost/mpl/inherit.hpp>
+#include <boost/mpl/identity.hpp>
+#include <boost/mpl/equal_to.hpp>
+#include <boost/mpl/contains.hpp>
+#include <boost/mpl/transform.hpp>
+#include <boost/mpl/is_sequence.hpp>
+#include <boost/mpl/placeholders.hpp>
+#include <boost/mpl/insert_range.hpp>
+#include <boost/mpl/back_inserter.hpp>
+#include <boost/mpl/transform_view.hpp>
+#include <boost/mpl/inherit_linearly.hpp>
+#include <boost/type_traits/is_base_and_derived.hpp>
+#include <boost/preprocessor/repetition/repeat.hpp>
+#include <boost/preprocessor/repetition/enum_params.hpp>
+#include <boost/preprocessor/facilities/intercept.hpp>
+#include <boost/accumulators/accumulators_fwd.hpp>
+#include <boost/fusion/include/next.hpp>
+#include <boost/fusion/include/equal_to.hpp>
+#include <boost/fusion/include/value_of.hpp>
+#include <boost/fusion/include/mpl.hpp>
+#include <boost/fusion/include/end.hpp>
+#include <boost/fusion/include/begin.hpp>
+#include <boost/fusion/include/cons.hpp>
+
+namespace boost { namespace accumulators
+{
+    ///////////////////////////////////////////////////////////////////////////
+    // as_feature
+    template<typename Feature>
+    struct as_feature
+    {
+        typedef Feature type;
+    };
+
+    ///////////////////////////////////////////////////////////////////////////
+    // weighted_feature
+    template<typename Feature>
+    struct as_weighted_feature
+    {
+        typedef Feature type;
+    };
+
+    ///////////////////////////////////////////////////////////////////////////
+    // feature_of
+    template<typename Feature>
+    struct feature_of
+    {
+        typedef Feature type;
+    };
+
+    namespace detail
+    {
+        ///////////////////////////////////////////////////////////////////////////
+        // feature_tag
+        template<typename Accumulator>
+        struct feature_tag
+        {
+            typedef typename Accumulator::feature_tag type;
+        };
+
+        template<typename Feature>
+        struct undroppable
+        {
+            typedef Feature type;
+        };
+
+        template<typename Feature>
+        struct undroppable<tag::droppable<Feature> >
+        {
+            typedef Feature type;
+        };
+
+        // For the purpose of determining whether one feature depends on another,
+        // disregard whether the feature is droppable or not.
+        template<typename A, typename B>
+        struct is_dependent_on
+          : is_base_and_derived<
+                typename feature_of<typename undroppable<B>::type>::type
+              , typename undroppable<A>::type
+            >
+        {};
+
+        template<typename Feature>
+        struct dependencies_of
+        {
+            typedef typename Feature::dependencies type;
+        };
+
+        // Should use mpl::insert_range, but doesn't seem to work with mpl sets
+        template<typename Set, typename Range>
+        struct set_insert_range
+          : mpl::fold<
+                Range
+              , Set
+              , mpl::insert<mpl::_1, mpl::_2>
+            >
+        {};
+
+        template<typename Features>
+        struct collect_abstract_features
+          : mpl::fold<
+                Features
+              , mpl::set0<>
+              , set_insert_range<
+                    mpl::insert<mpl::_1, feature_of<mpl::_2> >
+                  , collect_abstract_features<dependencies_of<mpl::_2> >
+                >
+            >
+        {};
+
+        template<typename Features>
+        struct depends_on_base
+          : mpl::inherit_linearly<
+                typename mpl::sort<
+                    typename mpl::copy<
+                        typename collect_abstract_features<Features>::type
+                      , mpl::back_inserter<mpl::vector0<> >
+                    >::type
+                  , is_dependent_on<mpl::_1, mpl::_2>
+                >::type
+                // Don't inherit multiply from a feature
+              , mpl::if_<
+                    is_dependent_on<mpl::_1, mpl::_2>
+                  , mpl::_1
+                  , mpl::inherit<mpl::_1, mpl::_2>
+                >
+            >::type
+        {
+        };
+    }
+
+    ///////////////////////////////////////////////////////////////////////////
+    /// depends_on
+    template<BOOST_PP_ENUM_PARAMS(BOOST_ACCUMULATORS_MAX_FEATURES, typename Feature)>
+    struct depends_on
+      : detail::depends_on_base<
+            typename mpl::transform<
+                mpl::vector<BOOST_PP_ENUM_PARAMS(BOOST_ACCUMULATORS_MAX_FEATURES, Feature)>
+              , as_feature<mpl::_1>
+            >::type
+        >
+    {
+        typedef mpl::false_ is_weight_accumulator;
+        typedef
+            typename mpl::transform<
+                mpl::vector<BOOST_PP_ENUM_PARAMS(BOOST_ACCUMULATORS_MAX_FEATURES, Feature)>
+              , as_feature<mpl::_1>
+            >::type
+        dependencies;
+    };
+
+    namespace detail
+    {
+        template<typename Feature>
+        struct matches_feature
+        {
+            template<typename Accumulator>
+            struct apply
+              : is_same<
+                    typename feature_of<typename as_feature<Feature>::type>::type
+                  , typename feature_of<typename as_feature<typename feature_tag<Accumulator>::type>::type>::type
+                >
+            {};
+        };
+
+        template<typename Features, typename Accumulator>
+        struct contains_feature_of
+        {
+            typedef
+                mpl::transform_view<Features, feature_of<as_feature<mpl::_> > >
+            features_list;
+
+            typedef
+                typename feature_of<typename feature_tag<Accumulator>::type>::type
+            the_feature;
+
+            typedef
+                typename mpl::contains<features_list, the_feature>::type
+            type;
+        };
+
+        // This is to work around a bug in early versions of Fusion which caused
+        // a compile error if contains_feature_of<List, mpl::_> is used as a
+        // predicate to fusion::find_if
+        template<typename Features>
+        struct contains_feature_of_
+        {
+            template<typename Accumulator>
+            struct apply
+              : contains_feature_of<Features, Accumulator>
+            {};
+        };
+
+        template<
+            typename First
+          , typename Last
+          , bool is_empty = fusion::result_of::equal_to<First, Last>::value
+        >
+        struct build_acc_list;
+
+        template<typename First, typename Last>
+        struct build_acc_list<First, Last, true>
+        {
+            typedef fusion::nil_ type;
+
+            template<typename Args>
+            static fusion::nil_
+            call(Args const &, First const&, Last const&)
+            {
+                return fusion::nil_();
+            }
+        };
+
+        template<typename First, typename Last>
+        struct build_acc_list<First, Last, false>
+        {
+            typedef
+                build_acc_list<typename fusion::result_of::next<First>::type, Last>
+            next_build_acc_list;
+
+            typedef fusion::cons<
+                typename fusion::result_of::value_of<First>::type
+              , typename next_build_acc_list::type>
+            type;
+
+            template<typename Args>
+            static type
+            call(Args const &args, First const& f, Last const& l)
+            {
+                return type(args, next_build_acc_list::call(args, fusion::next(f), l));
+            }
+        };
+
+        namespace meta
+        {
+            template<typename Sequence>
+            struct make_acc_list
+              : build_acc_list<
+                    typename fusion::result_of::begin<Sequence>::type
+                  , typename fusion::result_of::end<Sequence>::type
+                >
+            {};
+        }
+
+        template<typename Sequence, typename Args>
+        typename meta::make_acc_list<Sequence>::type
+        make_acc_list(Sequence &seq, Args const &args)
+        {
+            return meta::make_acc_list<Sequence>::call(args, fusion::begin(seq), fusion::end(seq));
+        }
+
+        template<typename Sequence, typename Args>
+        typename meta::make_acc_list<Sequence>::type
+        make_acc_list(Sequence const &seq, Args const &args)
+        {
+            return meta::make_acc_list<Sequence const>::call(args, fusion::begin(seq), fusion::end(seq));
+        }
+
+        ///////////////////////////////////////////////////////////////////////////
+        // checked_as_weighted_feature
+        template<typename Feature>
+        struct checked_as_weighted_feature
+        {
+            typedef typename as_feature<Feature>::type feature_type;
+            typedef typename as_weighted_feature<feature_type>::type type;
+            // weighted and non-weighted flavors should provide the same feature.
+            BOOST_MPL_ASSERT((
+                is_same<
+                    typename feature_of<feature_type>::type
+                  , typename feature_of<type>::type
+                >
+            ));
+        };
+
+        ///////////////////////////////////////////////////////////////////////////
+        // as_feature_list
+        template<typename Features, typename Weight>
+        struct as_feature_list
+          : mpl::transform_view<Features, checked_as_weighted_feature<mpl::_1> >
+        {
+        };
+
+        template<typename Features>
+        struct as_feature_list<Features, void>
+          : mpl::transform_view<Features, as_feature<mpl::_1> >
+        {
+        };
+
+        ///////////////////////////////////////////////////////////////////////////
+        // accumulator_wrapper
+        template<typename Accumulator, typename Feature>
+        struct accumulator_wrapper
+          : Accumulator
+        {
+            typedef Feature feature_tag;
+
+            accumulator_wrapper(accumulator_wrapper const &that)
+              : Accumulator(*static_cast<Accumulator const *>(&that))
+            {
+            }
+
+            accumulator_wrapper& operator=(accumulator_wrapper const &that)
+            {
+                *static_cast<Accumulator *>(this) = *static_cast<Accumulator const *>(&that);
+                return *this;
+            }
+
+            template<typename Args>
+            accumulator_wrapper(Args const &args)
+              : Accumulator(args)
+            {
+            }
+        };
+
+        ///////////////////////////////////////////////////////////////////////////
+        // to_accumulator
+        template<typename Feature, typename Sample, typename Weight>
+        struct to_accumulator
+        {
+            typedef
+                accumulator_wrapper<
+                    typename mpl::apply2<typename Feature::impl, Sample, Weight>::type
+                  , Feature
+                >
+            type;
+        };
+
+        template<typename Feature, typename Sample, typename Weight, typename Tag, typename AccumulatorSet>
+        struct to_accumulator<Feature, Sample, tag::external<Weight, Tag, AccumulatorSet> >
+        {
+            BOOST_MPL_ASSERT((is_same<Tag, void>));
+            BOOST_MPL_ASSERT((is_same<AccumulatorSet, void>));
+
+            typedef
+                accumulator_wrapper<
+                    typename mpl::apply2<typename Feature::impl, Sample, Weight>::type
+                  , Feature
+                >
+            accumulator_type;
+
+            typedef
+                typename mpl::if_<
+                    typename Feature::is_weight_accumulator
+                  , accumulator_wrapper<impl::external_impl<accumulator_type, tag::weights>, Feature>
+                  , accumulator_type
+                >::type
+            type;
+        };
+
+        // BUGBUG work around an MPL bug wrt map insertion
+        template<typename FeatureMap, typename Feature>
+        struct insert_feature
+          : mpl::eval_if<
+                mpl::has_key<FeatureMap, typename feature_of<Feature>::type>
+              , mpl::identity<FeatureMap>
+              , mpl::insert<FeatureMap, mpl::pair<typename feature_of<Feature>::type, Feature> >
+            >
+        {
+        };
+
+        template<typename FeatureMap, typename Feature, typename Weight>
+        struct insert_dependencies
+          : mpl::fold<
+                as_feature_list<typename Feature::dependencies, Weight>
+              , FeatureMap
+              , insert_dependencies<
+                    insert_feature<mpl::_1, mpl::_2>
+                  , mpl::_2
+                  , Weight
+                >
+            >
+        {
+        };
+
+        template<typename FeatureMap, typename Features, typename Weight>
+        struct insert_sequence
+          : mpl::fold< // BUGBUG should use insert_range, but doesn't seem to work for maps
+                as_feature_list<Features, Weight>
+              , FeatureMap
+              , insert_feature<mpl::_1, mpl::_2>
+            >
+        {
+        };
+
+        template<typename Features, typename Sample, typename Weight>
+        struct make_accumulator_tuple
+        {
+            typedef
+                typename mpl::fold<
+                    as_feature_list<Features, Weight>
+                  , mpl::map0<>
+                  , mpl::if_<
+                        mpl::is_sequence<mpl::_2>
+                      , insert_sequence<mpl::_1, mpl::_2, Weight>
+                      , insert_feature<mpl::_1, mpl::_2>
+                    >
+                >::type
+            feature_map;
+
+            // for each element in the map, add its dependencies also
+            typedef
+                typename mpl::fold<
+                    feature_map
+                  , feature_map
+                  , insert_dependencies<mpl::_1, mpl::second<mpl::_2>, Weight>
+                >::type
+            feature_map_with_dependencies;
+
+            // turn the map into a vector so we can sort it
+            typedef
+                typename mpl::insert_range<
+                    mpl::vector<>
+                  , mpl::end<mpl::vector<> >::type
+                  , mpl::transform_view<feature_map_with_dependencies, mpl::second<mpl::_1> >
+                >::type
+            feature_vector_with_dependencies;
+
+            // sort the features according to which is derived from which
+            typedef
+                typename mpl::sort<
+                    feature_vector_with_dependencies
+                  , is_dependent_on<mpl::_2, mpl::_1>
+                >::type
+            sorted_feature_vector;
+
+            // From the vector of features, construct a vector of accumulators
+            typedef
+                typename mpl::transform<
+                    sorted_feature_vector
+                  , to_accumulator<mpl::_1, Sample, Weight>
+                >::type
+            type;
+        };
+
+    } // namespace detail
+
+}} // namespace boost::accumulators
+
+#endif

+ 27 - 0
library/include/boost/accumulators/framework/external.hpp

@@ -0,0 +1,27 @@
+///////////////////////////////////////////////////////////////////////////////
+// external.hpp
+//
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_FRAMEWORK_EXTERNAL_HPP_EAN_01_12_2005
+#define BOOST_ACCUMULATORS_FRAMEWORK_EXTERNAL_HPP_EAN_01_12_2005
+
+#include <boost/mpl/apply.hpp>
+#include <boost/accumulators/framework/accumulators/external_accumulator.hpp>
+
+//namespace boost { namespace accumulators
+//{
+//
+/////////////////////////////////////////////////////////////////////////////////
+//// external
+////
+//template<typename Type>
+//struct external
+//{
+//};
+//
+//}} // namespace boost::accumulators
+
+#endif

+ 248 - 0
library/include/boost/accumulators/framework/extractor.hpp

@@ -0,0 +1,248 @@
+///////////////////////////////////////////////////////////////////////////////
+// extractor.hpp
+//
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_FRAMEWORK_EXTRACTOR_HPP_EAN_28_10_2005
+#define BOOST_ACCUMULATORS_FRAMEWORK_EXTRACTOR_HPP_EAN_28_10_2005
+
+#include <boost/preprocessor/cat.hpp>
+#include <boost/preprocessor/tuple/rem.hpp>
+#include <boost/preprocessor/array/size.hpp>
+#include <boost/preprocessor/array/data.hpp>
+#include <boost/preprocessor/array/elem.hpp>
+#include <boost/preprocessor/seq/to_array.hpp>
+#include <boost/preprocessor/seq/transform.hpp>
+#include <boost/preprocessor/repetition/enum_params.hpp>
+#include <boost/preprocessor/repetition/enum_trailing.hpp>
+#include <boost/preprocessor/repetition/enum_trailing_params.hpp>
+#include <boost/preprocessor/repetition/enum_trailing_binary_params.hpp>
+#include <boost/preprocessor/repetition/repeat.hpp>
+#include <boost/preprocessor/repetition/repeat_from_to.hpp>
+#include <boost/parameter/binding.hpp>
+#include <boost/mpl/bool.hpp>
+#include <boost/mpl/if.hpp>
+#include <boost/mpl/eval_if.hpp>
+#include <boost/mpl/apply.hpp>
+#include <boost/type_traits/remove_const.hpp>
+#include <boost/type_traits/remove_reference.hpp>
+#include <boost/accumulators/accumulators_fwd.hpp>
+#include <boost/accumulators/framework/parameters/accumulator.hpp>
+
+namespace boost { namespace accumulators
+{
+
+namespace detail
+{
+    template<typename AccumulatorSet, typename Feature>
+    struct accumulator_set_result
+    {
+        typedef typename as_feature<Feature>::type feature_type;
+        typedef typename mpl::apply<
+            typename boost::remove_const<
+                typename boost::remove_reference<AccumulatorSet>::type
+            >::type
+          , feature_type
+        >::type::result_type type;
+    };
+
+    template<typename Args, typename Feature>
+    struct argument_pack_result
+      : accumulator_set_result<
+            typename boost::remove_reference<
+                typename parameter::binding<
+                    typename boost::remove_const<
+                        typename boost::remove_reference<Args>::type
+                    >::type
+                  , tag::accumulator
+                >::type
+            >::type
+          , Feature
+        >
+    {
+    };
+
+    template<typename A, typename Feature>
+    struct extractor_result
+      : mpl::eval_if<
+            detail::is_accumulator_set<A>
+          , accumulator_set_result<A, Feature>
+          , argument_pack_result<A, Feature>
+        >
+    {
+    };
+
+    template<typename Feature, typename AccumulatorSet>
+    typename extractor_result<AccumulatorSet, Feature>::type
+    do_extract(AccumulatorSet const &acc, mpl::true_)
+    {
+        typedef typename as_feature<Feature>::type feature_type;
+        return extract_result<feature_type>(acc);
+    }
+
+    template<typename Feature, typename Args>
+    typename extractor_result<Args, Feature>::type
+    do_extract(Args const &args, mpl::false_)
+    {
+        typedef typename as_feature<Feature>::type feature_type;
+        return find_accumulator<feature_type>(args[accumulator]).result(args);
+    }
+
+} // namespace detail
+
+
+///////////////////////////////////////////////////////////////////////////////
+/// Extracts the result associated with Feature from the specified accumulator_set.
+template<typename Feature>
+struct extractor
+{
+    typedef extractor<Feature> this_type;
+
+    /// The result meta-function for determining the return type of the extractor
+    template<typename F>
+    struct result;
+
+    template<typename A1>
+    struct result<this_type(A1)>
+      : detail::extractor_result<A1, Feature>
+    {
+    };
+
+    /// Extract the result associated with Feature from the accumulator set
+    /// \param acc The accumulator set object from which to extract the result
+    template<typename Arg1>
+    typename detail::extractor_result<Arg1, Feature>::type
+    operator ()(Arg1 const &arg1) const
+    {
+        // Arg1 could be an accumulator_set or an argument pack containing
+        // an accumulator_set. Dispatch accordingly.
+        return detail::do_extract<Feature>(arg1, detail::is_accumulator_set<Arg1>());
+    }
+
+    /// \overload
+    ///
+    /// \param a1 Optional named parameter to be passed to the accumulator's result() function.
+    template<typename AccumulatorSet, typename A1>
+    typename detail::extractor_result<AccumulatorSet, Feature>::type
+    operator ()(AccumulatorSet const &acc, A1 const &a1) const
+    {
+        BOOST_MPL_ASSERT((detail::is_accumulator_set<AccumulatorSet>));
+        typedef typename as_feature<Feature>::type feature_type;
+        return extract_result<feature_type>(acc, a1);
+    }
+
+    // ... other overloads generated by Boost.Preprocessor:
+
+    /// INTERNAL ONLY
+    ///
+#define BOOST_ACCUMULATORS_EXTRACTOR_FUN_OP(z, n, _)                                    \
+    template<BOOST_PP_ENUM_PARAMS_Z(z, n, typename A)>                                  \
+    struct result<this_type(BOOST_PP_ENUM_PARAMS_Z(z, n, A))>                           \
+      : detail::extractor_result<A1, Feature>                                           \
+    {};                                                                                 \
+    template<                                                                           \
+        typename AccumulatorSet                                                         \
+        BOOST_PP_ENUM_TRAILING_PARAMS_Z(z, n, typename A)                               \
+    >                                                                                   \
+    typename detail::extractor_result<AccumulatorSet, Feature>::type                    \
+    operator ()(                                                                        \
+        AccumulatorSet const &acc                                                       \
+        BOOST_PP_ENUM_TRAILING_BINARY_PARAMS_Z(z, n, A, const &a)                       \
+    ) const                                                                             \
+    {                                                                                   \
+        BOOST_MPL_ASSERT((detail::is_accumulator_set<AccumulatorSet>));                 \
+        typedef typename as_feature<Feature>::type feature_type;                        \
+        return extract_result<feature_type>(acc BOOST_PP_ENUM_TRAILING_PARAMS_Z(z, n, a));\
+    }
+
+    BOOST_PP_REPEAT_FROM_TO(
+        2
+      , BOOST_PP_INC(BOOST_ACCUMULATORS_MAX_ARGS)
+      , BOOST_ACCUMULATORS_EXTRACTOR_FUN_OP
+      , _
+    )
+
+#undef BOOST_ACCUMULATORS_EXTRACTOR_FUN_OP
+
+    #ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED
+    /// \overload
+    ///
+    template<typename AccumulatorSet, typename A1, typename A2, ...>
+    typename detail::extractor_result<AccumulatorSet, Feature>::type
+    operator ()(AccumulatorSet const &acc, A1 const &a1, A2 const &a2, ...);
+    #endif
+};
+
+}} // namespace boost::accumulators
+
+/// INTERNAL ONLY
+///
+#define BOOST_ACCUMULATORS_ARRAY_REM(Array)                                                         \
+    BOOST_PP_TUPLE_REM_CTOR(BOOST_PP_ARRAY_SIZE(Array), BOOST_PP_ARRAY_DATA(Array))
+
+/// INTERNAL ONLY
+///
+#define BOOST_ACCUMULATORS_SEQ_REM(Seq)                                                             \
+    BOOST_ACCUMULATORS_ARRAY_REM(BOOST_PP_SEQ_TO_ARRAY(Seq))
+
+/// INTERNAL ONLY
+///
+#define BOOST_ACCUMULATORS_ARGS_OP(s, data, elem)                                                   \
+    T ## s
+
+/// INTERNAL ONLY
+///
+#define BOOST_ACCUMULATORS_PARAMS_OP(s, data, elem)                                                 \
+    elem T ## s
+
+/// INTERNAL ONLY
+///
+#define BOOST_ACCUMULATORS_MAKE_FEATURE(Tag, Feature, ParamsSeq)                                    \
+    Tag::Feature<                                                                                   \
+        BOOST_ACCUMULATORS_SEQ_REM(                                                                 \
+            BOOST_PP_SEQ_TRANSFORM(BOOST_ACCUMULATORS_ARGS_OP, ~, ParamsSeq)                        \
+        )                                                                                           \
+    >
+
+/// INTERNAL ONLY
+///
+#define BOOST_ACCUMULATORS_DEFINE_EXTRACTOR_FUN_IMPL(z, n, Tag, Feature, ParamsSeq)                 \
+    template<                                                                                       \
+        BOOST_ACCUMULATORS_SEQ_REM(                                                                 \
+            BOOST_PP_SEQ_TRANSFORM(BOOST_ACCUMULATORS_PARAMS_OP, ~, ParamsSeq)                      \
+        )                                                                                           \
+      , typename Arg1                                                                               \
+        BOOST_PP_ENUM_TRAILING_PARAMS_Z(z, n, typename A)                                           \
+    >                                                                                               \
+    typename boost::accumulators::detail::extractor_result<                                         \
+        Arg1                                                                                        \
+      , BOOST_ACCUMULATORS_MAKE_FEATURE(Tag, Feature, ParamsSeq)                                    \
+    >::type                                                                                         \
+    Feature(Arg1 const &arg1 BOOST_PP_ENUM_TRAILING_BINARY_PARAMS_Z(z, n, A, const &a) )            \
+    {                                                                                               \
+        typedef BOOST_ACCUMULATORS_MAKE_FEATURE(Tag, Feature, ParamsSeq) feature_type;              \
+        return boost::accumulators::extractor<feature_type>()(                                      \
+            arg1 BOOST_PP_ENUM_TRAILING_PARAMS_Z(z, n, a));                                         \
+    }
+
+/// INTERNAL ONLY
+///
+#define BOOST_ACCUMULATORS_DEFINE_EXTRACTOR_FUN(z, n, _)                                            \
+    BOOST_ACCUMULATORS_DEFINE_EXTRACTOR_FUN_IMPL(                                                   \
+        z                                                                                           \
+      , n                                                                                           \
+      , BOOST_PP_ARRAY_ELEM(0, _)                                                                   \
+      , BOOST_PP_ARRAY_ELEM(1, _)                                                                   \
+      , BOOST_PP_ARRAY_ELEM(2, _)                                                                   \
+    )
+
+#define BOOST_ACCUMULATORS_DEFINE_EXTRACTOR(Tag, Feature, ParamSeq)                                 \
+    BOOST_PP_REPEAT(                                                                                \
+        BOOST_PP_INC(BOOST_ACCUMULATORS_MAX_ARGS)                                                   \
+      , BOOST_ACCUMULATORS_DEFINE_EXTRACTOR_FUN                                                     \
+      , (3, (Tag, Feature, ParamSeq))                                                               \
+    )
+
+#endif

+ 29 - 0
library/include/boost/accumulators/framework/features.hpp

@@ -0,0 +1,29 @@
+///////////////////////////////////////////////////////////////////////////////
+// features.hpp
+//
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_STATS_HPP_EAN_08_12_2005
+#define BOOST_ACCUMULATORS_STATISTICS_STATS_HPP_EAN_08_12_2005
+
+#include <boost/preprocessor/repetition/enum_params.hpp>
+#include <boost/mpl/vector.hpp>
+#include <boost/accumulators/accumulators_fwd.hpp>
+
+namespace boost { namespace accumulators
+{
+
+///////////////////////////////////////////////////////////////////////////////
+// features
+//
+template<BOOST_PP_ENUM_PARAMS(BOOST_ACCUMULATORS_MAX_FEATURES, typename Feature)>
+struct features
+  : mpl::vector<BOOST_PP_ENUM_PARAMS(BOOST_ACCUMULATORS_MAX_FEATURES, Feature)>
+{
+};
+
+}} // namespace boost::accumulators
+
+#endif

+ 22 - 0
library/include/boost/accumulators/framework/parameters/accumulator.hpp

@@ -0,0 +1,22 @@
+///////////////////////////////////////////////////////////////////////////////
+// accumulator.hpp
+//
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_FRAMEWORK_PARAMETERS_ACCUMULATOR_HPP_EAN_31_10_2005
+#define BOOST_ACCUMULATORS_FRAMEWORK_PARAMETERS_ACCUMULATOR_HPP_EAN_31_10_2005
+
+#include <boost/parameter/name.hpp>
+#include <boost/accumulators/accumulators_fwd.hpp>
+
+namespace boost { namespace accumulators
+{
+
+BOOST_PARAMETER_NAME((accumulator, tag) accumulator)
+BOOST_ACCUMULATORS_IGNORE_GLOBAL(accumulator)
+
+}} // namespace boost::accumulators
+
+#endif

+ 22 - 0
library/include/boost/accumulators/framework/parameters/sample.hpp

@@ -0,0 +1,22 @@
+///////////////////////////////////////////////////////////////////////////////
+// sample.hpp
+//
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_FRAMEWORK_PARAMETERS_SAMPLE_HPP_EAN_31_10_2005
+#define BOOST_ACCUMULATORS_FRAMEWORK_PARAMETERS_SAMPLE_HPP_EAN_31_10_2005
+
+#include <boost/parameter/name.hpp>
+#include <boost/accumulators/accumulators_fwd.hpp>
+
+namespace boost { namespace accumulators
+{
+
+BOOST_PARAMETER_NAME((sample, tag) sample)
+BOOST_ACCUMULATORS_IGNORE_GLOBAL(sample)
+
+}} // namespace boost::accumulators
+
+#endif

+ 23 - 0
library/include/boost/accumulators/framework/parameters/weight.hpp

@@ -0,0 +1,23 @@
+///////////////////////////////////////////////////////////////////////////////
+// weight.hpp
+//
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_FRAMEWORK_PARAMETERS_WEIGHT_HPP_EAN_31_10_2005
+#define BOOST_ACCUMULATORS_FRAMEWORK_PARAMETERS_WEIGHT_HPP_EAN_31_10_2005
+
+#include <boost/parameter/name.hpp>
+#include <boost/accumulators/accumulators_fwd.hpp>
+
+namespace boost { namespace accumulators
+{
+
+// The weight of a single sample
+BOOST_PARAMETER_NAME((weight, tag) weight)
+BOOST_ACCUMULATORS_IGNORE_GLOBAL(weight)
+
+}} // namespace boost::accumulators
+
+#endif

+ 23 - 0
library/include/boost/accumulators/framework/parameters/weights.hpp

@@ -0,0 +1,23 @@
+///////////////////////////////////////////////////////////////////////////////
+// weights.hpp
+//
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_FRAMEWORK_PARAMETERS_WEIGHTS_HPP_EAN_28_10_2005
+#define BOOST_ACCUMULATORS_FRAMEWORK_PARAMETERS_WEIGHTS_HPP_EAN_28_10_2005
+
+#include <boost/parameter/name.hpp>
+#include <boost/accumulators/accumulators_fwd.hpp>
+
+namespace boost { namespace accumulators
+{
+
+// The weight accumulator
+BOOST_PARAMETER_NAME((weights, tag) weights)
+BOOST_ACCUMULATORS_IGNORE_GLOBAL(weights)
+
+}} // namespace boost::accumulators
+
+#endif

+ 75 - 0
library/include/boost/accumulators/numeric/detail/function1.hpp

@@ -0,0 +1,75 @@
+// Copyright David Abrahams 2006. Distributed under the Boost
+// Software License, Version 1.0. (See accompanying
+// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+#ifndef BOOST_DETAIL_FUNCTION1_DWA200655_HPP
+# define BOOST_DETAIL_FUNCTION1_DWA200655_HPP
+
+# include <boost/concept_check.hpp>
+# include <boost/type_traits/remove_reference.hpp>
+# include <boost/type_traits/add_const.hpp>
+# include <boost/mpl/apply.hpp>
+
+namespace boost { namespace detail {
+
+// A utility for creating unary function objects that play nicely with
+// boost::result_of and that handle the forwarding problem.
+//
+// mpl::apply<F, A0>::type is expected to be a stateless function
+// object that accepts an argument of type A0&.  It is also expected
+// to have a nested ::result_type identical to its return type.
+template<typename F>
+struct function1
+{
+    template<typename Signature>
+    struct result
+    {};
+
+    template<typename This, typename A0>
+    struct result<This(A0)>
+    {
+        // How adding const to arguments handles rvalues.
+        //
+        // if A0 is     arg0 is       represents actual argument
+        // --------     -------       --------------------------
+        // T const &    T const       const T lvalue
+        // T &          T             non-const T lvalue
+        // T const      T const       const T rvalue
+        // T            T const       non-const T rvalue
+        typedef typename remove_reference<
+            typename add_const< A0 >::type
+        >::type arg0;
+
+        typedef typename mpl::apply1<F, arg0>::type impl;
+        typedef typename impl::result_type type;
+    };
+
+    // Handles mutable lvalues
+    template<typename A0>
+    typename result<function1(A0 &)>::type
+    operator ()(A0 &a0) const
+    {
+        typedef typename result<function1(A0 &)>::impl impl;
+        typedef typename result<function1(A0 &)>::type type;
+        typedef A0 &arg0;
+        BOOST_CONCEPT_ASSERT((UnaryFunction<impl, type, arg0>));
+        //boost::function_requires<UnaryFunctionConcept<impl, type, arg0> >();
+        return impl()(a0);
+    }
+
+    // Handles const lvalues and all rvalues
+    template<typename A0>
+    typename result<function1(A0 const &)>::type
+    operator ()(A0 const &a0) const
+    {
+        typedef typename result<function1(A0 const &)>::impl impl;
+        typedef typename result<function1(A0 const &)>::type type;
+        typedef A0 const &arg0;
+        BOOST_CONCEPT_ASSERT((UnaryFunction<impl, type, arg0>));
+        //boost::function_requires<UnaryFunctionConcept<impl, type, arg0> >();
+        return impl()(a0);
+    }
+};
+
+}} // namespace boost::detail
+
+#endif // BOOST_DETAIL_FUNCTION1_DWA200655_HPP

+ 10 - 0
library/include/boost/accumulators/numeric/detail/function2.hpp

@@ -0,0 +1,10 @@
+// Copyright David Abrahams 2006. Distributed under the Boost
+// Software License, Version 1.0. (See accompanying
+// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+#ifndef BOOST_DETAIL_FUNCTION2_DWA200655_HPP
+# define BOOST_DETAIL_FUNCTION2_DWA200655_HPP
+
+# define args (2)
+# include <boost/accumulators/numeric/detail/function_n.hpp>
+
+#endif // BOOST_DETAIL_FUNCTION2_DWA200655_HPP

+ 10 - 0
library/include/boost/accumulators/numeric/detail/function3.hpp

@@ -0,0 +1,10 @@
+// Copyright David Abrahams 2006. Distributed under the Boost
+// Software License, Version 1.0. (See accompanying
+// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+#ifndef BOOST_DETAIL_FUNCTION3_DWA2006514_HPP
+# define BOOST_DETAIL_FUNCTION3_DWA2006514_HPP
+
+# define args (3)
+# include <boost/accumulators/numeric/detail/function_n.hpp>
+
+#endif // BOOST_DETAIL_FUNCTION3_DWA2006514_HPP

+ 10 - 0
library/include/boost/accumulators/numeric/detail/function4.hpp

@@ -0,0 +1,10 @@
+// Copyright David Abrahams 2006. Distributed under the Boost
+// Software License, Version 1.0. (See accompanying
+// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+#ifndef BOOST_DETAIL_FUNCTION4_DWA2006514_HPP
+# define BOOST_DETAIL_FUNCTION4_DWA2006514_HPP
+
+# define args (4)
+# include <boost/accumulators/numeric/detail/function_n.hpp>
+
+#endif // BOOST_DETAIL_FUNCTION4_DWA2006514_HPP

+ 148 - 0
library/include/boost/accumulators/numeric/detail/function_n.hpp

@@ -0,0 +1,148 @@
+// Copyright David Abrahams 2006. Distributed under the Boost
+// Software License, Version 1.0. (See accompanying
+// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+//
+// #include guards intentionally disabled.
+// #ifndef BOOST_DETAIL_FUNCTION_N_DWA2006514_HPP
+// # define BOOST_DETAIL_FUNCTION_N_DWA2006514_HPP
+
+#include <boost/mpl/void.hpp>
+#include <boost/mpl/apply.hpp>
+
+#include <boost/preprocessor/control/if.hpp>
+#include <boost/preprocessor/cat.hpp>
+#include <boost/preprocessor/punctuation/comma_if.hpp>
+#include <boost/preprocessor/repetition/enum_params.hpp>
+#include <boost/preprocessor/repetition/enum_trailing_params.hpp>
+#include <boost/preprocessor/repetition/repeat.hpp>
+#include <boost/preprocessor/seq/fold_left.hpp>
+#include <boost/preprocessor/seq/seq.hpp>
+#include <boost/preprocessor/seq/for_each.hpp>
+#include <boost/preprocessor/seq/for_each_i.hpp>
+#include <boost/preprocessor/seq/for_each_product.hpp>
+#include <boost/preprocessor/seq/size.hpp>
+#include <boost/type_traits/add_const.hpp>
+#include <boost/type_traits/remove_reference.hpp>
+
+namespace boost { namespace detail {
+
+# define BOOST_DETAIL_default_arg(z, n, _)                                      \
+    typedef mpl::void_ BOOST_PP_CAT(arg, n);
+
+# define BOOST_DETAIL_function_arg(z, n, _)                                     \
+    typedef typename remove_reference<                                          \
+        typename add_const< BOOST_PP_CAT(A, n) >::type                          \
+    >::type BOOST_PP_CAT(arg, n);
+
+#define BOOST_DETAIL_cat_arg_counts(s, state, n)                                \
+    BOOST_PP_IF(                                                                \
+        n                                                                       \
+      , BOOST_PP_CAT(state, BOOST_PP_CAT(_, n))                                 \
+      , state                                                                   \
+    )                                                                           \
+    /**/
+
+#define function_name                                                           \
+    BOOST_PP_SEQ_FOLD_LEFT(                                                     \
+        BOOST_DETAIL_cat_arg_counts                                             \
+      , BOOST_PP_CAT(function, BOOST_PP_SEQ_HEAD(args))                         \
+      , BOOST_PP_SEQ_TAIL(args)(0)                                              \
+    )                                                                           \
+    /**/
+
+template<typename F>
+struct function_name
+{
+    BOOST_PP_REPEAT(
+        BOOST_MPL_LIMIT_METAFUNCTION_ARITY
+      , BOOST_DETAIL_default_arg
+      , ~
+    )
+
+    template<typename Signature>
+    struct result {};
+
+#define BOOST_DETAIL_function_result(r, _, n)                                   \
+    template<typename This BOOST_PP_ENUM_TRAILING_PARAMS(n, typename A)>        \
+    struct result<This(BOOST_PP_ENUM_PARAMS(n, A))>                             \
+    {                                                                           \
+        BOOST_PP_REPEAT(n, BOOST_DETAIL_function_arg, ~)                        \
+        typedef                                                                 \
+            typename BOOST_PP_CAT(mpl::apply, BOOST_MPL_LIMIT_METAFUNCTION_ARITY)<\
+                F                                                               \
+                BOOST_PP_ENUM_TRAILING_PARAMS(                                  \
+                    BOOST_MPL_LIMIT_METAFUNCTION_ARITY                          \
+                  , arg                                                         \
+                )                                                               \
+            >::type                                                             \
+        impl;                                                                   \
+        typedef typename impl::result_type type;                                \
+    };                                                                          \
+    /**/
+
+    BOOST_PP_SEQ_FOR_EACH(BOOST_DETAIL_function_result, _, args)
+
+# define arg_type(r, _, i, is_const)                                            \
+    BOOST_PP_COMMA_IF(i) BOOST_PP_CAT(A, i) BOOST_PP_CAT(const_if, is_const) &
+
+# define result_(r, n, constness)                                               \
+    typename result<                                                            \
+        function_name(                                                          \
+            BOOST_PP_SEQ_FOR_EACH_I_R(r, arg_type, ~, constness)                \
+        )                                                                       \
+    >                                                                           \
+    /**/
+
+# define param(r, _, i, is_const) BOOST_PP_COMMA_IF(i)                          \
+    BOOST_PP_CAT(A, i) BOOST_PP_CAT(const_if, is_const) & BOOST_PP_CAT(x, i)
+
+# define param_list(r, n, constness)                                            \
+    BOOST_PP_SEQ_FOR_EACH_I_R(r, param, ~, constness)
+
+# define call_operator(r, constness)                                            \
+    template<BOOST_PP_ENUM_PARAMS(BOOST_PP_SEQ_SIZE(constness), typename A)>    \
+        result_(r, BOOST_PP_SEQ_SIZE(constness), constness)::type               \
+    operator ()( param_list(r, BOOST_PP_SEQ_SIZE(constness), constness) ) const \
+    {                                                                           \
+        typedef result_(r, BOOST_PP_SEQ_SIZE(constness), constness)::impl impl; \
+        return impl()(BOOST_PP_ENUM_PARAMS(BOOST_PP_SEQ_SIZE(constness), x));   \
+    }                                                                           \
+    /**/
+
+# define const_if0
+# define const_if1 const
+
+# define bits(z, n, _) ((0)(1))
+
+# define gen_operator(r, _, n)                                                  \
+    BOOST_PP_SEQ_FOR_EACH_PRODUCT_R(                                            \
+        r                                                                       \
+      , call_operator                                                           \
+      , BOOST_PP_REPEAT(n, bits, ~)                                             \
+    )                                                                           \
+    /**/
+
+    BOOST_PP_SEQ_FOR_EACH(
+        gen_operator
+      , ~
+      , args
+    )
+
+# undef bits
+# undef const_if1
+# undef const_if0
+# undef call_operator
+# undef param_list
+# undef param
+# undef result_
+# undef default_
+# undef arg_type
+# undef gen_operator
+# undef function_name
+
+# undef args
+};
+
+}} // namespace boost::detail
+
+//#endif // BOOST_DETAIL_FUNCTION_N_DWA2006514_HPP

+ 20 - 0
library/include/boost/accumulators/numeric/detail/pod_singleton.hpp

@@ -0,0 +1,20 @@
+// Copyright David Abrahams 2006. Distributed under the Boost
+// Software License, Version 1.0. (See accompanying
+// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+#ifndef BOOST_DETAIL_POD_SINGLETON_DWA200655_HPP
+# define BOOST_DETAIL_POD_SINGLETON_DWA200655_HPP
+
+namespace boost { namespace detail {
+
+template<typename T>
+struct pod_singleton
+{
+    static T instance;
+};
+
+template<typename T>
+T pod_singleton<T>::instance;
+
+}} // namespace boost::detail
+
+#endif // BOOST_DETAIL_POD_SINGLETON_DWA200655_HPP

+ 537 - 0
library/include/boost/accumulators/numeric/functional.hpp

@@ -0,0 +1,537 @@
+///////////////////////////////////////////////////////////////////////////////
+/// \file functional.hpp
+///
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_NUMERIC_FUNCTIONAL_HPP_EAN_08_12_2005
+#define BOOST_NUMERIC_FUNCTIONAL_HPP_EAN_08_12_2005
+
+#include <limits>
+#include <functional>
+#include <boost/static_assert.hpp>
+#include <boost/mpl/if.hpp>
+#include <boost/mpl/and.hpp>
+#include <boost/type_traits/remove_const.hpp>
+#include <boost/type_traits/add_reference.hpp>
+#include <boost/type_traits/is_empty.hpp>
+#include <boost/type_traits/is_integral.hpp>
+#include <boost/type_traits/is_floating_point.hpp>
+#include <boost/utility/enable_if.hpp>
+#include <boost/typeof/typeof.hpp>
+#include <boost/accumulators/accumulators_fwd.hpp>
+#include <boost/accumulators/numeric/functional_fwd.hpp>
+#include <boost/accumulators/numeric/detail/function1.hpp>
+#include <boost/accumulators/numeric/detail/function2.hpp>
+#include <boost/accumulators/numeric/detail/pod_singleton.hpp>
+
+#ifdef BOOST_NUMERIC_FUNCTIONAL_STD_VECTOR_SUPPORT
+# include <boost/accumulators/numeric/functional/vector.hpp>
+#endif
+
+#ifdef BOOST_NUMERIC_FUNCTIONAL_STD_VALARRAY_SUPPORT
+# include <boost/accumulators/numeric/functional/valarray.hpp>
+#endif
+
+#ifdef BOOST_NUMERIC_FUNCTIONAL_STD_COMPLEX_SUPPORT
+# include <boost/accumulators/numeric/functional/complex.hpp>
+#endif
+
+/// INTERNAL ONLY
+///
+#define BOOST_NUMERIC_FUNCTIONAL_HPP_INCLUDED
+
+#ifdef BOOST_NUMERIC_FUNCTIONAL_DOXYGEN_INVOKED
+// Hack to make Doxygen show the inheritance relationships
+/// INTERNAL ONLY
+///
+namespace std
+{
+    /// INTERNAL ONLY
+    ///
+    template<class Arg, class Ret> struct unary_function {};
+    /// INTERNAL ONLY
+    ///
+    template<class Left, class Right, class Ret> struct binary_function {};
+}
+#endif
+
+namespace boost { namespace numeric
+{
+    namespace functional
+    {
+        /// INTERNAL ONLY
+        ///
+        template<typename A0, typename A1>
+        struct are_integral
+          : mpl::and_<is_integral<A0>, is_integral<A1> >
+        {};
+
+        template<typename Left, typename Right>
+        struct left_ref
+        {
+            typedef Left &type;
+        };
+
+        namespace detail
+        {
+            template<typename T>
+            T &lvalue_of();
+        }
+    }
+
+    // TODO: handle complex weight, valarray, MTL vectors
+
+    /// INTERNAL ONLY
+    ///
+#define BOOST_NUMERIC_FUNCTIONAL_DEFINE_UNARY_OP(Name, Op)                                      \
+    namespace functional                                                                        \
+    {                                                                                           \
+        template<typename Arg>                                                                  \
+        struct result_of_ ## Name                                                               \
+        {                                                                                       \
+            BOOST_TYPEOF_NESTED_TYPEDEF_TPL(                                                    \
+                nested                                                                          \
+              , Op boost::numeric::functional::detail::lvalue_of<Arg>()                         \
+            )                                                                                   \
+            typedef typename nested::type type;                                                 \
+        };                                                                                      \
+        template<typename Arg, typename EnableIf>                                               \
+        struct Name ## _base                                                                    \
+        {                                                                                       \
+            typedef typename remove_const<Arg>::type argument_type;                             \
+            typedef typename result_of_ ## Name<Arg>::type result_type;                         \
+            typename result_of_ ## Name<Arg>::type operator ()(Arg &arg) const                  \
+            {                                                                                   \
+                return Op arg;                                                                  \
+            }                                                                                   \
+        };                                                                                      \
+        template<typename Arg, typename ArgTag>                                                 \
+        struct Name                                                                             \
+          : Name ## _base<Arg, void>                                                            \
+        {};                                                                                     \
+    }                                                                                           \
+    namespace op                                                                                \
+    {                                                                                           \
+        struct Name                                                                             \
+          : boost::detail::function1<functional::Name<_, functional::tag<_> > >                 \
+        {};                                                                                     \
+    }                                                                                           \
+    namespace                                                                                   \
+    {                                                                                           \
+        op::Name const &Name = boost::detail::pod_singleton<op::Name>::instance;                \
+    }                                                                                           \
+    /**/
+
+    /// INTERNAL ONLY
+    ///
+#define BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(Name, Op, RetType)                            \
+    namespace functional                                                                        \
+    {                                                                                           \
+        template<typename Left, typename Right, typename EnableIf>                              \
+        struct result_of_ ## Name                                                               \
+        {                                                                                       \
+            RetType(Left, Op, Right)                                                            \
+        };                                                                                      \
+        template<typename Left, typename Right, typename EnableIf>                              \
+        struct Name ## _base                                                                    \
+        {                                                                                       \
+            typedef typename remove_const<Left>::type first_argument_type;                      \
+            typedef typename remove_const<Right>::type second_argument_type;                    \
+            typedef typename result_of_ ## Name<Left, Right>::type result_type;                 \
+            typename result_of_ ## Name<Left, Right>::type                                      \
+            operator ()(Left &left, Right &right) const                                         \
+            {                                                                                   \
+                return left Op right;                                                           \
+            }                                                                                   \
+        };                                                                                      \
+        template<typename Left, typename Right, typename LeftTag, typename RightTag>            \
+        struct Name                                                                             \
+          : Name ## _base<Left, Right, void>                                                    \
+        {};                                                                                     \
+    }                                                                                           \
+    namespace op                                                                                \
+    {                                                                                           \
+        struct Name                                                                             \
+          : boost::detail::function2<                                                           \
+                functional::Name<_1, _2, functional::tag<_1>, functional::tag<_2> >             \
+            >                                                                                   \
+        {};                                                                                     \
+    }                                                                                           \
+    namespace                                                                                   \
+    {                                                                                           \
+        op::Name const &Name = boost::detail::pod_singleton<op::Name>::instance;                \
+    }                                                                                           \
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(Name)                                                      \
+    /**/
+
+    /// INTERNAL ONLY
+    ///
+#define BOOST_NUMERIC_FUNCTIONAL_DEDUCED(Left, Op, Right)                                       \
+    BOOST_TYPEOF_NESTED_TYPEDEF_TPL(                                                            \
+        nested                                                                                  \
+      , boost::numeric::functional::detail::lvalue_of<Left>() Op                                \
+        boost::numeric::functional::detail::lvalue_of<Right>()                                  \
+    )                                                                                           \
+    typedef typename nested::type type;                                                         \
+    /**/
+
+    /// INTERNAL ONLY
+    ///
+#define BOOST_NUMERIC_FUNCTIONAL_LEFT(Left, Op, Right)                                          \
+    typedef Left &type;                                                                         \
+    /**/
+
+    BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(plus, +, BOOST_NUMERIC_FUNCTIONAL_DEDUCED)
+    BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(minus, -, BOOST_NUMERIC_FUNCTIONAL_DEDUCED)
+    BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(multiplies, *, BOOST_NUMERIC_FUNCTIONAL_DEDUCED)
+    BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(divides, /, BOOST_NUMERIC_FUNCTIONAL_DEDUCED)
+    BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(modulus, %, BOOST_NUMERIC_FUNCTIONAL_DEDUCED)
+    BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(greater, >, BOOST_NUMERIC_FUNCTIONAL_DEDUCED)
+    BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(greater_equal, >=, BOOST_NUMERIC_FUNCTIONAL_DEDUCED)
+    BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(less, <, BOOST_NUMERIC_FUNCTIONAL_DEDUCED)
+    BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(less_equal, <=, BOOST_NUMERIC_FUNCTIONAL_DEDUCED)
+    BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(equal_to, ==, BOOST_NUMERIC_FUNCTIONAL_DEDUCED)
+    BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(not_equal_to, !=, BOOST_NUMERIC_FUNCTIONAL_DEDUCED)
+
+    BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(assign, =, BOOST_NUMERIC_FUNCTIONAL_LEFT)
+    BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(plus_assign, +=, BOOST_NUMERIC_FUNCTIONAL_LEFT)
+    BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(minus_assign, -=, BOOST_NUMERIC_FUNCTIONAL_LEFT)
+    BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(multiplies_assign, *=, BOOST_NUMERIC_FUNCTIONAL_LEFT)
+    BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(divides_assign, /=, BOOST_NUMERIC_FUNCTIONAL_LEFT)
+    BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(modulus_assign, %=, BOOST_NUMERIC_FUNCTIONAL_LEFT)
+
+    BOOST_NUMERIC_FUNCTIONAL_DEFINE_UNARY_OP(unary_plus, +)
+    BOOST_NUMERIC_FUNCTIONAL_DEFINE_UNARY_OP(unary_minus, -)
+    BOOST_NUMERIC_FUNCTIONAL_DEFINE_UNARY_OP(complement, ~)
+    BOOST_NUMERIC_FUNCTIONAL_DEFINE_UNARY_OP(logical_not, !)
+
+#undef BOOST_NUMERIC_FUNCTIONAL_LEFT
+#undef BOOST_NUMERIC_FUNCTIONAL_DEDUCED
+#undef BOOST_NUMERIC_FUNCTIONAL_DEFINE_UNARY_OP
+#undef BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP
+
+    namespace functional
+    {
+        template<typename Left, typename Right, typename EnableIf>
+        struct min_assign_base
+        {
+            typedef Left first_argument_type;
+            typedef Right second_argument_type;
+            typedef void result_type;
+
+            void operator ()(Left &left, Right &right) const
+            {
+                if(numeric::less(right, left))
+                {
+                    left = right;
+                }
+            }
+        };
+
+        template<typename Left, typename Right, typename EnableIf>
+        struct max_assign_base
+        {
+            typedef Left first_argument_type;
+            typedef Right second_argument_type;
+            typedef void result_type;
+
+            void operator ()(Left &left, Right &right) const
+            {
+                if(numeric::greater(right, left))
+                {
+                    left = right;
+                }
+            }
+        };
+
+        template<typename Left, typename Right, typename EnableIf>
+        struct fdiv_base
+          : functional::divides<Left, Right>
+        {};
+
+        // partial specialization that promotes the arguments to double for
+        // integral division.
+        template<typename Left, typename Right>
+        struct fdiv_base<Left, Right, typename enable_if<are_integral<Left, Right> >::type>
+          : functional::divides<double const, double const>
+        {};
+
+        template<typename To, typename From, typename EnableIf>
+        struct promote_base
+        {
+            typedef From argument_type;
+            typedef To result_type;
+
+            To operator ()(From &from) const
+            {
+                return from;
+            }
+        };
+
+        template<typename ToFrom>
+        struct promote_base<ToFrom, ToFrom, void>
+        {
+            typedef ToFrom argument_type;
+            typedef ToFrom result_type;
+
+            ToFrom &operator ()(ToFrom &tofrom)
+            {
+                return tofrom;
+            }
+        };
+
+        template<typename Arg, typename EnableIf>
+        struct as_min_base
+        {
+            BOOST_STATIC_ASSERT(std::numeric_limits<typename remove_const<Arg>::type>::is_specialized);
+
+            typedef Arg argument_type;
+            typedef typename remove_const<Arg>::type result_type;
+
+            typename remove_const<Arg>::type operator ()(Arg &) const
+            {
+                return (std::numeric_limits<typename remove_const<Arg>::type>::min)();
+            }
+        };
+
+        template<typename Arg>
+        struct as_min_base<Arg, typename enable_if<is_floating_point<Arg> >::type>
+        {
+            BOOST_STATIC_ASSERT(std::numeric_limits<typename remove_const<Arg>::type>::is_specialized);
+
+            typedef Arg argument_type;
+            typedef typename remove_const<Arg>::type result_type;
+
+            typename remove_const<Arg>::type operator ()(Arg &) const
+            {
+                return -(std::numeric_limits<typename remove_const<Arg>::type>::max)();
+            }
+        };
+
+        template<typename Arg, typename EnableIf>
+        struct as_max_base
+        {
+            BOOST_STATIC_ASSERT(std::numeric_limits<typename remove_const<Arg>::type>::is_specialized);
+
+            typedef Arg argument_type;
+            typedef typename remove_const<Arg>::type result_type;
+
+            typename remove_const<Arg>::type operator ()(Arg &) const
+            {
+                return (std::numeric_limits<typename remove_const<Arg>::type>::max)();
+            }
+        };
+
+        template<typename Arg, typename EnableIf>
+        struct as_zero_base
+        {
+            typedef Arg argument_type;
+            typedef typename remove_const<Arg>::type result_type;
+
+            typename remove_const<Arg>::type operator ()(Arg &) const
+            {
+                return numeric::zero<typename remove_const<Arg>::type>::value;
+            }
+        };
+
+        template<typename Arg, typename EnableIf>
+        struct as_one_base
+        {
+            typedef Arg argument_type;
+            typedef typename remove_const<Arg>::type result_type;
+
+            typename remove_const<Arg>::type operator ()(Arg &) const
+            {
+                return numeric::one<typename remove_const<Arg>::type>::value;
+            }
+        };
+
+        template<typename To, typename From, typename ToTag, typename FromTag>
+        struct promote
+          : promote_base<To, From, void>
+        {};
+
+        template<typename Left, typename Right, typename LeftTag, typename RightTag>
+        struct min_assign
+          : min_assign_base<Left, Right, void>
+        {};
+
+        template<typename Left, typename Right, typename LeftTag, typename RightTag>
+        struct max_assign
+          : max_assign_base<Left, Right, void>
+        {};
+
+        template<typename Left, typename Right, typename LeftTag, typename RightTag>
+        struct fdiv
+          : fdiv_base<Left, Right, void>
+        {};
+
+        /// INTERNAL ONLY 
+        /// For back-compat only. Use fdiv.
+        template<typename Left, typename Right, typename LeftTag, typename RightTag>
+        struct average
+          : fdiv<Left, Right, LeftTag, RightTag>
+        {};
+
+        template<typename Arg, typename Tag>
+        struct as_min
+          : as_min_base<Arg, void>
+        {};
+
+        template<typename Arg, typename Tag>
+        struct as_max
+          : as_max_base<Arg, void>
+        {};
+
+        template<typename Arg, typename Tag>
+        struct as_zero
+          : as_zero_base<Arg, void>
+        {};
+
+        template<typename Arg, typename Tag>
+        struct as_one
+          : as_one_base<Arg, void>
+        {};
+    }
+
+    namespace op
+    {
+        template<typename To>
+        struct promote
+          : boost::detail::function1<functional::promote<To, _, typename functional::tag<To>::type, functional::tag<_> > >
+        {};
+
+        struct min_assign
+          : boost::detail::function2<functional::min_assign<_1, _2, functional::tag<_1>, functional::tag<_2> > >
+        {};
+
+        struct max_assign
+          : boost::detail::function2<functional::max_assign<_1, _2, functional::tag<_1>, functional::tag<_2> > >
+        {};
+
+        struct fdiv
+          : boost::detail::function2<functional::fdiv<_1, _2, functional::tag<_1>, functional::tag<_2> > >
+        {};
+
+        /// INTERNAL ONLY
+        struct average
+          : boost::detail::function2<functional::fdiv<_1, _2, functional::tag<_1>, functional::tag<_2> > >
+        {};
+
+        struct as_min
+          : boost::detail::function1<functional::as_min<_, functional::tag<_> > >
+        {};
+
+        struct as_max
+          : boost::detail::function1<functional::as_max<_, functional::tag<_> > >
+        {};
+
+        struct as_zero
+          : boost::detail::function1<functional::as_zero<_, functional::tag<_> > >
+        {};
+
+        struct as_one
+          : boost::detail::function1<functional::as_one<_, functional::tag<_> > >
+        {};
+    }
+
+    namespace
+    {
+        op::min_assign const &min_assign = boost::detail::pod_singleton<op::min_assign>::instance;
+        op::max_assign const &max_assign = boost::detail::pod_singleton<op::max_assign>::instance;
+        op::fdiv const &fdiv = boost::detail::pod_singleton<op::fdiv>::instance;
+        op::fdiv const &average = boost::detail::pod_singleton<op::fdiv>::instance; ///< INTERNAL ONLY
+        op::as_min const &as_min = boost::detail::pod_singleton<op::as_min>::instance;
+        op::as_max const &as_max = boost::detail::pod_singleton<op::as_max>::instance;
+        op::as_zero const &as_zero = boost::detail::pod_singleton<op::as_zero>::instance;
+        op::as_one const &as_one = boost::detail::pod_singleton<op::as_one>::instance;
+
+        BOOST_ACCUMULATORS_IGNORE_GLOBAL(min_assign)
+        BOOST_ACCUMULATORS_IGNORE_GLOBAL(max_assign)
+        BOOST_ACCUMULATORS_IGNORE_GLOBAL(fdiv)
+        BOOST_ACCUMULATORS_IGNORE_GLOBAL(average)
+        BOOST_ACCUMULATORS_IGNORE_GLOBAL(as_min)
+        BOOST_ACCUMULATORS_IGNORE_GLOBAL(as_max)
+        BOOST_ACCUMULATORS_IGNORE_GLOBAL(as_zero)
+        BOOST_ACCUMULATORS_IGNORE_GLOBAL(as_one)
+    }
+
+    ///////////////////////////////////////////////////////////////////////////////
+    // promote
+    template<typename To, typename From>
+    typename lazy_disable_if<is_const<From>, mpl::if_<is_same<To, From>, To &, To> >::type
+    promote(From &from)
+    {
+        return functional::promote<To, From>()(from);
+    }
+
+    template<typename To, typename From>
+    typename mpl::if_<is_same<To const, From const>, To const &, To const>::type
+    promote(From const &from)
+    {
+        return functional::promote<To const, From const>()(from);
+    }
+
+    template<typename T>
+    struct default_
+    {
+        typedef default_ type;
+        typedef T value_type;
+        static T const value;
+
+        operator T const & () const
+        {
+            return default_::value;
+        }
+    };
+
+    template<typename T>
+    T const default_<T>::value = T();
+
+    template<typename T>
+    struct one
+    {
+        typedef one type;
+        typedef T value_type;
+        static T const value;
+
+        operator T const & () const
+        {
+            return one::value;
+        }
+    };
+
+    template<typename T>
+    T const one<T>::value = T(1);
+
+    template<typename T>
+    struct zero
+    {
+        typedef zero type;
+        typedef T value_type;
+        static T const value;
+
+        operator T const & () const
+        {
+            return zero::value;
+        }
+    };
+
+    template<typename T>
+    T const zero<T>::value = T();
+
+    template<typename T>
+    struct one_or_default
+      : mpl::if_<is_empty<T>, default_<T>, one<T> >::type
+    {};
+
+    template<typename T>
+    struct zero_or_default
+      : mpl::if_<is_empty<T>, default_<T>, zero<T> >::type
+    {};
+
+}} // namespace boost::numeric
+
+#endif

+ 82 - 0
library/include/boost/accumulators/numeric/functional/complex.hpp

@@ -0,0 +1,82 @@
+///////////////////////////////////////////////////////////////////////////////
+/// \file complex.hpp
+///
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_NUMERIC_FUNCTIONAL_COMPLEX_HPP_EAN_01_17_2006
+#define BOOST_NUMERIC_FUNCTIONAL_COMPLEX_HPP_EAN_01_17_2006
+
+#ifdef BOOST_NUMERIC_FUNCTIONAL_HPP_INCLUDED
+# error Include this file before boost/accumulators/numeric/functional.hpp
+#endif
+
+#include <complex>
+#include <boost/mpl/or.hpp>
+#include <boost/type_traits/is_same.hpp>
+#include <boost/utility/enable_if.hpp>
+#include <boost/typeof/std/complex.hpp>
+#include <boost/accumulators/numeric/functional_fwd.hpp>
+
+namespace boost { namespace numeric { namespace operators
+{
+    // So that the stats compile when Sample type is std::complex
+    template<typename T, typename U>
+    typename
+        disable_if<
+            mpl::or_<is_same<T, U>, is_same<std::complex<T>, U> >
+          , std::complex<T>
+        >::type
+    operator *(std::complex<T> ri, U const &u)
+    {
+        // BUGBUG promote result to typeof(T()*u) ?
+        return ri *= static_cast<T>(u);
+    }
+
+    template<typename T, typename U>
+    typename
+        disable_if<
+            mpl::or_<is_same<T, U>, is_same<std::complex<T>, U> >
+          , std::complex<T>
+        >::type
+    operator /(std::complex<T> ri, U const &u)
+    {
+        // BUGBUG promote result to typeof(T()*u) ?
+        return ri /= static_cast<T>(u);
+    }
+
+}}} // namespace boost::numeric::operators
+
+namespace boost { namespace numeric
+{
+    namespace detail
+    {
+        template<typename T>
+        struct one_complex
+        {
+            static std::complex<T> const value;
+        };
+
+        template<typename T>
+        std::complex<T> const one_complex<T>::value
+          = std::complex<T>(numeric::one<T>::value, numeric::one<T>::value);
+    }
+
+    /// INTERNAL ONLY
+    ///
+    template<typename T>
+    struct one<std::complex<T> >
+      : detail::one_complex<T>
+    {
+        typedef one type;
+        typedef std::complex<T> value_type;
+        operator value_type const & () const
+        {
+            return detail::one_complex<T>::value;
+        }
+    };
+
+}} // namespace boost::numeric
+
+#endif

+ 362 - 0
library/include/boost/accumulators/numeric/functional/valarray.hpp

@@ -0,0 +1,362 @@
+///////////////////////////////////////////////////////////////////////////////
+/// \file valarray.hpp
+///
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_NUMERIC_FUNCTIONAL_VALARRAY_HPP_EAN_12_12_2005
+#define BOOST_NUMERIC_FUNCTIONAL_VALARRAY_HPP_EAN_12_12_2005
+
+#ifdef BOOST_NUMERIC_FUNCTIONAL_HPP_INCLUDED
+# error Include this file before boost/accumulators/numeric/functional.hpp
+#endif
+
+#include <valarray>
+#include <functional>
+#include <boost/assert.hpp>
+#include <boost/mpl/and.hpp>
+#include <boost/mpl/not.hpp>
+#include <boost/mpl/assert.hpp>
+#include <boost/utility/enable_if.hpp>
+#include <boost/type_traits/is_same.hpp>
+#include <boost/type_traits/is_scalar.hpp>
+#include <boost/type_traits/remove_const.hpp>
+#include <boost/typeof/std/valarray.hpp>
+#include <boost/accumulators/numeric/functional_fwd.hpp>
+
+namespace boost { namespace numeric
+{
+    namespace operators
+    {
+        namespace acc_detail
+        {
+            template<typename Fun>
+            struct make_valarray
+            {
+                typedef std::valarray<typename Fun::result_type> type;
+            };
+        }
+
+        ///////////////////////////////////////////////////////////////////////////////
+        // Handle valarray<Left> / Right where Right is a scalar and Right != Left.
+        template<typename Left, typename Right>
+        typename lazy_enable_if<
+            mpl::and_<is_scalar<Right>, mpl::not_<is_same<Left, Right> > >
+          , acc_detail::make_valarray<functional::divides<Left, Right> >
+        >::type
+        operator /(std::valarray<Left> const &left, Right const &right)
+        {
+            typedef typename functional::divides<Left, Right>::result_type value_type;
+            std::valarray<value_type> result(left.size());
+            for(std::size_t i = 0, size = result.size(); i != size; ++i)
+            {
+                result[i] = numeric::divides(left[i], right);
+            }
+            return result;
+        }
+
+        ///////////////////////////////////////////////////////////////////////////////
+        // Handle valarray<Left> * Right where Right is a scalar and Right != Left.
+        template<typename Left, typename Right>
+        typename lazy_enable_if<
+            mpl::and_<is_scalar<Right>, mpl::not_<is_same<Left, Right> > >
+          , acc_detail::make_valarray<functional::multiplies<Left, Right> >
+        >::type
+        operator *(std::valarray<Left> const &left, Right const &right)
+        {
+            typedef typename functional::multiplies<Left, Right>::result_type value_type;
+            std::valarray<value_type> result(left.size());
+            for(std::size_t i = 0, size = result.size(); i != size; ++i)
+            {
+                result[i] = numeric::multiplies(left[i], right);
+            }
+            return result;
+        }
+
+        ///////////////////////////////////////////////////////////////////////////////
+        // Handle valarray<Left> + valarray<Right> where Right != Left.
+        template<typename Left, typename Right>
+        typename lazy_disable_if<
+            is_same<Left, Right>
+          , acc_detail::make_valarray<functional::plus<Left, Right> >
+        >::type
+        operator +(std::valarray<Left> const &left, std::valarray<Right> const &right)
+        {
+            typedef typename functional::plus<Left, Right>::result_type value_type;
+            std::valarray<value_type> result(left.size());
+            for(std::size_t i = 0, size = result.size(); i != size; ++i)
+            {
+                result[i] = numeric::plus(left[i], right[i]);
+            }
+            return result;
+        }
+    }
+
+    namespace functional
+    {
+        struct std_valarray_tag;
+
+        template<typename T>
+        struct tag<std::valarray<T> >
+        {
+            typedef std_valarray_tag type;
+        };
+
+    #ifdef __GLIBCXX__
+        template<typename T, typename U>
+        struct tag<std::_Expr<T, U> >
+        {
+            typedef std_valarray_tag type;
+        };
+    #endif
+
+        /// INTERNAL ONLY
+        ///
+        // This is necessary because the GCC stdlib uses expression templates, and
+        // typeof(som-valarray-expression) is not an instance of std::valarray
+    #define BOOST_NUMERIC_FUNCTIONAL_DEFINE_VALARRAY_BIN_OP(Name, Op)                   \
+        template<typename Left, typename Right>                                         \
+        struct Name<Left, Right, std_valarray_tag, std_valarray_tag>                    \
+        {                                                                               \
+            typedef Left first_argument_type;                                           \
+            typedef Right second_argument_type;                                         \
+            typedef typename Left::value_type left_value_type;                          \
+            typedef typename Right::value_type right_value_type;                        \
+            typedef                                                                     \
+                std::valarray<                                                          \
+                    typename Name<left_value_type, right_value_type>::result_type       \
+                >                                                                       \
+            result_type;                                                                \
+            result_type                                                                 \
+            operator ()(Left &left, Right &right) const                                 \
+            {                                                                           \
+                return numeric::promote<std::valarray<left_value_type> >(left)          \
+                    Op numeric::promote<std::valarray<right_value_type> >(right);       \
+            }                                                                           \
+        };                                                                              \
+        template<typename Left, typename Right>                                         \
+        struct Name<Left, Right, std_valarray_tag, void>                                \
+        {                                                                               \
+            typedef Left first_argument_type;                                           \
+            typedef Right second_argument_type;                                         \
+            typedef typename Left::value_type left_value_type;                          \
+            typedef                                                                     \
+                std::valarray<                                                          \
+                    typename Name<left_value_type, Right>::result_type                  \
+                >                                                                       \
+            result_type;                                                                \
+            result_type                                                                 \
+            operator ()(Left &left, Right &right) const                                 \
+            {                                                                           \
+                return numeric::promote<std::valarray<left_value_type> >(left) Op right;\
+            }                                                                           \
+        };                                                                              \
+        template<typename Left, typename Right>                                         \
+        struct Name<Left, Right, void, std_valarray_tag>                                \
+        {                                                                               \
+            typedef Left first_argument_type;                                           \
+            typedef Right second_argument_type;                                         \
+            typedef typename Right::value_type right_value_type;                        \
+            typedef                                                                     \
+                std::valarray<                                                          \
+                    typename Name<Left, right_value_type>::result_type                  \
+                >                                                                       \
+            result_type;                                                                \
+            result_type                                                                 \
+            operator ()(Left &left, Right &right) const                                 \
+            {                                                                           \
+                return left Op numeric::promote<std::valarray<right_value_type> >(right);\
+            }                                                                           \
+        };
+
+        BOOST_NUMERIC_FUNCTIONAL_DEFINE_VALARRAY_BIN_OP(plus, +)
+        BOOST_NUMERIC_FUNCTIONAL_DEFINE_VALARRAY_BIN_OP(minus, -)
+        BOOST_NUMERIC_FUNCTIONAL_DEFINE_VALARRAY_BIN_OP(multiplies, *)
+        BOOST_NUMERIC_FUNCTIONAL_DEFINE_VALARRAY_BIN_OP(divides, /)
+        BOOST_NUMERIC_FUNCTIONAL_DEFINE_VALARRAY_BIN_OP(modulus, %)
+
+    #undef BOOST_NUMERIC_FUNCTIONAL_DEFINE_VALARRAY_BIN_OP
+
+        ///////////////////////////////////////////////////////////////////////////////
+        // element-wise min of std::valarray
+        template<typename Left, typename Right>
+        struct min_assign<Left, Right, std_valarray_tag, std_valarray_tag>
+        {
+            typedef Left first_argument_type;
+            typedef Right second_argument_type;
+            typedef void result_type;
+
+            void operator ()(Left &left, Right &right) const
+            {
+                BOOST_ASSERT(left.size() == right.size());
+                for(std::size_t i = 0, size = left.size(); i != size; ++i)
+                {
+                    if(numeric::less(right[i], left[i]))
+                    {
+                        left[i] = right[i];
+                    }
+                }
+            }
+        };
+
+        ///////////////////////////////////////////////////////////////////////////////
+        // element-wise max of std::valarray
+        template<typename Left, typename Right>
+        struct max_assign<Left, Right, std_valarray_tag, std_valarray_tag>
+        {
+            typedef Left first_argument_type;
+            typedef Right second_argument_type;
+            typedef void result_type;
+
+            void operator ()(Left &left, Right &right) const
+            {
+                BOOST_ASSERT(left.size() == right.size());
+                for(std::size_t i = 0, size = left.size(); i != size; ++i)
+                {
+                    if(numeric::greater(right[i], left[i]))
+                    {
+                        left[i] = right[i];
+                    }
+                }
+            }
+        };
+
+        // partial specialization of numeric::fdiv<> for std::valarray.
+        template<typename Left, typename Right, typename RightTag>
+        struct fdiv<Left, Right, std_valarray_tag, RightTag>
+          : mpl::if_<
+                are_integral<typename Left::value_type, Right>
+              , divides<Left, double const>
+              , divides<Left, Right>
+            >::type
+        {};
+
+        // promote
+        template<typename To, typename From>
+        struct promote<To, From, std_valarray_tag, std_valarray_tag>
+        {
+            typedef From argument_type;
+            typedef To result_type;
+
+            To operator ()(From &arr) const
+            {
+                typename remove_const<To>::type res(arr.size());
+                for(std::size_t i = 0, size = arr.size(); i != size; ++i)
+                {
+                    res[i] = numeric::promote<typename To::value_type>(arr[i]);
+                }
+                return res;
+            }
+        };
+
+        template<typename ToFrom>
+        struct promote<ToFrom, ToFrom, std_valarray_tag, std_valarray_tag>
+        {
+            typedef ToFrom argument_type;
+            typedef ToFrom result_type;
+
+            ToFrom &operator ()(ToFrom &tofrom) const
+            {
+                return tofrom;
+            }
+        };
+
+        // for "promoting" a std::valarray<bool> to a bool, useful for
+        // comparing 2 valarrays for equality:
+        //   if(numeric::promote<bool>(a == b))
+        template<typename From>
+        struct promote<bool, From, void, std_valarray_tag>
+        {
+            typedef From argument_type;
+            typedef bool result_type;
+
+            bool operator ()(From &arr) const
+            {
+                BOOST_MPL_ASSERT((is_same<bool, typename From::value_type>));
+                for(std::size_t i = 0, size = arr.size(); i != size; ++i)
+                {
+                    if(!arr[i])
+                    {
+                        return false;
+                    }
+                }
+                return true;
+            }
+        };
+
+        template<typename From>
+        struct promote<bool const, From, void, std_valarray_tag>
+          : promote<bool, From, void, std_valarray_tag>
+        {};
+
+        ///////////////////////////////////////////////////////////////////////////////
+        // functional::as_min
+        template<typename T>
+        struct as_min<T, std_valarray_tag>
+        {
+            typedef T argument_type;
+            typedef typename remove_const<T>::type result_type;
+
+            typename remove_const<T>::type operator ()(T &arr) const
+            {
+                return 0 == arr.size()
+                  ? T()
+                  : T(numeric::as_min(arr[0]), arr.size());
+            }
+        };
+
+        ///////////////////////////////////////////////////////////////////////////////
+        // functional::as_max
+        template<typename T>
+        struct as_max<T, std_valarray_tag>
+        {
+            typedef T argument_type;
+            typedef typename remove_const<T>::type result_type;
+
+            typename remove_const<T>::type operator ()(T &arr) const
+            {
+                return 0 == arr.size()
+                  ? T()
+                  : T(numeric::as_max(arr[0]), arr.size());
+            }
+        };
+
+        ///////////////////////////////////////////////////////////////////////////////
+        // functional::as_zero
+        template<typename T>
+        struct as_zero<T, std_valarray_tag>
+        {
+            typedef T argument_type;
+            typedef typename remove_const<T>::type result_type;
+
+            typename remove_const<T>::type operator ()(T &arr) const
+            {
+                return 0 == arr.size()
+                  ? T()
+                  : T(numeric::as_zero(arr[0]), arr.size());
+            }
+        };
+
+        ///////////////////////////////////////////////////////////////////////////////
+        // functional::as_one
+        template<typename T>
+        struct as_one<T, std_valarray_tag>
+        {
+            typedef T argument_type;
+            typedef typename remove_const<T>::type result_type;
+
+            typename remove_const<T>::type operator ()(T &arr) const
+            {
+                return 0 == arr.size()
+                  ? T()
+                  : T(numeric::as_one(arr[0]), arr.size());
+            }
+        };
+
+    } // namespace functional
+
+}} // namespace boost::numeric
+
+#endif
+

+ 347 - 0
library/include/boost/accumulators/numeric/functional/vector.hpp

@@ -0,0 +1,347 @@
+///////////////////////////////////////////////////////////////////////////////
+/// \file vector.hpp
+///
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_NUMERIC_FUNCTIONAL_VECTOR_HPP_EAN_12_12_2005
+#define BOOST_NUMERIC_FUNCTIONAL_VECTOR_HPP_EAN_12_12_2005
+
+#ifdef BOOST_NUMERIC_FUNCTIONAL_HPP_INCLUDED
+# error Include this file before boost/accumulators/numeric/functional.hpp
+#endif
+
+#include <vector>
+#include <functional>
+#include <boost/assert.hpp>
+#include <boost/mpl/and.hpp>
+#include <boost/mpl/not.hpp>
+#include <boost/utility/enable_if.hpp>
+#include <boost/type_traits/is_same.hpp>
+#include <boost/type_traits/is_scalar.hpp>
+#include <boost/type_traits/remove_const.hpp>
+#include <boost/typeof/std/vector.hpp>
+#include <boost/accumulators/numeric/functional_fwd.hpp>
+
+namespace boost { namespace numeric
+{
+    namespace operators
+    {
+        namespace acc_detail
+        {
+            template<typename Fun>
+            struct make_vector
+            {
+                typedef std::vector<typename Fun::result_type> type;
+            };
+        }
+
+        ///////////////////////////////////////////////////////////////////////////////
+        // Handle vector<Left> / Right where Right is a scalar.
+        template<typename Left, typename Right>
+        typename lazy_enable_if<
+            is_scalar<Right>
+          , acc_detail::make_vector<functional::divides<Left, Right> >
+        >::type
+        operator /(std::vector<Left> const &left, Right const &right)
+        {
+            typedef typename functional::divides<Left, Right>::result_type value_type;
+            std::vector<value_type> result(left.size());
+            for(std::size_t i = 0, size = result.size(); i != size; ++i)
+            {
+                result[i] = numeric::divides(left[i], right);
+            }
+            return result;
+        }
+
+        ///////////////////////////////////////////////////////////////////////////////
+        // Handle vector<Left> / vector<Right>.
+        template<typename Left, typename Right>
+        std::vector<typename functional::divides<Left, Right>::result_type>
+        operator /(std::vector<Left> const &left, std::vector<Right> const &right)
+        {
+            typedef typename functional::divides<Left, Right>::result_type value_type;
+            std::vector<value_type> result(left.size());
+            for(std::size_t i = 0, size = result.size(); i != size; ++i)
+            {
+                result[i] = numeric::divides(left[i], right[i]);
+            }
+            return result;
+        }
+
+        ///////////////////////////////////////////////////////////////////////////////
+        // Handle vector<Left> * Right where Right is a scalar.
+        template<typename Left, typename Right>
+        typename lazy_enable_if<
+            is_scalar<Right>
+          , acc_detail::make_vector<functional::multiplies<Left, Right> >
+        >::type
+        operator *(std::vector<Left> const &left, Right const &right)
+        {
+            typedef typename functional::multiplies<Left, Right>::result_type value_type;
+            std::vector<value_type> result(left.size());
+            for(std::size_t i = 0, size = result.size(); i != size; ++i)
+            {
+                result[i] = numeric::multiplies(left[i], right);
+            }
+            return result;
+        }
+
+        ///////////////////////////////////////////////////////////////////////////////
+        // Handle Left * vector<Right> where Left is a scalar.
+        template<typename Left, typename Right>
+        typename lazy_enable_if<
+            is_scalar<Left>
+          , acc_detail::make_vector<functional::multiplies<Left, Right> >
+        >::type
+        operator *(Left const &left, std::vector<Right> const &right)
+        {
+            typedef typename functional::multiplies<Left, Right>::result_type value_type;
+            std::vector<value_type> result(right.size());
+            for(std::size_t i = 0, size = result.size(); i != size; ++i)
+            {
+                result[i] = numeric::multiplies(left, right[i]);
+            }
+            return result;
+        }
+
+        ///////////////////////////////////////////////////////////////////////////////
+        // Handle vector<Left> * vector<Right>
+        template<typename Left, typename Right>
+        std::vector<typename functional::multiplies<Left, Right>::result_type>
+        operator *(std::vector<Left> const &left, std::vector<Right> const &right)
+        {
+            typedef typename functional::multiplies<Left, Right>::result_type value_type;
+            std::vector<value_type> result(left.size());
+            for(std::size_t i = 0, size = result.size(); i != size; ++i)
+            {
+                result[i] = numeric::multiplies(left[i], right[i]);
+            }
+            return result;
+        }
+
+        ///////////////////////////////////////////////////////////////////////////////
+        // Handle vector<Left> + vector<Right>
+        template<typename Left, typename Right>
+        std::vector<typename functional::plus<Left, Right>::result_type>
+        operator +(std::vector<Left> const &left, std::vector<Right> const &right)
+        {
+            typedef typename functional::plus<Left, Right>::result_type value_type;
+            std::vector<value_type> result(left.size());
+            for(std::size_t i = 0, size = result.size(); i != size; ++i)
+            {
+                result[i] = numeric::plus(left[i], right[i]);
+            }
+            return result;
+        }
+
+        ///////////////////////////////////////////////////////////////////////////////
+        // Handle vector<Left> - vector<Right>
+        template<typename Left, typename Right>
+        std::vector<typename functional::minus<Left, Right>::result_type>
+        operator -(std::vector<Left> const &left, std::vector<Right> const &right)
+        {
+            typedef typename functional::minus<Left, Right>::result_type value_type;
+            std::vector<value_type> result(left.size());
+            for(std::size_t i = 0, size = result.size(); i != size; ++i)
+            {
+                result[i] = numeric::minus(left[i], right[i]);
+            }
+            return result;
+        }
+
+        ///////////////////////////////////////////////////////////////////////////////
+        // Handle vector<Left> += vector<Left>
+        template<typename Left>
+        std::vector<Left> &
+        operator +=(std::vector<Left> &left, std::vector<Left> const &right)
+        {
+            BOOST_ASSERT(left.size() == right.size());
+            for(std::size_t i = 0, size = left.size(); i != size; ++i)
+            {
+                numeric::plus_assign(left[i], right[i]);
+            }
+            return left;
+        }
+
+        ///////////////////////////////////////////////////////////////////////////////
+        // Handle -vector<Arg>
+        template<typename Arg>
+        std::vector<typename functional::unary_minus<Arg>::result_type>
+        operator -(std::vector<Arg> const &arg)
+        {
+            typedef typename functional::unary_minus<Arg>::result_type value_type;
+            std::vector<value_type> result(arg.size());
+            for(std::size_t i = 0, size = result.size(); i != size; ++i)
+            {
+                result[i] = numeric::unary_minus(arg[i]);
+            }
+            return result;
+        }
+    }
+
+    namespace functional
+    {
+        struct std_vector_tag;
+
+        template<typename T, typename Al>
+        struct tag<std::vector<T, Al> >
+        {
+            typedef std_vector_tag type;
+        };
+
+        ///////////////////////////////////////////////////////////////////////////////
+        // element-wise min of std::vector
+        template<typename Left, typename Right>
+        struct min_assign<Left, Right, std_vector_tag, std_vector_tag>
+        {
+            typedef Left first_argument_type;
+            typedef Right second_argument_type;
+            typedef void result_type;
+
+            void operator ()(Left &left, Right &right) const
+            {
+                BOOST_ASSERT(left.size() == right.size());
+                for(std::size_t i = 0, size = left.size(); i != size; ++i)
+                {
+                    if(numeric::less(right[i], left[i]))
+                    {
+                        left[i] = right[i];
+                    }
+                }
+            }
+        };
+
+        ///////////////////////////////////////////////////////////////////////////////
+        // element-wise max of std::vector
+        template<typename Left, typename Right>
+        struct max_assign<Left, Right, std_vector_tag, std_vector_tag>
+        {
+            typedef Left first_argument_type;
+            typedef Right second_argument_type;
+            typedef void result_type;
+
+            void operator ()(Left &left, Right &right) const
+            {
+                BOOST_ASSERT(left.size() == right.size());
+                for(std::size_t i = 0, size = left.size(); i != size; ++i)
+                {
+                    if(numeric::greater(right[i], left[i]))
+                    {
+                        left[i] = right[i];
+                    }
+                }
+            }
+        };
+
+        // partial specialization for std::vector.
+        template<typename Left, typename Right>
+        struct fdiv<Left, Right, std_vector_tag, void>
+          : mpl::if_<
+                are_integral<typename Left::value_type, Right>
+              , divides<Left, double const>
+              , divides<Left, Right>
+            >::type
+        {};
+
+        // promote
+        template<typename To, typename From>
+        struct promote<To, From, std_vector_tag, std_vector_tag>
+        {
+            typedef From argument_type;
+            typedef To result_type;
+
+            To operator ()(From &arr) const
+            {
+                typename remove_const<To>::type res(arr.size());
+                for(std::size_t i = 0, size = arr.size(); i != size; ++i)
+                {
+                    res[i] = numeric::promote<typename To::value_type>(arr[i]);
+                }
+                return res;
+            }
+        };
+
+        template<typename ToFrom>
+        struct promote<ToFrom, ToFrom, std_vector_tag, std_vector_tag>
+        {
+            typedef ToFrom argument_type;
+            typedef ToFrom result_type;
+
+            ToFrom &operator ()(ToFrom &tofrom) const
+            {
+                return tofrom;
+            }
+        };
+
+        ///////////////////////////////////////////////////////////////////////////////
+        // functional::as_min
+        template<typename T>
+        struct as_min<T, std_vector_tag>
+        {
+            typedef T argument_type;
+            typedef typename remove_const<T>::type result_type;
+
+            typename remove_const<T>::type operator ()(T &arr) const
+            {
+                return 0 == arr.size()
+                  ? T()
+                  : T(arr.size(), numeric::as_min(arr[0]));
+            }
+        };
+
+        ///////////////////////////////////////////////////////////////////////////////
+        // functional::as_max
+        template<typename T>
+        struct as_max<T, std_vector_tag>
+        {
+            typedef T argument_type;
+            typedef typename remove_const<T>::type result_type;
+
+            typename remove_const<T>::type operator ()(T &arr) const
+            {
+                return 0 == arr.size()
+                  ? T()
+                  : T(arr.size(), numeric::as_max(arr[0]));
+            }
+        };
+
+        ///////////////////////////////////////////////////////////////////////////////
+        // functional::as_zero
+        template<typename T>
+        struct as_zero<T, std_vector_tag>
+        {
+            typedef T argument_type;
+            typedef typename remove_const<T>::type result_type;
+
+            typename remove_const<T>::type operator ()(T &arr) const
+            {
+                return 0 == arr.size()
+                  ? T()
+                  : T(arr.size(), numeric::as_zero(arr[0]));
+            }
+        };
+
+        ///////////////////////////////////////////////////////////////////////////////
+        // functional::as_one
+        template<typename T>
+        struct as_one<T, std_vector_tag>
+        {
+            typedef T argument_type;
+            typedef typename remove_const<T>::type result_type;
+
+            typename remove_const<T>::type operator ()(T &arr) const
+            {
+                return 0 == arr.size()
+                  ? T()
+                  : T(arr.size(), numeric::as_one(arr[0]));
+            }
+        };
+
+    } // namespace functional
+
+}} // namespace boost::numeric
+
+#endif
+

+ 221 - 0
library/include/boost/accumulators/numeric/functional_fwd.hpp

@@ -0,0 +1,221 @@
+///////////////////////////////////////////////////////////////////////////////
+/// \file functional_fwd.hpp
+///
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_NUMERIC_FUNCTIONAL_FWD_HPP_EAN_08_12_2005
+#define BOOST_NUMERIC_FUNCTIONAL_FWD_HPP_EAN_08_12_2005
+
+#include <boost/mpl/if.hpp>
+#include <boost/mpl/placeholders.hpp>
+#include <boost/utility/enable_if.hpp>
+#include <boost/type_traits/is_same.hpp>
+#include <boost/type_traits/is_const.hpp>
+
+namespace boost { namespace numeric
+{
+    // For using directives -- this namespace may be re-opened elsewhere
+    namespace operators
+    {}
+
+    namespace op
+    {
+        using mpl::_;
+        using mpl::_1;
+        using mpl::_2;
+    }
+
+    namespace functional
+    {
+        using namespace operators;
+
+        template<typename T>
+        struct tag
+        {
+            typedef void type;
+        };
+
+        template<typename T>
+        struct tag<T const>
+          : tag<T>
+        {};
+
+        template<typename T>
+        struct tag<T volatile>
+          : tag<T>
+        {};
+
+        template<typename T>
+        struct tag<T const volatile>
+          : tag<T>
+        {};
+
+        template<typename T>
+        struct static_;
+
+        template<typename A0, typename A1>
+        struct are_integral;
+    }
+
+    /// INTERNAL ONLY
+    ///
+#define BOOST_NUMERIC_FUNCTIONAL_DECLARE_UNARY_OP(Name, Op)                                     \
+    namespace functional                                                                        \
+    {                                                                                           \
+        template<typename Arg, typename EnableIf = void>                                        \
+        struct Name ## _base;                                                                   \
+        template<typename Arg, typename ArgTag = typename tag<Arg>::type>                       \
+        struct Name;                                                                            \
+    }                                                                                           \
+    namespace op                                                                                \
+    {                                                                                           \
+        struct Name;                                                                            \
+    }                                                                                           \
+    namespace                                                                                   \
+    {                                                                                           \
+        extern op::Name const &Name;                                                            \
+    }
+
+    /// INTERNAL ONLY
+    ///
+#define BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(Name)                                        \
+    namespace functional                                                                        \
+    {                                                                                           \
+        template<typename Left, typename Right, typename EnableIf = void>                       \
+        struct result_of_ ## Name;                                                              \
+        template<typename Left, typename Right, typename EnableIf = void>                       \
+        struct Name ## _base;                                                                   \
+        template<                                                                               \
+            typename Left                                                                       \
+          , typename Right                                                                      \
+          , typename LeftTag = typename tag<Left>::type                                         \
+          , typename RightTag = typename tag<Right>::type                                       \
+        >                                                                                       \
+        struct Name;                                                                            \
+    }                                                                                           \
+    namespace op                                                                                \
+    {                                                                                           \
+        struct Name;                                                                            \
+    }                                                                                           \
+    namespace                                                                                   \
+    {                                                                                           \
+        extern op::Name const &Name;                                                            \
+    }
+
+    BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(plus)
+    BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(minus)
+    BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(multiplies)
+    BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(divides)
+    BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(modulus)
+    BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(greater)
+    BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(greater_equal)
+    BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(less)
+    BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(less_equal)
+    BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(equal_to)
+    BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(not_equal_to)
+
+    BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(assign)
+    BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(plus_assign)
+    BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(minus_assign)
+    BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(multiplies_assign)
+    BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(divides_assign)
+    BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(modulus_assign)
+
+    BOOST_NUMERIC_FUNCTIONAL_DECLARE_UNARY_OP(unary_plus, +)
+    BOOST_NUMERIC_FUNCTIONAL_DECLARE_UNARY_OP(unary_minus, -)
+    BOOST_NUMERIC_FUNCTIONAL_DECLARE_UNARY_OP(complement, ~)
+    BOOST_NUMERIC_FUNCTIONAL_DECLARE_UNARY_OP(logical_not, !)
+
+#undef BOOST_NUMERIC_FUNCTIONAL_DECLARE_UNARY_OP
+#undef BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP
+
+
+    namespace functional
+    {
+        template<typename To, typename From, typename EnableIf = void>
+        struct promote_base;
+        template<typename Left, typename Right, typename EnableIf = void>
+        struct min_assign_base;
+        template<typename Left, typename Right, typename EnableIf = void>
+        struct max_assign_base;
+        template<typename Left, typename Right, typename EnableIf = void>
+        struct fdiv_base;
+        template<typename Arg, typename EnableIf = void>
+        struct as_min_base;
+        template<typename Arg, typename EnableIf = void>
+        struct as_max_base;
+        template<typename Arg, typename EnableIf = void>
+        struct as_zero_base;
+        template<typename Arg, typename EnableIf = void>
+        struct as_one_base;
+
+        template<typename To, typename From, typename ToTag = typename tag<To>::type, typename FromTag = typename tag<From>::type>
+        struct promote;
+        template<typename Left, typename Right, typename LeftTag = typename tag<Left>::type, typename RightTag = typename tag<Right>::type>
+        struct min_assign;
+        template<typename Left, typename Right, typename LeftTag = typename tag<Left>::type, typename RightTag = typename tag<Right>::type>
+        struct max_assign;
+        template<typename Left, typename Right, typename LeftTag = typename tag<Left>::type, typename RightTag = typename tag<Right>::type>
+        struct fdiv;
+        template<typename Arg, typename Tag = typename tag<Arg>::type>
+        struct as_min;
+        template<typename Arg, typename Tag = typename tag<Arg>::type>
+        struct as_max;
+        template<typename Arg, typename Tag = typename tag<Arg>::type>
+        struct as_zero;
+        template<typename Arg, typename Tag = typename tag<Arg>::type>
+        struct as_one;
+    }
+
+    namespace op
+    {
+        template<typename To>
+        struct promote;
+        struct min_assign;
+        struct max_assign;
+        struct fdiv;
+        struct as_min;
+        struct as_max;
+        struct as_zero;
+        struct as_one;
+    }
+
+    namespace
+    {
+        extern op::min_assign const &min_assign;
+        extern op::max_assign const &max_assign;
+        extern op::fdiv const &fdiv;
+        extern op::as_min const &as_min;
+        extern op::as_max const &as_max;
+        extern op::as_zero const &as_zero;
+        extern op::as_one const &as_one;
+    }
+
+    template<typename To, typename From>
+    typename lazy_disable_if<is_const<From>, mpl::if_<is_same<To, From>, To &, To> >::type
+    promote(From &from);
+
+    template<typename To, typename From>
+    typename mpl::if_<is_same<To const, From const>, To const &, To const>::type
+    promote(From const &from);
+
+    template<typename T>
+    struct default_;
+
+    template<typename T>
+    struct one;
+
+    template<typename T>
+    struct zero;
+
+    template<typename T>
+    struct one_or_default;
+
+    template<typename T>
+    struct zero_or_default;
+
+}} // namespace boost::numeric
+
+#endif

+ 61 - 0
library/include/boost/accumulators/statistics.hpp

@@ -0,0 +1,61 @@
+///////////////////////////////////////////////////////////////////////////////
+/// \file statistics.hpp
+/// Includes all of the Statistical Accumulators Library
+//
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_HPP_EAN_01_17_2006
+#define BOOST_ACCUMULATORS_STATISTICS_HPP_EAN_01_17_2006
+
+#include <boost/accumulators/statistics/count.hpp>
+#include <boost/accumulators/statistics/covariance.hpp>
+#include <boost/accumulators/statistics/density.hpp>
+#include <boost/accumulators/statistics/error_of.hpp>
+#include <boost/accumulators/statistics/error_of_mean.hpp>
+#include <boost/accumulators/statistics/extended_p_square.hpp>
+#include <boost/accumulators/statistics/extended_p_square_quantile.hpp>
+#include <boost/accumulators/statistics/kurtosis.hpp>
+#include <boost/accumulators/statistics/max.hpp>
+#include <boost/accumulators/statistics/mean.hpp>
+#include <boost/accumulators/statistics/median.hpp>
+#include <boost/accumulators/statistics/min.hpp>
+#include <boost/accumulators/statistics/moment.hpp>
+#include <boost/accumulators/statistics/peaks_over_threshold.hpp>
+#include <boost/accumulators/statistics/pot_tail_mean.hpp>
+#include <boost/accumulators/statistics/pot_quantile.hpp>
+#include <boost/accumulators/statistics/p_square_cumul_dist.hpp>
+#include <boost/accumulators/statistics/p_square_quantile.hpp>
+#include <boost/accumulators/statistics/skewness.hpp>
+#include <boost/accumulators/statistics/stats.hpp>
+#include <boost/accumulators/statistics/sum.hpp>
+#include <boost/accumulators/statistics/sum_kahan.hpp>
+#include <boost/accumulators/statistics/tail.hpp>
+#include <boost/accumulators/statistics/tail_quantile.hpp>
+#include <boost/accumulators/statistics/tail_mean.hpp>
+#include <boost/accumulators/statistics/tail_variate.hpp>
+#include <boost/accumulators/statistics/tail_variate_means.hpp>
+#include <boost/accumulators/statistics/variance.hpp>
+#include <boost/accumulators/statistics/weighted_covariance.hpp>
+#include <boost/accumulators/statistics/weighted_density.hpp>
+#include <boost/accumulators/statistics/weighted_kurtosis.hpp>
+#include <boost/accumulators/statistics/weighted_extended_p_square.hpp>
+#include <boost/accumulators/statistics/weighted_mean.hpp>
+#include <boost/accumulators/statistics/weighted_median.hpp>
+#include <boost/accumulators/statistics/weighted_moment.hpp>
+#include <boost/accumulators/statistics/weighted_peaks_over_threshold.hpp>
+#include <boost/accumulators/statistics/weighted_p_square_cumul_dist.hpp>
+#include <boost/accumulators/statistics/weighted_p_square_quantile.hpp>
+#include <boost/accumulators/statistics/weighted_skewness.hpp>
+#include <boost/accumulators/statistics/weighted_sum.hpp>
+#include <boost/accumulators/statistics/weighted_sum_kahan.hpp>
+#include <boost/accumulators/statistics/weighted_tail_quantile.hpp>
+#include <boost/accumulators/statistics/weighted_tail_mean.hpp>
+#include <boost/accumulators/statistics/weighted_tail_variate_means.hpp>
+#include <boost/accumulators/statistics/weighted_variance.hpp>
+#include <boost/accumulators/statistics/with_error.hpp>
+#include <boost/accumulators/statistics/parameters/quantile_probability.hpp>
+#include <boost/accumulators/statistics/variates/covariate.hpp>
+
+#endif

+ 87 - 0
library/include/boost/accumulators/statistics/count.hpp

@@ -0,0 +1,87 @@
+///////////////////////////////////////////////////////////////////////////////
+// count.hpp
+//
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_COUNT_HPP_EAN_28_10_2005
+#define BOOST_ACCUMULATORS_STATISTICS_COUNT_HPP_EAN_28_10_2005
+
+#include <boost/mpl/always.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/framework/depends_on.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+
+namespace boost { namespace accumulators
+{
+
+namespace impl
+{
+
+    ///////////////////////////////////////////////////////////////////////////////
+    // count_impl
+    struct count_impl
+      : accumulator_base
+    {
+        // for boost::result_of
+        typedef std::size_t result_type;
+
+        count_impl(dont_care)
+          : cnt(0)
+        {
+        }
+
+        void operator ()(dont_care)
+        {
+            ++this->cnt;
+        }
+
+        result_type result(dont_care) const
+        {
+            return this->cnt;
+        }
+
+        // make this accumulator serializeable
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int /* file_version */)
+        {
+            ar & cnt;
+        }
+
+    private:
+        std::size_t cnt;
+    };
+
+} // namespace impl
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::count
+//
+namespace tag
+{
+    struct count
+      : depends_on<>
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef mpl::always<accumulators::impl::count_impl> impl;
+    };
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// extract::count
+//
+namespace extract
+{
+    extractor<tag::count> const count = {};
+
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(count)
+}
+
+using extract::count;
+
+}} // namespace boost::accumulators
+
+#endif

+ 219 - 0
library/include/boost/accumulators/statistics/covariance.hpp

@@ -0,0 +1,219 @@
+///////////////////////////////////////////////////////////////////////////////
+// covariance.hpp
+//
+//  Copyright 2006 Daniel Egloff, Olivier Gygi. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_COVARIANCE_HPP_DE_01_01_2006
+#define BOOST_ACCUMULATORS_STATISTICS_COVARIANCE_HPP_DE_01_01_2006
+
+#include <vector>
+#include <limits>
+#include <numeric>
+#include <functional>
+#include <complex>
+#include <boost/mpl/assert.hpp>
+#include <boost/mpl/bool.hpp>
+#include <boost/range.hpp>
+#include <boost/parameter/keyword.hpp>
+#include <boost/mpl/placeholders.hpp>
+#include <boost/numeric/ublas/io.hpp>
+#include <boost/numeric/ublas/matrix.hpp>
+#include <boost/type_traits/is_scalar.hpp>
+#include <boost/type_traits/is_same.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/numeric/functional.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+#include <boost/accumulators/statistics/count.hpp>
+#include <boost/accumulators/statistics/mean.hpp>
+
+namespace boost { namespace numeric
+{
+    namespace functional
+    {
+        struct std_vector_tag;
+
+        ///////////////////////////////////////////////////////////////////////////////
+        // functional::outer_product
+        template<typename Left, typename Right, typename EnableIf = void>
+        struct outer_product_base
+          : functional::multiplies<Left, Right>
+        {};
+
+        template<typename Left, typename Right, typename LeftTag = typename tag<Left>::type, typename RightTag = typename tag<Right>::type>
+        struct outer_product
+          : outer_product_base<Left, Right, void>
+        {};
+
+        template<typename Left, typename Right>
+        struct outer_product<Left, Right, std_vector_tag, std_vector_tag>
+        {
+            typedef Left first_argument_type;
+            typedef Right second_argument_type;
+            typedef
+                ublas::matrix<
+                    typename functional::multiplies<
+                        typename Left::value_type
+                      , typename Right::value_type
+                    >::result_type
+                >
+            result_type;
+
+            result_type
+            operator ()(Left & left, Right & right) const
+            {
+                std::size_t left_size = left.size();
+                std::size_t right_size = right.size();
+                result_type result(left_size, right_size);
+                for (std::size_t i = 0; i < left_size; ++i)
+                    for (std::size_t j = 0; j < right_size; ++j)
+                        result(i,j) = numeric::multiplies(left[i], right[j]);
+                return result;
+            }
+        };
+    }
+
+    namespace op
+    {
+        struct outer_product
+          : boost::detail::function2<functional::outer_product<_1, _2, functional::tag<_1>, functional::tag<_2> > >
+        {};
+    }
+
+    namespace
+    {
+        op::outer_product const &outer_product = boost::detail::pod_singleton<op::outer_product>::instance;
+    }
+
+}}
+
+namespace boost { namespace accumulators
+{
+
+namespace impl
+{
+    ///////////////////////////////////////////////////////////////////////////////
+    // covariance_impl
+    //
+    /**
+        @brief Covariance Estimator
+
+        An iterative Monte Carlo estimator for the covariance \f$\mathrm{Cov}(X,X')\f$, where \f$X\f$ is a sample
+        and \f$X'\f$ is a variate, is given by:
+
+        \f[
+            \hat{c}_n = \frac{n-1}{n} \hat{c}_{n-1} + \frac{1}{n-1}(X_n - \hat{\mu}_n)(X_n' - \hat{\mu}_n'),\quad n\ge2,\quad\hat{c}_1 = 0,
+        \f]
+
+        \f$\hat{\mu}_n\f$ and \f$\hat{\mu}_n'\f$ being the means of the samples and variates.
+    */
+    template<typename Sample, typename VariateType, typename VariateTag>
+    struct covariance_impl
+      : accumulator_base
+    {
+        typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type sample_type;
+        typedef typename numeric::functional::fdiv<VariateType, std::size_t>::result_type variate_type;
+        // for boost::result_of
+        typedef typename numeric::functional::outer_product<sample_type, variate_type>::result_type result_type;
+
+        template<typename Args>
+        covariance_impl(Args const &args)
+          : cov_(
+                numeric::outer_product(
+                    numeric::fdiv(args[sample | Sample()], (std::size_t)1)
+                  , numeric::fdiv(args[parameter::keyword<VariateTag>::get() | VariateType()], (std::size_t)1)
+                )
+            )
+        {
+        }
+
+        template<typename Args>
+        void operator ()(Args const &args)
+        {
+            std::size_t cnt = count(args);
+
+            if (cnt > 1)
+            {
+                extractor<tag::mean_of_variates<VariateType, VariateTag> > const some_mean_of_variates = {};
+
+                this->cov_ = this->cov_*(cnt-1.)/cnt
+                           + numeric::outer_product(
+                                 some_mean_of_variates(args) - args[parameter::keyword<VariateTag>::get()]
+                               , mean(args) - args[sample]
+                             ) / (cnt-1.);
+            }
+        }
+
+        result_type result(dont_care) const
+        {
+            return this->cov_;
+        }
+
+        // make this accumulator serializeable
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int file_version)
+        { 
+            ar & cov_;
+        }
+
+    private:
+        result_type cov_;
+    };
+
+} // namespace impl
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::covariance
+//
+namespace tag
+{
+    template<typename VariateType, typename VariateTag>
+    struct covariance
+      : depends_on<count, mean, mean_of_variates<VariateType, VariateTag> >
+    {
+        typedef accumulators::impl::covariance_impl<mpl::_1, VariateType, VariateTag> impl;
+    };
+
+    struct abstract_covariance
+      : depends_on<>
+    {
+    };
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// extract::covariance
+//
+namespace extract
+{
+    extractor<tag::abstract_covariance> const covariance = {};
+
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(covariance)
+}
+
+using extract::covariance;
+
+template<typename VariateType, typename VariateTag>
+struct feature_of<tag::covariance<VariateType, VariateTag> >
+  : feature_of<tag::abstract_covariance>
+{
+};
+
+// So that covariance can be automatically substituted with
+// weighted_covariance when the weight parameter is non-void.
+template<typename VariateType, typename VariateTag>
+struct as_weighted_feature<tag::covariance<VariateType, VariateTag> >
+{
+    typedef tag::weighted_covariance<VariateType, VariateTag> type;
+};
+
+template<typename VariateType, typename VariateTag>
+struct feature_of<tag::weighted_covariance<VariateType, VariateTag> >
+  : feature_of<tag::covariance<VariateType, VariateTag> >
+{};
+
+}} // namespace boost::accumulators
+
+#endif

+ 266 - 0
library/include/boost/accumulators/statistics/density.hpp

@@ -0,0 +1,266 @@
+
+///////////////////////////////////////////////////////////////////////////////
+// density.hpp
+//
+//  Copyright 2006 Daniel Egloff, Olivier Gygi. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_DENSITY_HPP_DE_01_01_2006
+#define BOOST_ACCUMULATORS_STATISTICS_DENSITY_HPP_DE_01_01_2006
+
+#include <vector>
+#include <limits>
+#include <functional>
+#include <boost/range.hpp>
+#include <boost/parameter/keyword.hpp>
+#include <boost/mpl/placeholders.hpp>
+#include <boost/accumulators/accumulators_fwd.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/numeric/functional.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/framework/depends_on.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+#include <boost/accumulators/statistics/count.hpp>
+#include <boost/accumulators/statistics/max.hpp>
+#include <boost/accumulators/statistics/min.hpp>
+#include <boost/serialization/vector.hpp>
+#include <boost/serialization/utility.hpp>
+
+namespace boost { namespace accumulators
+{
+
+///////////////////////////////////////////////////////////////////////////////
+// cache_size and num_bins named parameters
+//
+BOOST_PARAMETER_NESTED_KEYWORD(tag, density_cache_size, cache_size)
+BOOST_PARAMETER_NESTED_KEYWORD(tag, density_num_bins, num_bins)
+
+BOOST_ACCUMULATORS_IGNORE_GLOBAL(density_cache_size)
+BOOST_ACCUMULATORS_IGNORE_GLOBAL(density_num_bins)
+
+namespace impl
+{
+    ///////////////////////////////////////////////////////////////////////////////
+    // density_impl
+    //  density histogram
+    /**
+        @brief Histogram density estimator
+
+        The histogram density estimator returns a histogram of the sample distribution. The positions and sizes of the bins
+        are determined using a specifiable number of cached samples (cache_size). The range between the minimum and the
+        maximum of the cached samples is subdivided into a specifiable number of bins (num_bins) of same size. Additionally,
+        an under- and an overflow bin is added to capture future under- and overflow samples. Once the bins are determined,
+        the cached samples and all subsequent samples are added to the correct bins. At the end, a range of std::pair is
+        return, where each pair contains the position of the bin (lower bound) and the samples count (normalized with the
+        total number of samples).
+
+        @param  density_cache_size Number of first samples used to determine min and max.
+        @param  density_num_bins Number of bins (two additional bins collect under- and overflow samples).
+    */
+    template<typename Sample>
+    struct density_impl
+      : accumulator_base
+    {
+        typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type float_type;
+        typedef std::vector<std::pair<float_type, float_type> > histogram_type;
+        typedef std::vector<float_type> array_type;
+        // for boost::result_of
+        typedef iterator_range<typename histogram_type::iterator> result_type;
+
+        template<typename Args>
+        density_impl(Args const &args)
+            : cache_size(args[density_cache_size])
+            , cache(cache_size)
+            , num_bins(args[density_num_bins])
+            , samples_in_bin(num_bins + 2, 0.)
+            , bin_positions(num_bins + 2)
+            , histogram(
+                num_bins + 2
+              , std::make_pair(
+                    numeric::fdiv(args[sample | Sample()],(std::size_t)1)
+                  , numeric::fdiv(args[sample | Sample()],(std::size_t)1)
+                )
+              )
+            , is_dirty(true)
+        {
+        }
+
+        template<typename Args>
+        void operator ()(Args const &args)
+        {
+            this->is_dirty = true;
+
+            std::size_t cnt = count(args);
+
+            // Fill up cache with cache_size first samples
+            if (cnt <= this->cache_size)
+            {
+                this->cache[cnt - 1] = args[sample];
+            }
+
+            // Once cache_size samples have been accumulated, create num_bins bins of same size between
+            // the minimum and maximum of the cached samples as well as under and overflow bins.
+            // Store their lower bounds (bin_positions) and fill the bins with the cached samples (samples_in_bin).
+            if (cnt == this->cache_size)
+            {
+                float_type minimum = numeric::fdiv((min)(args), (std::size_t)1);
+                float_type maximum = numeric::fdiv((max)(args), (std::size_t)1);
+                float_type bin_size = numeric::fdiv(maximum - minimum, this->num_bins );
+
+                // determine bin positions (their lower bounds)
+                for (std::size_t i = 0; i < this->num_bins + 2; ++i)
+                {
+                    this->bin_positions[i] = minimum + (i - 1.) * bin_size;
+                }
+
+                for (typename array_type::const_iterator iter = this->cache.begin(); iter != this->cache.end(); ++iter)
+                {
+                    if (*iter < this->bin_positions[1])
+                    {
+                        ++(this->samples_in_bin[0]);
+                    }
+                    else if (*iter >= this->bin_positions[this->num_bins + 1])
+                    {
+                        ++(this->samples_in_bin[this->num_bins + 1]);
+                    }
+                    else
+                    {
+                        typename array_type::iterator it = std::upper_bound(
+                            this->bin_positions.begin()
+                          , this->bin_positions.end()
+                          , *iter
+                        );
+
+                        std::size_t d = std::distance(this->bin_positions.begin(), it);
+                        ++(this->samples_in_bin[d - 1]);
+                    }
+                }
+            }
+            // Add each subsequent sample to the correct bin
+            else if (cnt > this->cache_size)
+            {
+                if (args[sample] < this->bin_positions[1])
+                {
+                    ++(this->samples_in_bin[0]);
+                }
+                else if (args[sample] >= this->bin_positions[this->num_bins + 1])
+                {
+                    ++(this->samples_in_bin[this->num_bins + 1]);
+                }
+                else
+                {
+                    typename array_type::iterator it = std::upper_bound(
+                        this->bin_positions.begin()
+                      , this->bin_positions.end()
+                      , args[sample]
+                    );
+
+                    std::size_t d = std::distance(this->bin_positions.begin(), it);
+                    ++(this->samples_in_bin[d - 1]);
+                }
+            }
+        }
+
+        /**
+            @pre The number of samples must meet or exceed the cache size
+        */
+        template<typename Args>
+        result_type result(Args const &args) const
+        {
+            if (this->is_dirty)
+            {
+                this->is_dirty = false;
+
+                // creates a vector of std::pair where each pair i holds
+                // the values bin_positions[i] (x-axis of histogram) and
+                // samples_in_bin[i] / cnt (y-axis of histogram).
+
+                for (std::size_t i = 0; i < this->num_bins + 2; ++i)
+                {
+                    this->histogram[i] = std::make_pair(this->bin_positions[i], numeric::fdiv(this->samples_in_bin[i], count(args)));
+                }
+            }
+            // returns a range of pairs
+            return make_iterator_range(this->histogram);
+        }
+
+        // make this accumulator serializeable
+        // TODO split to save/load and check on parameters provided in ctor
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int file_version)
+        {
+            ar & cache_size;
+            ar & cache;
+            ar & num_bins;
+            ar & samples_in_bin;
+            ar & bin_positions;
+            ar & histogram;
+            ar & is_dirty; 
+        }
+
+    private:
+        std::size_t            cache_size;      // number of cached samples
+        array_type             cache;           // cache to store the first cache_size samples
+        std::size_t            num_bins;        // number of bins
+        array_type             samples_in_bin;  // number of samples in each bin
+        array_type             bin_positions;   // lower bounds of bins
+        mutable histogram_type histogram;       // histogram
+        mutable bool is_dirty;
+    };
+
+} // namespace impl
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::density
+//
+namespace tag
+{
+    struct density
+      : depends_on<count, min, max>
+      , density_cache_size
+      , density_num_bins
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::density_impl<mpl::_1> impl;
+
+        #ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED
+        /// tag::density::cache_size named parameter
+        /// tag::density::num_bins named parameter
+        static boost::parameter::keyword<density_cache_size> const cache_size;
+        static boost::parameter::keyword<density_num_bins> const num_bins;
+        #endif
+    };
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// extract::density
+//
+namespace extract
+{
+    extractor<tag::density> const density = {};
+
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(density)
+}
+
+using extract::density;
+
+// So that density can be automatically substituted
+// with weighted_density when the weight parameter is non-void.
+template<>
+struct as_weighted_feature<tag::density>
+{
+    typedef tag::weighted_density type;
+};
+
+template<>
+struct feature_of<tag::weighted_density>
+  : feature_of<tag::density>
+{
+};
+
+}} // namespace boost::accumulators
+
+#endif

+ 99 - 0
library/include/boost/accumulators/statistics/error_of.hpp

@@ -0,0 +1,99 @@
+///////////////////////////////////////////////////////////////////////////////
+// error_of.hpp
+//
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_ERROR_OF_HPP_EAN_29_11_2005
+#define BOOST_ACCUMULATORS_STATISTICS_ERROR_OF_HPP_EAN_29_11_2005
+
+#include <boost/mpl/placeholders.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/framework/depends_on.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+
+namespace boost { namespace accumulators
+{
+
+namespace impl
+{
+    /// INTERNAL ONLY
+    ///
+    template<typename Feature>
+    struct this_feature_has_no_error_calculation
+      : mpl::false_
+    {
+    };
+
+    ///////////////////////////////////////////////////////////////////////////////
+    // error_of_impl
+    /// INTERNAL ONLY
+    ///
+    template<typename Sample, typename Feature>
+    struct error_of_impl
+      : accumulator_base
+    {
+        // TODO: specialize this on the specific features that have errors we're
+        // interested in.
+        BOOST_MPL_ASSERT((this_feature_has_no_error_calculation<Feature>));
+
+        // for boost::result_of
+        typedef int result_type;
+
+        error_of_impl(dont_care)
+        {
+        }
+
+        result_type result(dont_care) const
+        {
+            return 0;
+        }
+    };
+
+} // namespace impl
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::error_of
+//
+namespace tag
+{
+    template<typename Feature>
+    struct error_of
+      : depends_on<Feature>
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::error_of_impl<mpl::_1, Feature> impl;
+    };
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// extract::error_of
+//
+namespace extract
+{
+    BOOST_ACCUMULATORS_DEFINE_EXTRACTOR(tag, error_of, (typename))
+}
+
+using extract::error_of;
+
+// make tag::error_of<tag::feature(modifier)> work
+template<typename Feature>
+struct as_feature<tag::error_of<Feature> >
+{
+    typedef tag::error_of<typename as_feature<Feature>::type> type;
+};
+
+// make error_of<tag::mean> work with non-void weights (should become
+// error_of<tag::weighted_mean>
+template<typename Feature>
+struct as_weighted_feature<tag::error_of<Feature> >
+{
+    typedef tag::error_of<typename as_weighted_feature<Feature>::type> type;
+};
+
+}} // namespace boost::accumulators
+
+#endif

+ 73 - 0
library/include/boost/accumulators/statistics/error_of_mean.hpp

@@ -0,0 +1,73 @@
+///////////////////////////////////////////////////////////////////////////////
+// error_of.hpp
+//
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_ERROR_OF_MEAN_HPP_EAN_27_03_2006
+#define BOOST_ACCUMULATORS_STATISTICS_ERROR_OF_MEAN_HPP_EAN_27_03_2006
+
+#include <boost/mpl/placeholders.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/framework/depends_on.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+#include <boost/accumulators/statistics/error_of.hpp>
+#include <boost/accumulators/statistics/variance.hpp>
+#include <boost/accumulators/statistics/count.hpp>
+
+namespace boost { namespace accumulators
+{
+
+namespace impl
+{
+    ///////////////////////////////////////////////////////////////////////////////
+    // error_of_mean_impl
+    template<typename Sample, typename Variance>
+    struct error_of_mean_impl
+      : accumulator_base
+    {
+        // for boost::result_of
+        typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type result_type;
+
+        error_of_mean_impl(dont_care) {}
+
+        template<typename Args>
+        result_type result(Args const &args) const
+        {
+            using namespace std;
+            extractor<Variance> const variance = {};
+            return sqrt(numeric::fdiv(variance(args), count(args) - 1));
+        }
+    };
+
+} // namespace impl
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::error_of
+//
+namespace tag
+{
+    template<>
+    struct error_of<mean>
+      : depends_on<lazy_variance, count>
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::error_of_mean_impl<mpl::_1, lazy_variance> impl;
+    };
+
+    template<>
+    struct error_of<immediate_mean>
+      : depends_on<variance, count>
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::error_of_mean_impl<mpl::_1, variance> impl;
+    };
+}
+
+}} // namespace boost::accumulators
+
+#endif

+ 309 - 0
library/include/boost/accumulators/statistics/extended_p_square.hpp

@@ -0,0 +1,309 @@
+///////////////////////////////////////////////////////////////////////////////
+// extended_p_square.hpp
+//
+//  Copyright 2005 Daniel Egloff. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_EXTENDED_SINGLE_HPP_DE_01_01_2006
+#define BOOST_ACCUMULATORS_STATISTICS_EXTENDED_SINGLE_HPP_DE_01_01_2006
+
+#include <vector>
+#include <functional>
+#include <boost/range/begin.hpp>
+#include <boost/range/end.hpp>
+#include <boost/range/iterator_range.hpp>
+#include <boost/iterator/transform_iterator.hpp>
+#include <boost/iterator/counting_iterator.hpp>
+#include <boost/iterator/permutation_iterator.hpp>
+#include <boost/parameter/keyword.hpp>
+#include <boost/mpl/placeholders.hpp>
+#include <boost/accumulators/accumulators_fwd.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/numeric/functional.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/framework/depends_on.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+#include <boost/accumulators/statistics/count.hpp>
+#include <boost/accumulators/statistics/times2_iterator.hpp>
+#include <boost/serialization/vector.hpp>
+
+namespace boost { namespace accumulators
+{
+///////////////////////////////////////////////////////////////////////////////
+// probabilities named parameter
+//
+BOOST_PARAMETER_NESTED_KEYWORD(tag, extended_p_square_probabilities, probabilities)
+
+BOOST_ACCUMULATORS_IGNORE_GLOBAL(extended_p_square_probabilities)
+
+namespace impl
+{
+    ///////////////////////////////////////////////////////////////////////////////
+    // extended_p_square_impl
+    //  multiple quantile estimation
+    /**
+        @brief Multiple quantile estimation with the extended \f$P^2\f$ algorithm
+
+        Extended \f$P^2\f$ algorithm for estimation of several quantiles without storing samples.
+        Assume that \f$m\f$ quantiles \f$\xi_{p_1}, \ldots, \xi_{p_m}\f$ are to be estimated.
+        Instead of storing the whole sample cumulative distribution, the algorithm maintains only
+        \f$m+2\f$ principal markers and \f$m+1\f$ middle markers, whose positions are updated
+        with each sample and whose heights are adjusted (if necessary) using a piecewise-parablic
+        formula. The heights of these central markers are the current estimates of the quantiles
+        and returned as an iterator range.
+
+        For further details, see
+
+        K. E. E. Raatikainen, Simultaneous estimation of several quantiles, Simulation, Volume 49,
+        Number 4 (October), 1986, p. 159-164.
+
+        The extended \f$ P^2 \f$ algorithm generalizes the \f$ P^2 \f$ algorithm of
+
+        R. Jain and I. Chlamtac, The P^2 algorithm for dynamic calculation of quantiles and
+        histograms without storing observations, Communications of the ACM,
+        Volume 28 (October), Number 10, 1985, p. 1076-1085.
+
+        @param extended_p_square_probabilities A vector of quantile probabilities.
+    */
+    template<typename Sample>
+    struct extended_p_square_impl
+      : accumulator_base
+    {
+        typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type float_type;
+        typedef std::vector<float_type> array_type;
+        // for boost::result_of
+        typedef iterator_range<
+            detail::lvalue_index_iterator<
+                permutation_iterator<
+                    typename array_type::const_iterator
+                  , detail::times2_iterator
+                >
+            >
+        > result_type;
+
+        template<typename Args>
+        extended_p_square_impl(Args const &args)
+          : probabilities(
+                boost::begin(args[extended_p_square_probabilities])
+              , boost::end(args[extended_p_square_probabilities])
+            )
+          , heights(2 * probabilities.size() + 3)
+          , actual_positions(heights.size())
+          , desired_positions(heights.size())
+          , positions_increments(heights.size())
+        {
+            std::size_t num_quantiles = this->probabilities.size();
+            std::size_t num_markers = this->heights.size();
+
+            for(std::size_t i = 0; i < num_markers; ++i)
+            {
+                this->actual_positions[i] = i + 1;
+            }
+
+            this->positions_increments[0] = 0.;
+            this->positions_increments[num_markers - 1] = 1.;
+
+            for(std::size_t i = 0; i < num_quantiles; ++i)
+            {
+                this->positions_increments[2 * i + 2] = probabilities[i];
+            }
+
+            for(std::size_t i = 0; i <= num_quantiles; ++i)
+            {
+                this->positions_increments[2 * i + 1] =
+                    0.5 * (this->positions_increments[2 * i] + this->positions_increments[2 * i + 2]);
+            }
+
+            for(std::size_t i = 0; i < num_markers; ++i)
+            {
+                this->desired_positions[i] = 1. + 2. * (num_quantiles + 1.) * this->positions_increments[i];
+            }
+        }
+
+        template<typename Args>
+        void operator ()(Args const &args)
+        {
+            std::size_t cnt = count(args);
+
+            // m+2 principal markers and m+1 middle markers
+            std::size_t num_markers = 2 * this->probabilities.size() + 3;
+
+            // first accumulate num_markers samples
+            if(cnt <= num_markers)
+            {
+                this->heights[cnt - 1] = args[sample];
+
+                // complete the initialization of heights by sorting
+                if(cnt == num_markers)
+                {
+                    std::sort(this->heights.begin(), this->heights.end());
+                }
+            }
+            else
+            {
+                std::size_t sample_cell = 1;
+
+                // find cell k = sample_cell such that heights[k-1] <= sample < heights[k]
+                if(args[sample] < this->heights[0])
+                {
+                    this->heights[0] = args[sample];
+                    sample_cell = 1;
+                }
+                else if(args[sample] >= this->heights[num_markers - 1])
+                {
+                    this->heights[num_markers - 1] = args[sample];
+                    sample_cell = num_markers - 1;
+                }
+                else
+                {
+                    typedef typename array_type::iterator iterator;
+                    iterator it = std::upper_bound(
+                        this->heights.begin()
+                      , this->heights.end()
+                      , args[sample]
+                    );
+
+                    sample_cell = std::distance(this->heights.begin(), it);
+                }
+
+                // update actual positions of all markers above sample_cell index
+                for(std::size_t i = sample_cell; i < num_markers; ++i)
+                {
+                    ++this->actual_positions[i];
+                }
+
+                // update desired positions of all markers
+                for(std::size_t i = 0; i < num_markers; ++i)
+                {
+                    this->desired_positions[i] += this->positions_increments[i];
+                }
+
+                // adjust heights and actual positions of markers 1 to num_markers-2 if necessary
+                for(std::size_t i = 1; i <= num_markers - 2; ++i)
+                {
+                    // offset to desired position
+                    float_type d = this->desired_positions[i] - this->actual_positions[i];
+
+                    // offset to next position
+                    float_type dp = this->actual_positions[i+1] - this->actual_positions[i];
+
+                    // offset to previous position
+                    float_type dm = this->actual_positions[i-1] - this->actual_positions[i];
+
+                    // height ds
+                    float_type hp = (this->heights[i+1] - this->heights[i]) / dp;
+                    float_type hm = (this->heights[i-1] - this->heights[i]) / dm;
+
+                    if((d >= 1 && dp > 1) || (d <= -1 && dm < -1))
+                    {
+                        short sign_d = static_cast<short>(d / std::abs(d));
+
+                        float_type h = this->heights[i] + sign_d / (dp - dm) * ((sign_d - dm)*hp
+                                     + (dp - sign_d) * hm);
+
+                        // try adjusting heights[i] using p-squared formula
+                        if(this->heights[i - 1] < h && h < this->heights[i + 1])
+                        {
+                            this->heights[i] = h;
+                        }
+                        else
+                        {
+                            // use linear formula
+                            if(d > 0)
+                            {
+                                this->heights[i] += hp;
+                            }
+                            if(d < 0)
+                            {
+                                this->heights[i] -= hm;
+                            }
+                        }
+                        this->actual_positions[i] += sign_d;
+                    }
+                }
+            }
+        }
+
+        result_type result(dont_care) const
+        {
+            // for i in [1,probabilities.size()], return heights[i * 2]
+            detail::times2_iterator idx_begin = detail::make_times2_iterator(1);
+            detail::times2_iterator idx_end = detail::make_times2_iterator(this->probabilities.size() + 1);
+
+            return result_type(
+                make_permutation_iterator(this->heights.begin(), idx_begin)
+              , make_permutation_iterator(this->heights.begin(), idx_end)
+            );
+        }
+
+    public:
+        // make this accumulator serializeable
+        // TODO: do we need to split to load/save and verify that the parameters did not change?
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int file_version)
+        { 
+            ar & probabilities;
+            ar & heights;
+            ar & actual_positions;
+            ar & desired_positions;
+            ar & positions_increments;
+        }
+
+    private:
+        array_type probabilities;         // the quantile probabilities
+        array_type heights;               // q_i
+        array_type actual_positions;      // n_i
+        array_type desired_positions;     // d_i
+        array_type positions_increments;  // f_i
+    };
+
+} // namespace impl
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::extended_p_square
+//
+namespace tag
+{
+    struct extended_p_square
+      : depends_on<count>
+      , extended_p_square_probabilities
+    {
+        typedef accumulators::impl::extended_p_square_impl<mpl::_1> impl;
+
+        #ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED
+        /// tag::extended_p_square::probabilities named parameter
+        static boost::parameter::keyword<tag::probabilities> const probabilities;
+        #endif
+    };
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// extract::extended_p_square
+//
+namespace extract
+{
+    extractor<tag::extended_p_square> const extended_p_square = {};
+
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(extended_p_square)
+}
+
+using extract::extended_p_square;
+
+// So that extended_p_square can be automatically substituted with
+// weighted_extended_p_square when the weight parameter is non-void
+template<>
+struct as_weighted_feature<tag::extended_p_square>
+{
+    typedef tag::weighted_extended_p_square type;
+};
+
+template<>
+struct feature_of<tag::weighted_extended_p_square>
+  : feature_of<tag::extended_p_square>
+{
+};
+
+}} // namespace boost::accumulators
+
+#endif

+ 332 - 0
library/include/boost/accumulators/statistics/extended_p_square_quantile.hpp

@@ -0,0 +1,332 @@
+///////////////////////////////////////////////////////////////////////////////
+// extended_p_square_quantile.hpp
+//
+//  Copyright 2005 Daniel Egloff. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_EXTENDED_SINGLE_QUANTILE_HPP_DE_01_01_2006
+#define BOOST_ACCUMULATORS_STATISTICS_EXTENDED_SINGLE_QUANTILE_HPP_DE_01_01_2006
+
+#include <vector>
+#include <functional>
+#include <boost/throw_exception.hpp>
+#include <boost/range/begin.hpp>
+#include <boost/range/end.hpp>
+#include <boost/range/iterator_range.hpp>
+#include <boost/iterator/transform_iterator.hpp>
+#include <boost/iterator/counting_iterator.hpp>
+#include <boost/iterator/permutation_iterator.hpp>
+#include <boost/parameter/keyword.hpp>
+#include <boost/mpl/placeholders.hpp>
+#include <boost/type_traits/is_same.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/numeric/functional.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/framework/depends_on.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+#include <boost/accumulators/statistics/count.hpp>
+#include <boost/accumulators/statistics/parameters/quantile_probability.hpp>
+#include <boost/accumulators/statistics/extended_p_square.hpp>
+#include <boost/accumulators/statistics/weighted_extended_p_square.hpp>
+#include <boost/accumulators/statistics/times2_iterator.hpp>
+
+#ifdef _MSC_VER
+# pragma warning(push)
+# pragma warning(disable: 4127) // conditional expression is constant
+#endif
+
+namespace boost { namespace accumulators
+{
+
+namespace impl
+{
+    ///////////////////////////////////////////////////////////////////////////////
+    // extended_p_square_quantile_impl
+    //  single quantile estimation
+    /**
+        @brief Quantile estimation using the extended \f$P^2\f$ algorithm for weighted and unweighted samples
+
+        Uses the quantile estimates calculated by the extended \f$P^2\f$ algorithm to compute
+        intermediate quantile estimates by means of quadratic interpolation.
+
+        @param quantile_probability The probability of the quantile to be estimated.
+    */
+    template<typename Sample, typename Impl1, typename Impl2> // Impl1: weighted/unweighted // Impl2: linear/quadratic
+    struct extended_p_square_quantile_impl
+      : accumulator_base
+    {
+        typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type float_type;
+        typedef std::vector<float_type> array_type;
+        typedef iterator_range<
+            detail::lvalue_index_iterator<
+                permutation_iterator<
+                    typename array_type::const_iterator
+                  , detail::times2_iterator
+                >
+            >
+        > range_type;
+        // for boost::result_of
+        typedef float_type result_type;
+
+        template<typename Args>
+        extended_p_square_quantile_impl(Args const &args)
+          : probabilities(
+                boost::begin(args[extended_p_square_probabilities])
+              , boost::end(args[extended_p_square_probabilities])
+            )
+          , probability()
+        {
+        }
+
+        template<typename Args>
+        result_type result(Args const &args) const
+        {
+            typedef
+                typename mpl::if_<
+                    is_same<Impl1, weighted>
+                  , tag::weighted_extended_p_square
+                  , tag::extended_p_square
+                >::type
+            extended_p_square_tag;
+
+            extractor<extended_p_square_tag> const some_extended_p_square = {};
+
+            array_type heights(some_extended_p_square(args).size());
+            std::copy(some_extended_p_square(args).begin(), some_extended_p_square(args).end(), heights.begin());
+
+            this->probability = args[quantile_probability];
+
+            typename array_type::const_iterator iter_probs = std::lower_bound(this->probabilities.begin(), this->probabilities.end(), this->probability);
+            std::size_t dist = std::distance(this->probabilities.begin(), iter_probs);
+            typename array_type::const_iterator iter_heights = heights.begin() + dist;
+
+            // If this->probability is not in a valid range return NaN or throw exception
+            if (this->probability < *this->probabilities.begin() || this->probability > *(this->probabilities.end() - 1))
+            {
+                if (std::numeric_limits<result_type>::has_quiet_NaN)
+                {
+                    return std::numeric_limits<result_type>::quiet_NaN();
+                }
+                else
+                {
+                    std::ostringstream msg;
+                    msg << "probability = " << this->probability << " is not in valid range (";
+                    msg << *this->probabilities.begin() << ", " << *(this->probabilities.end() - 1) << ")";
+                    boost::throw_exception(std::runtime_error(msg.str()));
+                    return Sample(0);
+                }
+
+            }
+
+            if (*iter_probs == this->probability)
+            {
+                return heights[dist];
+            }
+            else
+            {
+                result_type res;
+
+                if (is_same<Impl2, linear>::value)
+                {
+                    /////////////////////////////////////////////////////////////////////////////////
+                    // LINEAR INTERPOLATION
+                    //
+                    float_type p1 = *iter_probs;
+                    float_type p0 = *(iter_probs - 1);
+                    float_type h1 = *iter_heights;
+                    float_type h0 = *(iter_heights - 1);
+
+                    float_type a = numeric::fdiv(h1 - h0, p1 - p0);
+                    float_type b = h1 - p1 * a;
+
+                    res = a * this->probability + b;
+                }
+                else
+                {
+                    /////////////////////////////////////////////////////////////////////////////////
+                    // QUADRATIC INTERPOLATION
+                    //
+                    float_type p0, p1, p2;
+                    float_type h0, h1, h2;
+
+                    if ( (dist == 1 || *iter_probs - this->probability <= this->probability - *(iter_probs - 1) ) && dist != this->probabilities.size() - 1 )
+                    {
+                        p0 = *(iter_probs - 1);
+                        p1 = *iter_probs;
+                        p2 = *(iter_probs + 1);
+                        h0 = *(iter_heights - 1);
+                        h1 = *iter_heights;
+                        h2 = *(iter_heights + 1);
+                    }
+                    else
+                    {
+                        p0 = *(iter_probs - 2);
+                        p1 = *(iter_probs - 1);
+                        p2 = *iter_probs;
+                        h0 = *(iter_heights - 2);
+                        h1 = *(iter_heights - 1);
+                        h2 = *iter_heights;
+                    }
+
+                    float_type hp21 = numeric::fdiv(h2 - h1, p2 - p1);
+                    float_type hp10 = numeric::fdiv(h1 - h0, p1 - p0);
+                    float_type p21  = numeric::fdiv(p2 * p2 - p1 * p1, p2 - p1);
+                    float_type p10  = numeric::fdiv(p1 * p1 - p0 * p0, p1 - p0);
+
+                    float_type a = numeric::fdiv(hp21 - hp10, p21 - p10);
+                    float_type b = hp21 - a * p21;
+                    float_type c = h2 - a * p2 * p2 - b * p2;
+
+                    res = a * this->probability * this-> probability + b * this->probability + c;
+                }
+
+                return res;
+            }
+
+        }
+
+    public:
+        // make this accumulator serializeable
+        // TODO: do we need to split to load/save and verify that the parameters did not change?
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int file_version)
+        { 
+            ar & probabilities;
+            ar & probability;
+        }
+
+    private:
+
+        array_type probabilities;
+        mutable float_type probability;
+
+    };
+
+} // namespace impl
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::extended_p_square_quantile
+//
+namespace tag
+{
+    struct extended_p_square_quantile
+      : depends_on<extended_p_square>
+    {
+        typedef accumulators::impl::extended_p_square_quantile_impl<mpl::_1, unweighted, linear> impl;
+    };
+    struct extended_p_square_quantile_quadratic
+      : depends_on<extended_p_square>
+    {
+        typedef accumulators::impl::extended_p_square_quantile_impl<mpl::_1, unweighted, quadratic> impl;
+    };
+    struct weighted_extended_p_square_quantile
+      : depends_on<weighted_extended_p_square>
+    {
+        typedef accumulators::impl::extended_p_square_quantile_impl<mpl::_1, weighted, linear> impl;
+    };
+    struct weighted_extended_p_square_quantile_quadratic
+      : depends_on<weighted_extended_p_square>
+    {
+        typedef accumulators::impl::extended_p_square_quantile_impl<mpl::_1, weighted, quadratic> impl;
+    };
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// extract::extended_p_square_quantile
+// extract::weighted_extended_p_square_quantile
+//
+namespace extract
+{
+    extractor<tag::extended_p_square_quantile> const extended_p_square_quantile = {};
+    extractor<tag::extended_p_square_quantile_quadratic> const extended_p_square_quantile_quadratic = {};
+    extractor<tag::weighted_extended_p_square_quantile> const weighted_extended_p_square_quantile = {};
+    extractor<tag::weighted_extended_p_square_quantile_quadratic> const weighted_extended_p_square_quantile_quadratic = {};
+
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(extended_p_square_quantile)
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(extended_p_square_quantile_quadratic)
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(weighted_extended_p_square_quantile)
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(weighted_extended_p_square_quantile_quadratic)
+}
+
+using extract::extended_p_square_quantile;
+using extract::extended_p_square_quantile_quadratic;
+using extract::weighted_extended_p_square_quantile;
+using extract::weighted_extended_p_square_quantile_quadratic;
+
+// extended_p_square_quantile(linear) -> extended_p_square_quantile
+template<>
+struct as_feature<tag::extended_p_square_quantile(linear)>
+{
+    typedef tag::extended_p_square_quantile type;
+};
+
+// extended_p_square_quantile(quadratic) -> extended_p_square_quantile_quadratic
+template<>
+struct as_feature<tag::extended_p_square_quantile(quadratic)>
+{
+    typedef tag::extended_p_square_quantile_quadratic type;
+};
+
+// weighted_extended_p_square_quantile(linear) -> weighted_extended_p_square_quantile
+template<>
+struct as_feature<tag::weighted_extended_p_square_quantile(linear)>
+{
+    typedef tag::weighted_extended_p_square_quantile type;
+};
+
+// weighted_extended_p_square_quantile(quadratic) -> weighted_extended_p_square_quantile_quadratic
+template<>
+struct as_feature<tag::weighted_extended_p_square_quantile(quadratic)>
+{
+    typedef tag::weighted_extended_p_square_quantile_quadratic type;
+};
+
+// for the purposes of feature-based dependency resolution,
+// extended_p_square_quantile and weighted_extended_p_square_quantile
+// provide the same feature as quantile
+template<>
+struct feature_of<tag::extended_p_square_quantile>
+  : feature_of<tag::quantile>
+{
+};
+template<>
+struct feature_of<tag::extended_p_square_quantile_quadratic>
+  : feature_of<tag::quantile>
+{
+};
+// So that extended_p_square_quantile can be automatically substituted with
+// weighted_extended_p_square_quantile when the weight parameter is non-void
+template<>
+struct as_weighted_feature<tag::extended_p_square_quantile>
+{
+    typedef tag::weighted_extended_p_square_quantile type;
+};
+
+template<>
+struct feature_of<tag::weighted_extended_p_square_quantile>
+  : feature_of<tag::extended_p_square_quantile>
+{
+};
+
+// So that extended_p_square_quantile_quadratic can be automatically substituted with
+// weighted_extended_p_square_quantile_quadratic when the weight parameter is non-void
+template<>
+struct as_weighted_feature<tag::extended_p_square_quantile_quadratic>
+{
+    typedef tag::weighted_extended_p_square_quantile_quadratic type;
+};
+template<>
+struct feature_of<tag::weighted_extended_p_square_quantile_quadratic>
+  : feature_of<tag::extended_p_square_quantile_quadratic>
+{
+};
+
+}} // namespace boost::accumulators
+
+#ifdef _MSC_VER
+# pragma warning(pop)
+#endif
+
+#endif

+ 116 - 0
library/include/boost/accumulators/statistics/kurtosis.hpp

@@ -0,0 +1,116 @@
+///////////////////////////////////////////////////////////////////////////////
+// kurtosis.hpp
+//
+//  Copyright 2006 Olivier Gygi, Daniel Egloff. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_KURTOSIS_HPP_EAN_28_10_2005
+#define BOOST_ACCUMULATORS_STATISTICS_KURTOSIS_HPP_EAN_28_10_2005
+
+#include <limits>
+#include <boost/mpl/placeholders.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/numeric/functional.hpp>
+#include <boost/accumulators/framework/depends_on.hpp>
+#include <boost/accumulators/statistics/mean.hpp>
+#include <boost/accumulators/statistics/moment.hpp>
+
+namespace boost { namespace accumulators
+{
+
+namespace impl
+{
+    ///////////////////////////////////////////////////////////////////////////////
+    // kurtosis_impl
+    /**
+        @brief Kurtosis estimation
+
+        The kurtosis of a sample distribution is defined as the ratio of the 4th central moment and the square of the 2nd central
+        moment (the variance) of the samples, minus 3. The term \f$ -3 \f$ is added in order to ensure that the normal distribution
+        has zero kurtosis. The kurtosis can also be expressed by the simple moments:
+
+        \f[
+            \hat{g}_2 =
+                \frac
+                {\widehat{m}_n^{(4)}-4\widehat{m}_n^{(3)}\hat{\mu}_n+6\widehat{m}_n^{(2)}\hat{\mu}_n^2-3\hat{\mu}_n^4}
+                {\left(\widehat{m}_n^{(2)} - \hat{\mu}_n^{2}\right)^2} - 3,
+        \f]
+
+        where \f$ \widehat{m}_n^{(i)} \f$ are the \f$ i \f$-th moment and \f$ \hat{\mu}_n \f$ the mean (first moment) of the
+        \f$ n \f$ samples.
+    */
+    template<typename Sample>
+    struct kurtosis_impl
+      : accumulator_base
+    {
+        // for boost::result_of
+        typedef typename numeric::functional::fdiv<Sample, Sample>::result_type result_type;
+
+        kurtosis_impl(dont_care) {}
+
+        template<typename Args>
+        result_type result(Args const &args) const
+        {
+            return numeric::fdiv(
+                        accumulators::moment<4>(args)
+                        - 4. * accumulators::moment<3>(args) * mean(args)
+                        + 6. * accumulators::moment<2>(args) * mean(args) * mean(args)
+                        - 3. * mean(args) * mean(args) * mean(args) * mean(args)
+                      , ( accumulators::moment<2>(args) - mean(args) * mean(args) )
+                        * ( accumulators::moment<2>(args) - mean(args) * mean(args) )
+                    ) - 3.;
+        }
+        
+        // serialization is done by accumulators it depends on
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int file_version) {}
+    };
+
+} // namespace impl
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::kurtosis
+//
+namespace tag
+{
+    struct kurtosis
+      : depends_on<mean, moment<2>, moment<3>, moment<4> >
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::kurtosis_impl<mpl::_1> impl;
+    };
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// extract::kurtosis
+//
+namespace extract
+{
+    extractor<tag::kurtosis> const kurtosis = {};
+
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(kurtosis)
+}
+
+using extract::kurtosis;
+
+// So that kurtosis can be automatically substituted with
+// weighted_kurtosis when the weight parameter is non-void
+template<>
+struct as_weighted_feature<tag::kurtosis>
+{
+    typedef tag::weighted_kurtosis type;
+};
+
+template<>
+struct feature_of<tag::weighted_kurtosis>
+  : feature_of<tag::kurtosis>
+{
+};
+
+}} // namespace boost::accumulators
+
+#endif

+ 92 - 0
library/include/boost/accumulators/statistics/max.hpp

@@ -0,0 +1,92 @@
+///////////////////////////////////////////////////////////////////////////////
+// max.hpp
+//
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_MAX_HPP_EAN_28_10_2005
+#define BOOST_ACCUMULATORS_STATISTICS_MAX_HPP_EAN_28_10_2005
+
+#include <limits>
+#include <boost/mpl/placeholders.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/numeric/functional.hpp>
+#include <boost/accumulators/framework/depends_on.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+
+namespace boost { namespace accumulators
+{
+
+namespace impl
+{
+    ///////////////////////////////////////////////////////////////////////////////
+    // max_impl
+    template<typename Sample>
+    struct max_impl
+      : accumulator_base
+    {
+        // for boost::result_of
+        typedef Sample result_type;
+
+        template<typename Args>
+        max_impl(Args const &args)
+          : max_(numeric::as_min(args[sample | Sample()]))
+        {
+        }
+
+        template<typename Args>
+        void operator ()(Args const &args)
+        {
+            numeric::max_assign(this->max_, args[sample]);
+        }
+
+        result_type result(dont_care) const
+        {
+            return this->max_;
+        }
+
+        // make this accumulator serializeable
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int /* file_version */)
+        {
+            ar & max_;
+        }
+
+    private:
+        Sample max_;
+    };
+
+} // namespace impl
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::max
+//
+namespace tag
+{
+    struct max
+      : depends_on<>
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::max_impl<mpl::_1> impl;
+    };
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// extract::max
+//
+namespace extract
+{
+    extractor<tag::max> const max = {};
+
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(max)
+}
+
+using extract::max;
+
+}} // namespace boost::accumulators
+
+#endif

+ 308 - 0
library/include/boost/accumulators/statistics/mean.hpp

@@ -0,0 +1,308 @@
+///////////////////////////////////////////////////////////////////////////////
+// mean.hpp
+//
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_MEAN_HPP_EAN_28_10_2005
+#define BOOST_ACCUMULATORS_STATISTICS_MEAN_HPP_EAN_28_10_2005
+
+#include <boost/mpl/placeholders.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/numeric/functional.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/framework/depends_on.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+#include <boost/accumulators/statistics/count.hpp>
+#include <boost/accumulators/statistics/sum.hpp>
+
+namespace boost { namespace accumulators
+{
+
+namespace impl
+{
+    ///////////////////////////////////////////////////////////////////////////////
+    // mean_impl
+    //      lazy, by default
+    template<typename Sample, typename SumFeature>
+    struct mean_impl
+      : accumulator_base
+    {
+        // for boost::result_of
+        typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type result_type;
+
+        mean_impl(dont_care) {}
+
+        template<typename Args>
+        result_type result(Args const &args) const
+        {
+            extractor<SumFeature> sum;
+            return numeric::fdiv(sum(args), count(args));
+        }
+
+        // serialization is done by accumulators it depends on
+        template<class Archive>
+        void serialize(Archive & /* ar */, const unsigned int /* file_version */) {}
+    };
+
+    template<typename Sample, typename Tag>
+    struct immediate_mean_impl
+      : accumulator_base
+    {
+        // for boost::result_of
+        typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type result_type;
+
+        template<typename Args>
+        immediate_mean_impl(Args const &args)
+          : mean(numeric::fdiv(args[sample | Sample()], numeric::one<std::size_t>::value))
+        {
+        }
+
+        template<typename Args>
+        void operator ()(Args const &args)
+        {
+            std::size_t cnt = count(args);
+            this->mean = numeric::fdiv(
+                (this->mean * (cnt - 1)) + args[parameter::keyword<Tag>::get()]
+              , cnt
+            );
+        }
+
+        result_type result(dont_care) const
+        {
+            return this->mean;
+        }
+
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int /* file_version */)
+        {
+            ar & mean;
+        }
+
+    private:
+        result_type mean;
+    };
+
+} // namespace impl
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::mean
+// tag::immediate_mean
+// tag::mean_of_weights
+// tag::immediate_mean_of_weights
+// tag::mean_of_variates
+// tag::immediate_mean_of_variates
+//
+namespace tag
+{
+    struct mean
+      : depends_on<count, sum>
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::mean_impl<mpl::_1, sum> impl;
+    };
+    struct immediate_mean
+      : depends_on<count>
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::immediate_mean_impl<mpl::_1, tag::sample> impl;
+    };
+    struct mean_of_weights
+      : depends_on<count, sum_of_weights>
+    {
+        typedef mpl::true_ is_weight_accumulator;
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::mean_impl<mpl::_2, sum_of_weights> impl;
+    };
+    struct immediate_mean_of_weights
+      : depends_on<count>
+    {
+        typedef mpl::true_ is_weight_accumulator;
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::immediate_mean_impl<mpl::_2, tag::weight> impl;
+    };
+    template<typename VariateType, typename VariateTag>
+    struct mean_of_variates
+      : depends_on<count, sum_of_variates<VariateType, VariateTag> >
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef mpl::always<accumulators::impl::mean_impl<VariateType, sum_of_variates<VariateType, VariateTag> > > impl;
+    };
+    template<typename VariateType, typename VariateTag>
+    struct immediate_mean_of_variates
+      : depends_on<count>
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef mpl::always<accumulators::impl::immediate_mean_impl<VariateType, VariateTag> > impl;
+    };
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// extract::mean
+// extract::mean_of_weights
+// extract::mean_of_variates
+//
+namespace extract
+{
+    extractor<tag::mean> const mean = {};
+    extractor<tag::mean_of_weights> const mean_of_weights = {};
+    BOOST_ACCUMULATORS_DEFINE_EXTRACTOR(tag, mean_of_variates, (typename)(typename))
+
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(mean)
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(mean_of_weights)
+}
+
+using extract::mean;
+using extract::mean_of_weights;
+using extract::mean_of_variates;
+
+// mean(lazy) -> mean
+template<>
+struct as_feature<tag::mean(lazy)>
+{
+    typedef tag::mean type;
+};
+
+// mean(immediate) -> immediate_mean
+template<>
+struct as_feature<tag::mean(immediate)>
+{
+    typedef tag::immediate_mean type;
+};
+
+// mean_of_weights(lazy) -> mean_of_weights
+template<>
+struct as_feature<tag::mean_of_weights(lazy)>
+{
+    typedef tag::mean_of_weights type;
+};
+
+// mean_of_weights(immediate) -> immediate_mean_of_weights
+template<>
+struct as_feature<tag::mean_of_weights(immediate)>
+{
+    typedef tag::immediate_mean_of_weights type;
+};
+
+// mean_of_variates<VariateType, VariateTag>(lazy) -> mean_of_variates<VariateType, VariateTag>
+template<typename VariateType, typename VariateTag>
+struct as_feature<tag::mean_of_variates<VariateType, VariateTag>(lazy)>
+{
+    typedef tag::mean_of_variates<VariateType, VariateTag> type;
+};
+
+// mean_of_variates<VariateType, VariateTag>(immediate) -> immediate_mean_of_variates<VariateType, VariateTag>
+template<typename VariateType, typename VariateTag>
+struct as_feature<tag::mean_of_variates<VariateType, VariateTag>(immediate)>
+{
+    typedef tag::immediate_mean_of_variates<VariateType, VariateTag> type;
+};
+
+// for the purposes of feature-based dependency resolution,
+// immediate_mean provides the same feature as mean
+template<>
+struct feature_of<tag::immediate_mean>
+  : feature_of<tag::mean>
+{
+};
+
+// for the purposes of feature-based dependency resolution,
+// immediate_mean provides the same feature as mean
+template<>
+struct feature_of<tag::immediate_mean_of_weights>
+  : feature_of<tag::mean_of_weights>
+{
+};
+
+// for the purposes of feature-based dependency resolution,
+// immediate_mean provides the same feature as mean
+template<typename VariateType, typename VariateTag>
+struct feature_of<tag::immediate_mean_of_variates<VariateType, VariateTag> >
+  : feature_of<tag::mean_of_variates<VariateType, VariateTag> >
+{
+};
+
+// So that mean can be automatically substituted with
+// weighted_mean when the weight parameter is non-void.
+template<>
+struct as_weighted_feature<tag::mean>
+{
+    typedef tag::weighted_mean type;
+};
+
+template<>
+struct feature_of<tag::weighted_mean>
+  : feature_of<tag::mean>
+{};
+
+// So that immediate_mean can be automatically substituted with
+// immediate_weighted_mean when the weight parameter is non-void.
+template<>
+struct as_weighted_feature<tag::immediate_mean>
+{
+    typedef tag::immediate_weighted_mean type;
+};
+
+template<>
+struct feature_of<tag::immediate_weighted_mean>
+  : feature_of<tag::immediate_mean>
+{};
+
+// So that mean_of_weights<> can be automatically substituted with
+// weighted_mean_of_variates<> when the weight parameter is non-void.
+template<typename VariateType, typename VariateTag>
+struct as_weighted_feature<tag::mean_of_variates<VariateType, VariateTag> >
+{
+    typedef tag::weighted_mean_of_variates<VariateType, VariateTag> type;
+};
+
+template<typename VariateType, typename VariateTag>
+struct feature_of<tag::weighted_mean_of_variates<VariateType, VariateTag> >
+  : feature_of<tag::mean_of_variates<VariateType, VariateTag> >
+{
+};
+
+// So that immediate_mean_of_weights<> can be automatically substituted with
+// immediate_weighted_mean_of_variates<> when the weight parameter is non-void.
+template<typename VariateType, typename VariateTag>
+struct as_weighted_feature<tag::immediate_mean_of_variates<VariateType, VariateTag> >
+{
+    typedef tag::immediate_weighted_mean_of_variates<VariateType, VariateTag> type;
+};
+
+template<typename VariateType, typename VariateTag>
+struct feature_of<tag::immediate_weighted_mean_of_variates<VariateType, VariateTag> >
+  : feature_of<tag::immediate_mean_of_variates<VariateType, VariateTag> >
+{
+};
+
+////////////////////////////////////////////////////////////////////////////
+//// droppable_accumulator<mean_impl>
+////  need to specialize droppable lazy mean to cache the result at the
+////  point the accumulator is dropped.
+///// INTERNAL ONLY
+/////
+//template<typename Sample, typename SumFeature>
+//struct droppable_accumulator<impl::mean_impl<Sample, SumFeature> >
+//  : droppable_accumulator_base<
+//        with_cached_result<impl::mean_impl<Sample, SumFeature> >
+//    >
+//{
+//    template<typename Args>
+//    droppable_accumulator(Args const &args)
+//      : droppable_accumulator::base(args)
+//    {
+//    }
+//};
+
+}} // namespace boost::accumulators
+
+#endif

+ 324 - 0
library/include/boost/accumulators/statistics/median.hpp

@@ -0,0 +1,324 @@
+///////////////////////////////////////////////////////////////////////////////
+// median.hpp
+//
+//  Copyright 2006 Eric Niebler, Olivier Gygi. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_MEDIAN_HPP_EAN_28_10_2005
+#define BOOST_ACCUMULATORS_STATISTICS_MEDIAN_HPP_EAN_28_10_2005
+
+#include <boost/mpl/placeholders.hpp>
+#include <boost/range/iterator_range.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/numeric/functional.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/framework/depends_on.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+#include <boost/accumulators/statistics/count.hpp>
+#include <boost/accumulators/statistics/p_square_quantile.hpp>
+#include <boost/accumulators/statistics/density.hpp>
+#include <boost/accumulators/statistics/p_square_cumul_dist.hpp>
+
+namespace boost { namespace accumulators
+{
+
+namespace impl
+{
+    ///////////////////////////////////////////////////////////////////////////////
+    // median_impl
+    //
+    /**
+        @brief Median estimation based on the \f$P^2\f$ quantile estimator
+
+        The \f$P^2\f$ algorithm is invoked with a quantile probability of 0.5.
+    */
+    template<typename Sample>
+    struct median_impl
+      : accumulator_base
+    {
+        // for boost::result_of
+        typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type result_type;
+
+        median_impl(dont_care) {}
+
+        template<typename Args>
+        result_type result(Args const &args) const
+        {
+            return p_square_quantile_for_median(args);
+        }
+        
+        // serialization is done by accumulators it depends on
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int file_version) {}
+    };
+    ///////////////////////////////////////////////////////////////////////////////
+    // with_density_median_impl
+    //
+    /**
+        @brief Median estimation based on the density estimator
+
+        The algorithm determines the bin in which the \f$0.5*cnt\f$-th sample lies, \f$cnt\f$ being
+        the total number of samples. It returns the approximate horizontal position of this sample,
+        based on a linear interpolation inside the bin.
+    */
+    template<typename Sample>
+    struct with_density_median_impl
+      : accumulator_base
+    {
+        typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type float_type;
+        typedef std::vector<std::pair<float_type, float_type> > histogram_type;
+        typedef iterator_range<typename histogram_type::iterator> range_type;
+        // for boost::result_of
+        typedef float_type result_type;
+
+        template<typename Args>
+        with_density_median_impl(Args const &args)
+          : sum(numeric::fdiv(args[sample | Sample()], (std::size_t)1))
+          , is_dirty(true)
+        {
+        }
+
+        void operator ()(dont_care)
+        {
+            this->is_dirty = true;
+        }
+
+
+        template<typename Args>
+        result_type result(Args const &args) const
+        {
+            if (this->is_dirty)
+            {
+                this->is_dirty = false;
+
+                std::size_t cnt = count(args);
+                range_type histogram = density(args);
+                typename range_type::iterator it = histogram.begin();
+                while (this->sum < 0.5 * cnt)
+                {
+                    this->sum += it->second * cnt;
+                    ++it;
+                }
+                --it;
+                float_type over = numeric::fdiv(this->sum - 0.5 * cnt, it->second * cnt);
+                this->median = it->first * over + (it + 1)->first * (1. - over);
+            }
+
+            return this->median;
+        }
+
+        // make this accumulator serializeable
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int file_version)
+        { 
+            ar & sum;
+            ar & is_dirty;
+            ar & median;
+        }
+
+
+    private:
+        mutable float_type sum;
+        mutable bool is_dirty;
+        mutable float_type median;
+    };
+
+    ///////////////////////////////////////////////////////////////////////////////
+    // with_p_square_cumulative_distribution_median_impl
+    //
+    /**
+        @brief Median estimation based on the \f$P^2\f$ cumulative distribution estimator
+
+        The algorithm determines the first (leftmost) bin with a height exceeding 0.5. It
+        returns the approximate horizontal position of where the cumulative distribution
+        equals 0.5, based on a linear interpolation inside the bin.
+    */
+    template<typename Sample>
+    struct with_p_square_cumulative_distribution_median_impl
+      : accumulator_base
+    {
+        typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type float_type;
+        typedef std::vector<std::pair<float_type, float_type> > histogram_type;
+        typedef iterator_range<typename histogram_type::iterator> range_type;
+        // for boost::result_of
+        typedef float_type result_type;
+
+        with_p_square_cumulative_distribution_median_impl(dont_care)
+          : is_dirty(true)
+        {
+        }
+
+        void operator ()(dont_care)
+        {
+            this->is_dirty = true;
+        }
+
+        template<typename Args>
+        result_type result(Args const &args) const
+        {
+            if (this->is_dirty)
+            {
+                this->is_dirty = false;
+
+                range_type histogram = p_square_cumulative_distribution(args);
+                typename range_type::iterator it = histogram.begin();
+                while (it->second < 0.5)
+                {
+                    ++it;
+                }
+                float_type over = numeric::fdiv(it->second - 0.5, it->second - (it - 1)->second);
+                this->median = it->first * over + (it + 1)->first * ( 1. - over );
+            }
+
+            return this->median;
+        }
+        
+        // make this accumulator serializeable
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int file_version)
+        { 
+            ar & is_dirty;
+            ar & median;
+        }
+
+    private:
+
+        mutable bool is_dirty;
+        mutable float_type median;
+    };
+
+} // namespace impl
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::median
+// tag::with_densisty_median
+// tag::with_p_square_cumulative_distribution_median
+//
+namespace tag
+{
+    struct median
+      : depends_on<p_square_quantile_for_median>
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::median_impl<mpl::_1> impl;
+    };
+    struct with_density_median
+      : depends_on<count, density>
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::with_density_median_impl<mpl::_1> impl;
+    };
+    struct with_p_square_cumulative_distribution_median
+      : depends_on<p_square_cumulative_distribution>
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::with_p_square_cumulative_distribution_median_impl<mpl::_1> impl;
+    };
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// extract::median
+// extract::with_density_median
+// extract::with_p_square_cumulative_distribution_median
+//
+namespace extract
+{
+    extractor<tag::median> const median = {};
+    extractor<tag::with_density_median> const with_density_median = {};
+    extractor<tag::with_p_square_cumulative_distribution_median> const with_p_square_cumulative_distribution_median = {};
+
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(median)
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(with_density_median)
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(with_p_square_cumulative_distribution_median)
+}
+
+using extract::median;
+using extract::with_density_median;
+using extract::with_p_square_cumulative_distribution_median;
+
+// median(with_p_square_quantile) -> median
+template<>
+struct as_feature<tag::median(with_p_square_quantile)>
+{
+    typedef tag::median type;
+};
+
+// median(with_density) -> with_density_median
+template<>
+struct as_feature<tag::median(with_density)>
+{
+    typedef tag::with_density_median type;
+};
+
+// median(with_p_square_cumulative_distribution) -> with_p_square_cumulative_distribution_median
+template<>
+struct as_feature<tag::median(with_p_square_cumulative_distribution)>
+{
+    typedef tag::with_p_square_cumulative_distribution_median type;
+};
+
+// for the purposes of feature-based dependency resolution,
+// with_density_median and with_p_square_cumulative_distribution_median
+// provide the same feature as median
+template<>
+struct feature_of<tag::with_density_median>
+  : feature_of<tag::median>
+{
+};
+
+template<>
+struct feature_of<tag::with_p_square_cumulative_distribution_median>
+  : feature_of<tag::median>
+{
+};
+
+// So that median can be automatically substituted with
+// weighted_median when the weight parameter is non-void.
+template<>
+struct as_weighted_feature<tag::median>
+{
+    typedef tag::weighted_median type;
+};
+
+template<>
+struct feature_of<tag::weighted_median>
+  : feature_of<tag::median>
+{
+};
+
+// So that with_density_median can be automatically substituted with
+// with_density_weighted_median when the weight parameter is non-void.
+template<>
+struct as_weighted_feature<tag::with_density_median>
+{
+    typedef tag::with_density_weighted_median type;
+};
+
+template<>
+struct feature_of<tag::with_density_weighted_median>
+  : feature_of<tag::with_density_median>
+{
+};
+
+// So that with_p_square_cumulative_distribution_median can be automatically substituted with
+// with_p_square_cumulative_distribution_weighted_median when the weight parameter is non-void.
+template<>
+struct as_weighted_feature<tag::with_p_square_cumulative_distribution_median>
+{
+    typedef tag::with_p_square_cumulative_distribution_weighted_median type;
+};
+
+template<>
+struct feature_of<tag::with_p_square_cumulative_distribution_weighted_median>
+  : feature_of<tag::with_p_square_cumulative_distribution_median>
+{
+};
+
+}} // namespace boost::accumulators
+
+#endif

+ 92 - 0
library/include/boost/accumulators/statistics/min.hpp

@@ -0,0 +1,92 @@
+///////////////////////////////////////////////////////////////////////////////
+// min.hpp
+//
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_MIN_HPP_EAN_28_10_2005
+#define BOOST_ACCUMULATORS_STATISTICS_MIN_HPP_EAN_28_10_2005
+
+#include <limits>
+#include <boost/mpl/placeholders.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/numeric/functional.hpp>
+#include <boost/accumulators/framework/depends_on.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+
+namespace boost { namespace accumulators
+{
+
+namespace impl
+{
+    ///////////////////////////////////////////////////////////////////////////////
+    // min_impl
+    template<typename Sample>
+    struct min_impl
+      : accumulator_base
+    {
+        // for boost::result_of
+        typedef Sample result_type;
+
+        template<typename Args>
+        min_impl(Args const &args)
+          : min_(numeric::as_max(args[sample | Sample()]))
+        {
+        }
+
+        template<typename Args>
+        void operator ()(Args const &args)
+        {
+            numeric::min_assign(this->min_, args[sample]);
+        }
+
+        result_type result(dont_care) const
+        {
+            return this->min_;
+        }
+
+        // make this accumulator serializeable
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int /* file_version */)
+        {
+            ar & min_;
+        }
+
+    private:
+        Sample min_;
+    };
+
+} // namespace impl
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::min
+//
+namespace tag
+{
+    struct min
+      : depends_on<>
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::min_impl<mpl::_1> impl;
+    };
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// extract::min
+//
+namespace extract
+{
+    extractor<tag::min> const min = {};
+
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(min)
+}
+
+using extract::min;
+
+}} // namespace boost::accumulators
+
+#endif

+ 132 - 0
library/include/boost/accumulators/statistics/moment.hpp

@@ -0,0 +1,132 @@
+///////////////////////////////////////////////////////////////////////////////
+// moment.hpp
+//
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_MOMENT_HPP_EAN_15_11_2005
+#define BOOST_ACCUMULATORS_STATISTICS_MOMENT_HPP_EAN_15_11_2005
+
+#include <boost/config/no_tr1/cmath.hpp>
+#include <boost/mpl/int.hpp>
+#include <boost/mpl/assert.hpp>
+#include <boost/mpl/placeholders.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/numeric/functional.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/framework/depends_on.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+#include <boost/accumulators/statistics/count.hpp>
+
+namespace boost { namespace numeric
+{
+    /// INTERNAL ONLY
+    ///
+    template<typename T>
+    T const &pow(T const &x, mpl::int_<1>)
+    {
+        return x;
+    }
+
+    /// INTERNAL ONLY
+    ///
+    template<typename T, int N>
+    T pow(T const &x, mpl::int_<N>)
+    {
+        using namespace operators;
+        T y = numeric::pow(x, mpl::int_<N/2>());
+        T z = y * y;
+        return (N % 2) ? (z * x) : z;
+    }
+}}
+
+namespace boost { namespace accumulators
+{
+
+namespace impl
+{
+    ///////////////////////////////////////////////////////////////////////////////
+    // moment_impl
+    template<typename N, typename Sample>
+    struct moment_impl
+      : accumulator_base // TODO: also depends_on sum of powers
+    {
+        BOOST_MPL_ASSERT_RELATION(N::value, >, 0);
+        // for boost::result_of
+        typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type result_type;
+
+        template<typename Args>
+        moment_impl(Args const &args)
+          : sum(args[sample | Sample()])
+        {
+        }
+
+        template<typename Args>
+        void operator ()(Args const &args)
+        {
+            this->sum += numeric::pow(args[sample], N());
+        }
+
+        template<typename Args>
+        result_type result(Args const &args) const
+        {
+            return numeric::fdiv(this->sum, count(args));
+        }
+
+        // make this accumulator serializeable
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int /* file_version */)
+        {
+            ar & sum;
+        }
+
+    private:
+        Sample sum;
+    };
+
+} // namespace impl
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::moment
+//
+namespace tag
+{
+    template<int N>
+    struct moment
+      : depends_on<count>
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::moment_impl<mpl::int_<N>, mpl::_1> impl;
+    };
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// extract::moment
+//
+namespace extract
+{
+    BOOST_ACCUMULATORS_DEFINE_EXTRACTOR(tag, moment, (int))
+}
+
+using extract::moment;
+
+// So that moment<N> can be automatically substituted with
+// weighted_moment<N> when the weight parameter is non-void
+template<int N>
+struct as_weighted_feature<tag::moment<N> >
+{
+    typedef tag::weighted_moment<N> type;
+};
+
+template<int N>
+struct feature_of<tag::weighted_moment<N> >
+  : feature_of<tag::moment<N> >
+{
+};
+
+}} // namespace boost::accumulators
+
+#endif

+ 279 - 0
library/include/boost/accumulators/statistics/p_square_cumul_dist.hpp

@@ -0,0 +1,279 @@
+///////////////////////////////////////////////////////////////////////////////
+// p_square_cumulative_distribution.hpp
+//
+//  Copyright 2005 Daniel Egloff, Olivier Gygi. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_P_SQUARE_CUMUL_DIST_HPP_DE_01_01_2006
+#define BOOST_ACCUMULATORS_STATISTICS_P_SQUARE_CUMUL_DIST_HPP_DE_01_01_2006
+
+#include <vector>
+#include <functional>
+#include <boost/parameter/keyword.hpp>
+#include <boost/range.hpp>
+#include <boost/mpl/placeholders.hpp>
+#include <boost/accumulators/accumulators_fwd.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/numeric/functional.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+#include <boost/accumulators/statistics/count.hpp>
+#include <boost/serialization/vector.hpp>
+#include <boost/serialization/utility.hpp>
+
+namespace boost { namespace accumulators
+{
+///////////////////////////////////////////////////////////////////////////////
+// num_cells named parameter
+//
+BOOST_PARAMETER_NESTED_KEYWORD(tag, p_square_cumulative_distribution_num_cells, num_cells)
+
+BOOST_ACCUMULATORS_IGNORE_GLOBAL(p_square_cumulative_distribution_num_cells)
+
+namespace impl
+{
+    ///////////////////////////////////////////////////////////////////////////////
+    // p_square_cumulative_distribution_impl
+    //  cumulative_distribution calculation (as histogram)
+    /**
+        @brief Histogram calculation of the cumulative distribution with the \f$P^2\f$ algorithm
+
+        A histogram of the sample cumulative distribution is computed dynamically without storing samples
+        based on the \f$ P^2 \f$ algorithm. The returned histogram has a specifiable amount (num_cells)
+        equiprobable (and not equal-sized) cells.
+
+        For further details, see
+
+        R. Jain and I. Chlamtac, The P^2 algorithm for dynamic calculation of quantiles and
+        histograms without storing observations, Communications of the ACM,
+        Volume 28 (October), Number 10, 1985, p. 1076-1085.
+
+        @param p_square_cumulative_distribution_num_cells.
+    */
+    template<typename Sample>
+    struct p_square_cumulative_distribution_impl
+      : accumulator_base
+    {
+        typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type float_type;
+        typedef std::vector<float_type> array_type;
+        typedef std::vector<std::pair<float_type, float_type> > histogram_type;
+        // for boost::result_of
+        typedef iterator_range<typename histogram_type::iterator> result_type;
+
+        template<typename Args>
+        p_square_cumulative_distribution_impl(Args const &args)
+          : num_cells(args[p_square_cumulative_distribution_num_cells])
+          , heights(num_cells + 1)
+          , actual_positions(num_cells + 1)
+          , desired_positions(num_cells + 1)
+          , positions_increments(num_cells + 1)
+          , histogram(num_cells + 1)
+          , is_dirty(true)
+        {
+            std::size_t b = this->num_cells;
+
+            for (std::size_t i = 0; i < b + 1; ++i)
+            {
+                this->actual_positions[i] = i + 1.;
+                this->desired_positions[i] = i + 1.;
+                this->positions_increments[i] = numeric::fdiv(i, b);
+            }
+        }
+
+        template<typename Args>
+        void operator ()(Args const &args)
+        {
+            this->is_dirty = true;
+
+            std::size_t cnt = count(args);
+            std::size_t sample_cell = 1; // k
+            std::size_t b = this->num_cells;
+
+            // accumulate num_cells + 1 first samples
+            if (cnt <= b + 1)
+            {
+                this->heights[cnt - 1] = args[sample];
+
+                // complete the initialization of heights by sorting
+                if (cnt == b + 1)
+                {
+                    std::sort(this->heights.begin(), this->heights.end());
+                }
+            }
+            else
+            {
+                // find cell k such that heights[k-1] <= args[sample] < heights[k] and adjust extreme values
+                if (args[sample] < this->heights[0])
+                {
+                    this->heights[0] = args[sample];
+                    sample_cell = 1;
+                }
+                else if (this->heights[b] <= args[sample])
+                {
+                    this->heights[b] = args[sample];
+                    sample_cell = b;
+                }
+                else
+                {
+                    typename array_type::iterator it;
+                    it = std::upper_bound(
+                        this->heights.begin()
+                      , this->heights.end()
+                      , args[sample]
+                    );
+
+                    sample_cell = std::distance(this->heights.begin(), it);
+                }
+
+                // increment positions of markers above sample_cell
+                for (std::size_t i = sample_cell; i < b + 1; ++i)
+                {
+                    ++this->actual_positions[i];
+                }
+
+                // update desired position of markers 2 to num_cells + 1
+                // (desired position of first marker is always 1)
+                for (std::size_t i = 1; i < b + 1; ++i)
+                {
+                    this->desired_positions[i] += this->positions_increments[i];
+                }
+
+                // adjust heights of markers 2 to num_cells if necessary
+                for (std::size_t i = 1; i < b; ++i)
+                {
+                    // offset to desire position
+                    float_type d = this->desired_positions[i] - this->actual_positions[i];
+
+                    // offset to next position
+                    float_type dp = this->actual_positions[i + 1] - this->actual_positions[i];
+
+                    // offset to previous position
+                    float_type dm = this->actual_positions[i - 1] - this->actual_positions[i];
+
+                    // height ds
+                    float_type hp = (this->heights[i + 1] - this->heights[i]) / dp;
+                    float_type hm = (this->heights[i - 1] - this->heights[i]) / dm;
+
+                    if ( ( d >= 1. && dp > 1. ) || ( d <= -1. && dm < -1. ) )
+                    {
+                        short sign_d = static_cast<short>(d / std::abs(d));
+
+                        // try adjusting heights[i] using p-squared formula
+                        float_type h = this->heights[i] + sign_d / (dp - dm) * ( (sign_d - dm) * hp + (dp - sign_d) * hm );
+
+                        if ( this->heights[i - 1] < h && h < this->heights[i + 1] )
+                        {
+                            this->heights[i] = h;
+                        }
+                        else
+                        {
+                            // use linear formula
+                            if (d>0)
+                            {
+                                this->heights[i] += hp;
+                            }
+                            if (d<0)
+                            {
+                                this->heights[i] -= hm;
+                            }
+                        }
+                        this->actual_positions[i] += sign_d;
+                    }
+                }
+            }
+        }
+
+        template<typename Args>
+        result_type result(Args const &args) const
+        {
+            if (this->is_dirty)
+            {
+                this->is_dirty = false;
+
+                // creates a vector of std::pair where each pair i holds
+                // the values heights[i] (x-axis of histogram) and
+                // actual_positions[i] / cnt (y-axis of histogram)
+
+                std::size_t cnt = count(args);
+
+                for (std::size_t i = 0; i < this->histogram.size(); ++i)
+                {
+                    this->histogram[i] = std::make_pair(this->heights[i], numeric::fdiv(this->actual_positions[i], cnt));
+                }
+            }
+            //return histogram;
+            return make_iterator_range(this->histogram);
+        }
+    
+        // make this accumulator serializeable
+        // TODO split to save/load and check on parameters provided in ctor
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int file_version)
+        {
+            ar & num_cells;
+            ar & heights;
+            ar & actual_positions;
+            ar & desired_positions;
+            ar & positions_increments;
+            ar & histogram;
+            ar & is_dirty; 
+        }
+
+    private:
+        std::size_t num_cells;            // number of cells b
+        array_type  heights;              // q_i
+        array_type  actual_positions;     // n_i
+        array_type  desired_positions;    // n'_i
+        array_type  positions_increments; // dn'_i
+        mutable histogram_type histogram; // histogram
+        mutable bool is_dirty;
+    };
+
+} // namespace detail
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::p_square_cumulative_distribution
+//
+namespace tag
+{
+    struct p_square_cumulative_distribution
+      : depends_on<count>
+      , p_square_cumulative_distribution_num_cells
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::p_square_cumulative_distribution_impl<mpl::_1> impl;
+    };
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// extract::p_square_cumulative_distribution
+//
+namespace extract
+{
+    extractor<tag::p_square_cumulative_distribution> const p_square_cumulative_distribution = {};
+
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(p_square_cumulative_distribution)
+}
+
+using extract::p_square_cumulative_distribution;
+
+// So that p_square_cumulative_distribution can be automatically substituted with
+// weighted_p_square_cumulative_distribution when the weight parameter is non-void
+template<>
+struct as_weighted_feature<tag::p_square_cumulative_distribution>
+{
+    typedef tag::weighted_p_square_cumulative_distribution type;
+};
+
+template<>
+struct feature_of<tag::weighted_p_square_cumulative_distribution>
+  : feature_of<tag::p_square_cumulative_distribution>
+{
+};
+
+}} // namespace boost::accumulators
+
+#endif

+ 19 - 0
library/include/boost/accumulators/statistics/p_square_cumulative_distribution.hpp

@@ -0,0 +1,19 @@
+///////////////////////////////////////////////////////////////////////////////
+// p_square_cumulative_distribution.hpp
+//
+//  Copyright 2012 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_P_SQUARE_CUMULATIVE_DISTRIBUTION_HPP_03_19_2012
+#define BOOST_ACCUMULATORS_STATISTICS_P_SQUARE_CUMULATIVE_DISTRIBUTION_HPP_03_19_2012
+
+#if defined(_MSC_VER) || defined(__BORLANDC__) && !defined(__clang__) || defined(__DMC__)
+#  pragma message ("Warning: This header is deprecated. Please use: boost/accumulators/statistics/p_square_cumul_dist.hpp")
+#elif defined(__GNUC__) || defined(__HP_aCC) || defined(__SUNPRO_CC) || defined(__IBMCPP__) || defined(__BORLANDC__)
+#  warning "This header is deprecated. Please use: boost/accumulators/statistics/p_square_cumul_dist.hpp"
+#endif
+
+#include <boost/accumulators/statistics/p_square_cumul_dist.hpp>
+
+#endif

+ 271 - 0
library/include/boost/accumulators/statistics/p_square_quantile.hpp

@@ -0,0 +1,271 @@
+///////////////////////////////////////////////////////////////////////////////
+// p_square_quantile.hpp
+//
+//  Copyright 2005 Daniel Egloff. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_P_SQUARE_QUANTILE_HPP_DE_01_01_2006
+#define BOOST_ACCUMULATORS_STATISTICS_P_SQUARE_QUANTILE_HPP_DE_01_01_2006
+
+#include <cmath>
+#include <functional>
+#include <boost/array.hpp>
+#include <boost/mpl/placeholders.hpp>
+#include <boost/type_traits/is_same.hpp>
+#include <boost/parameter/keyword.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/numeric/functional.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/framework/depends_on.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+#include <boost/accumulators/statistics/count.hpp>
+#include <boost/accumulators/statistics/parameters/quantile_probability.hpp>
+#include <boost/serialization/boost_array.hpp>
+
+namespace boost { namespace accumulators
+{
+
+namespace impl
+{
+    ///////////////////////////////////////////////////////////////////////////////
+    // p_square_quantile_impl
+    //  single quantile estimation
+    /**
+        @brief Single quantile estimation with the \f$P^2\f$ algorithm
+
+        The \f$P^2\f$ algorithm estimates a quantile dynamically without storing samples. Instead of
+        storing the whole sample cumulative distribution, only five points (markers) are stored. The heights
+        of these markers are the minimum and the maximum of the samples and the current estimates of the
+        \f$(p/2)\f$-, \f$p\f$- and \f$(1+p)/2\f$-quantiles. Their positions are equal to the number
+        of samples that are smaller or equal to the markers. Each time a new samples is recorded, the
+        positions of the markers are updated and if necessary their heights are adjusted using a piecewise-
+        parabolic formula.
+
+        For further details, see
+
+        R. Jain and I. Chlamtac, The P^2 algorithm for dynamic calculation of quantiles and
+        histograms without storing observations, Communications of the ACM,
+        Volume 28 (October), Number 10, 1985, p. 1076-1085.
+
+        @param quantile_probability
+    */
+    template<typename Sample, typename Impl>
+    struct p_square_quantile_impl
+      : accumulator_base
+    {
+        typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type float_type;
+        typedef array<float_type, 5> array_type;
+        // for boost::result_of
+        typedef float_type result_type;
+
+        template<typename Args>
+        p_square_quantile_impl(Args const &args)
+          : p(is_same<Impl, for_median>::value ? float_type(0.5) : args[quantile_probability | float_type(0.5)])
+          , heights()
+          , actual_positions()
+          , desired_positions()
+          , positions_increments()
+        {
+            for(std::size_t i = 0; i < 5; ++i)
+            {
+                this->actual_positions[i] = i + float_type(1.);
+            }
+
+            this->desired_positions[0] = float_type(1.);
+            this->desired_positions[1] = float_type(1.) + float_type(2.) * this->p;
+            this->desired_positions[2] = float_type(1.) + float_type(4.) * this->p;
+            this->desired_positions[3] = float_type(3.) + float_type(2.) * this->p;
+            this->desired_positions[4] = float_type(5.);
+
+
+            this->positions_increments[0] = float_type(0.);
+            this->positions_increments[1] = this->p / float_type(2.);
+            this->positions_increments[2] = this->p;
+            this->positions_increments[3] = (float_type(1.) + this->p) / float_type(2.);
+            this->positions_increments[4] = float_type(1.);
+        }
+
+        template<typename Args>
+        void operator ()(Args const &args)
+        {
+            std::size_t cnt = count(args);
+
+            // accumulate 5 first samples
+            if(cnt <= 5)
+            {
+                this->heights[cnt - 1] = args[sample];
+
+                // complete the initialization of heights by sorting
+                if(cnt == 5)
+                {
+                    std::sort(this->heights.begin(), this->heights.end());
+                }
+            }
+            else
+            {
+                std::size_t sample_cell = 1; // k
+
+                // find cell k such that heights[k-1] <= args[sample] < heights[k] and adjust extreme values
+                if (args[sample] < this->heights[0])
+                {
+                    this->heights[0] = args[sample];
+                    sample_cell = 1;
+                }
+                else if (this->heights[4] <= args[sample])
+                {
+                    this->heights[4] = args[sample];
+                    sample_cell = 4;
+                }
+                else
+                {
+                    typedef typename array_type::iterator iterator;
+                    iterator it = std::upper_bound(
+                        this->heights.begin()
+                      , this->heights.end()
+                      , args[sample]
+                    );
+
+                    sample_cell = std::distance(this->heights.begin(), it);
+                }
+
+                // update positions of markers above sample_cell
+                for(std::size_t i = sample_cell; i < 5; ++i)
+                {
+                    ++this->actual_positions[i];
+                }
+
+                // update desired positions of all markers
+                for(std::size_t i = 0; i < 5; ++i)
+                {
+                    this->desired_positions[i] += this->positions_increments[i];
+                }
+
+                // adjust heights and actual positions of markers 1 to 3 if necessary
+                for(std::size_t i = 1; i <= 3; ++i)
+                {
+                    // offset to desired positions
+                    float_type d = this->desired_positions[i] - this->actual_positions[i];
+
+                    // offset to next position
+                    float_type dp = this->actual_positions[i + 1] - this->actual_positions[i];
+
+                    // offset to previous position
+                    float_type dm = this->actual_positions[i - 1] - this->actual_positions[i];
+
+                    // height ds
+                    float_type hp = (this->heights[i + 1] - this->heights[i]) / dp;
+                    float_type hm = (this->heights[i - 1] - this->heights[i]) / dm;
+
+                    if((d >= float_type(1.) && dp > float_type(1.)) || (d <= float_type(-1.) && dm < float_type(-1.)))
+                    {
+                        short sign_d = static_cast<short>(d / std::abs(d));
+
+                        // try adjusting heights[i] using p-squared formula
+                        float_type h = this->heights[i] + sign_d / (dp - dm) * ((sign_d - dm) * hp
+                                     + (dp - sign_d) * hm);
+
+                        if(this->heights[i - 1] < h && h < this->heights[i + 1])
+                        {
+                            this->heights[i] = h;
+                        }
+                        else
+                        {
+                            // use linear formula
+                            if(d > float_type(0))
+                            {
+                                this->heights[i] += hp;
+                            }
+                            if(d < float_type(0))
+                            {
+                                this->heights[i] -= hm;
+                            }
+                        }
+                        this->actual_positions[i] += sign_d;
+                    }
+                }
+            }
+        }
+
+        result_type result(dont_care) const
+        {
+            return this->heights[2];
+        }
+
+        // make this accumulator serializeable
+        // TODO: do we need to split to load/save and verify that P did not change?
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int file_version)
+        { 
+            ar & p;
+            ar & heights;
+            ar & actual_positions;
+            ar & desired_positions;
+            ar & positions_increments;
+        }
+
+    private:
+        float_type p;                    // the quantile probability p
+        array_type heights;              // q_i
+        array_type actual_positions;     // n_i
+        array_type desired_positions;    // n'_i
+        array_type positions_increments; // dn'_i
+    };
+
+} // namespace detail
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::p_square_quantile
+//
+namespace tag
+{
+    struct p_square_quantile
+      : depends_on<count>
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::p_square_quantile_impl<mpl::_1, regular> impl;
+    };
+    struct p_square_quantile_for_median
+      : depends_on<count>
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::p_square_quantile_impl<mpl::_1, for_median> impl;
+    };
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// extract::p_square_quantile
+// extract::p_square_quantile_for_median
+//
+namespace extract
+{
+    extractor<tag::p_square_quantile> const p_square_quantile = {};
+    extractor<tag::p_square_quantile_for_median> const p_square_quantile_for_median = {};
+
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(p_square_quantile)
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(p_square_quantile_for_median)
+}
+
+using extract::p_square_quantile;
+using extract::p_square_quantile_for_median;
+
+// So that p_square_quantile can be automatically substituted with
+// weighted_p_square_quantile when the weight parameter is non-void
+template<>
+struct as_weighted_feature<tag::p_square_quantile>
+{
+    typedef tag::weighted_p_square_quantile type;
+};
+
+template<>
+struct feature_of<tag::weighted_p_square_quantile>
+  : feature_of<tag::p_square_quantile>
+{
+};
+
+}} // namespace boost::accumulators
+
+#endif

+ 23 - 0
library/include/boost/accumulators/statistics/parameters/quantile_probability.hpp

@@ -0,0 +1,23 @@
+///////////////////////////////////////////////////////////////////////////////
+// quantile_probability.hpp
+//
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_PARAMETERS_QUANTILE_PROBABILITY_HPP_EAN_03_11_2005
+#define BOOST_ACCUMULATORS_STATISTICS_PARAMETERS_QUANTILE_PROBABILITY_HPP_EAN_03_11_2005
+
+#include <boost/parameter/keyword.hpp>
+#include <boost/accumulators/accumulators_fwd.hpp>
+
+namespace boost { namespace accumulators
+{
+
+BOOST_PARAMETER_KEYWORD(tag, quantile_probability)
+
+BOOST_ACCUMULATORS_IGNORE_GLOBAL(quantile_probability)
+
+}} // namespace boost::accumulators
+
+#endif

+ 434 - 0
library/include/boost/accumulators/statistics/peaks_over_threshold.hpp

@@ -0,0 +1,434 @@
+///////////////////////////////////////////////////////////////////////////////
+// peaks_over_threshold.hpp
+//
+//  Copyright 2006 Daniel Egloff, Olivier Gygi. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_PEAKS_OVER_THRESHOLD_HPP_DE_01_01_2006
+#define BOOST_ACCUMULATORS_STATISTICS_PEAKS_OVER_THRESHOLD_HPP_DE_01_01_2006
+
+#include <vector>
+#include <limits>
+#include <numeric>
+#include <functional>
+#include <boost/config/no_tr1/cmath.hpp> // pow
+#include <sstream> // stringstream
+#include <stdexcept> // runtime_error
+#include <boost/throw_exception.hpp>
+#include <boost/range.hpp>
+#include <boost/mpl/if.hpp>
+#include <boost/mpl/int.hpp>
+#include <boost/mpl/placeholders.hpp>
+#include <boost/parameter/keyword.hpp>
+#include <boost/tuple/tuple.hpp>
+#include <boost/accumulators/accumulators_fwd.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/numeric/functional.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/framework/depends_on.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+#include <boost/accumulators/statistics/parameters/quantile_probability.hpp>
+#include <boost/accumulators/statistics/count.hpp>
+#include <boost/accumulators/statistics/tail.hpp>
+
+#ifdef _MSC_VER
+# pragma warning(push)
+# pragma warning(disable: 4127) // conditional expression is constant
+#endif
+
+namespace boost { namespace accumulators
+{
+
+///////////////////////////////////////////////////////////////////////////////
+// threshold_probability and threshold named parameters
+//
+BOOST_PARAMETER_NESTED_KEYWORD(tag, pot_threshold_value, threshold_value)
+BOOST_PARAMETER_NESTED_KEYWORD(tag, pot_threshold_probability, threshold_probability)
+
+BOOST_ACCUMULATORS_IGNORE_GLOBAL(pot_threshold_value)
+BOOST_ACCUMULATORS_IGNORE_GLOBAL(pot_threshold_probability)
+
+namespace impl
+{
+    ///////////////////////////////////////////////////////////////////////////////
+    // peaks_over_threshold_impl
+    //  works with an explicit threshold value and does not depend on order statistics
+    /**
+        @brief Peaks over Threshold Method for Quantile and Tail Mean Estimation
+
+        According to the theorem of Pickands-Balkema-de Haan, the distribution function \f$F_u(x)\f$ of
+        the excesses \f$x\f$ over some sufficiently high threshold \f$u\f$ of a distribution function \f$F(x)\f$
+        may be approximated by a generalized Pareto distribution
+        \f[
+            G_{\xi,\beta}(x) =
+            \left\{
+            \begin{array}{ll}
+                \beta^{-1}\left(1+\frac{\xi x}{\beta}\right)^{-1/\xi-1} & \textrm{if }\xi\neq0\\
+                \beta^{-1}\exp\left(-\frac{x}{\beta}\right) & \textrm{if }\xi=0,
+            \end{array}
+            \right.
+        \f]
+        with suitable parameters \f$\xi\f$ and \f$\beta\f$ that can be estimated, e.g., with the method of moments, cf.
+        Hosking and Wallis (1987),
+        \f[
+            \begin{array}{lll}
+            \hat{\xi} & = & \frac{1}{2}\left[1-\frac{(\hat{\mu}-u)^2}{\hat{\sigma}^2}\right]\\
+            \hat{\beta} & = & \frac{\hat{\mu}-u}{2}\left[\frac{(\hat{\mu}-u)^2}{\hat{\sigma}^2}+1\right],
+            \end{array}
+        \f]
+        \f$\hat{\mu}\f$ and \f$\hat{\sigma}^2\f$ being the empirical mean and variance of the samples over
+        the threshold \f$u\f$. Equivalently, the distribution function
+        \f$F_u(x-u)\f$ of the exceedances \f$x-u\f$ can be approximated by
+        \f$G_{\xi,\beta}(x-u)=G_{\xi,\beta,u}(x)\f$. Since for \f$x\geq u\f$ the distribution function \f$F(x)\f$
+        can be written as
+        \f[
+            F(x) = [1 - \P(X \leq u)]F_u(x - u) + \P(X \leq u)
+        \f]
+        and the probability \f$\P(X \leq u)\f$ can be approximated by the empirical distribution function
+        \f$F_n(u)\f$ evaluated at \f$u\f$, an estimator of \f$F(x)\f$ is given by
+        \f[
+            \widehat{F}(x) = [1 - F_n(u)]G_{\xi,\beta,u}(x) + F_n(u).
+        \f]
+        It can be shown that \f$\widehat{F}(x)\f$ is a generalized
+        Pareto distribution \f$G_{\xi,\bar{\beta},\bar{u}}(x)\f$ with \f$\bar{\beta}=\beta[1-F_n(u)]^{\xi}\f$
+        and \f$\bar{u}=u-\bar{\beta}\left\{[1-F_n(u)]^{-\xi}-1\right\}/\xi\f$. By inverting \f$\widehat{F}(x)\f$,
+        one obtains an estimator for the \f$\alpha\f$-quantile,
+        \f[
+            \hat{q}_{\alpha} = \bar{u} + \frac{\bar{\beta}}{\xi}\left[(1-\alpha)^{-\xi}-1\right],
+        \f]
+        and similarly an estimator for the (coherent) tail mean,
+        \f[
+            \widehat{CTM}_{\alpha} = \hat{q}_{\alpha} - \frac{\bar{\beta}}{\xi-1}(1-\alpha)^{-\xi},
+        \f]
+        cf. McNeil and Frey (2000).
+
+        Note that in case extreme values of the left tail are fitted, the distribution is mirrored with respect to the
+        \f$y\f$ axis such that the left tail can be treated as a right tail. The computed fit parameters thus define
+        the Pareto distribution that fits the mirrored left tail. When quantities like a quantile or a tail mean are
+        computed using the fit parameters obtained from the mirrored data, the result is mirrored back, yielding the
+        correct result.
+
+        For further details, see
+
+        J. R. M. Hosking and J. R. Wallis, Parameter and quantile estimation for the generalized Pareto distribution,
+        Technometrics, Volume 29, 1987, p. 339-349
+
+        A. J. McNeil and R. Frey, Estimation of Tail-Related Risk Measures for Heteroscedastic Financial Time Series:
+        an Extreme Value Approach, Journal of Empirical Finance, Volume 7, 2000, p. 271-300
+
+        @param quantile_probability
+        @param pot_threshold_value
+    */
+    template<typename Sample, typename LeftRight>
+    struct peaks_over_threshold_impl
+      : accumulator_base
+    {
+        typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type float_type;
+        // for boost::result_of
+        typedef boost::tuple<float_type, float_type, float_type> result_type;
+        // for left tail fitting, mirror the extreme values
+        typedef mpl::int_<is_same<LeftRight, left>::value ? -1 : 1> sign;
+
+        template<typename Args>
+        peaks_over_threshold_impl(Args const &args)
+          : Nu_(0)
+          , mu_(sign::value * numeric::fdiv(args[sample | Sample()], (std::size_t)1))
+          , sigma2_(numeric::fdiv(args[sample | Sample()], (std::size_t)1))
+          , threshold_(sign::value * args[pot_threshold_value])
+          , fit_parameters_(boost::make_tuple(0., 0., 0.))
+          , is_dirty_(true)
+        {
+        }
+
+        template<typename Args>
+        void operator ()(Args const &args)
+        {
+            this->is_dirty_ = true;
+
+            if (sign::value * args[sample] > this->threshold_)
+            {
+                this->mu_ += args[sample];
+                this->sigma2_ += args[sample] * args[sample];
+                ++this->Nu_;
+            }
+        }
+
+        template<typename Args>
+        result_type result(Args const &args) const
+        {
+            if (this->is_dirty_)
+            {
+                this->is_dirty_ = false;
+
+                std::size_t cnt = count(args);
+
+                this->mu_ = sign::value * numeric::fdiv(this->mu_, this->Nu_);
+                this->sigma2_ = numeric::fdiv(this->sigma2_, this->Nu_);
+                this->sigma2_ -= this->mu_ * this->mu_;
+
+                float_type threshold_probability = numeric::fdiv(cnt - this->Nu_, cnt);
+
+                float_type tmp = numeric::fdiv(( this->mu_ - this->threshold_ )*( this->mu_ - this->threshold_ ), this->sigma2_);
+                float_type xi_hat = 0.5 * ( 1. - tmp );
+                float_type beta_hat = 0.5 * ( this->mu_ - this->threshold_ ) * ( 1. + tmp );
+                float_type beta_bar = beta_hat * std::pow(1. - threshold_probability, xi_hat);
+                float_type u_bar = this->threshold_ - beta_bar * ( std::pow(1. - threshold_probability, -xi_hat) - 1.)/xi_hat;
+                this->fit_parameters_ = boost::make_tuple(u_bar, beta_bar, xi_hat);
+            }
+
+            return this->fit_parameters_;
+        }
+
+        // make this accumulator serializeable
+        // TODO: do we need to split to load/save and verify that threshold did not change?
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int file_version)
+        { 
+            ar & Nu_;
+            ar & mu_;
+            ar & sigma2_;
+            ar & threshold_;
+            ar & get<0>(fit_parameters_);
+            ar & get<1>(fit_parameters_);
+            ar & get<2>(fit_parameters_);
+            ar & is_dirty_;
+        }
+
+    private:
+        std::size_t Nu_;                     // number of samples larger than threshold
+        mutable float_type mu_;              // mean of Nu_ largest samples
+        mutable float_type sigma2_;          // variance of Nu_ largest samples
+        float_type threshold_;
+        mutable result_type fit_parameters_; // boost::tuple that stores fit parameters
+        mutable bool is_dirty_;
+    };
+
+    ///////////////////////////////////////////////////////////////////////////////
+    // peaks_over_threshold_prob_impl
+    //  determines threshold from a given threshold probability using order statistics
+    /**
+        @brief Peaks over Threshold Method for Quantile and Tail Mean Estimation
+
+        @sa peaks_over_threshold_impl
+
+        @param quantile_probability
+        @param pot_threshold_probability
+    */
+    template<typename Sample, typename LeftRight>
+    struct peaks_over_threshold_prob_impl
+      : accumulator_base
+    {
+        typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type float_type;
+        // for boost::result_of
+        typedef boost::tuple<float_type, float_type, float_type> result_type;
+        // for left tail fitting, mirror the extreme values
+        typedef mpl::int_<is_same<LeftRight, left>::value ? -1 : 1> sign;
+
+        template<typename Args>
+        peaks_over_threshold_prob_impl(Args const &args)
+          : mu_(sign::value * numeric::fdiv(args[sample | Sample()], (std::size_t)1))
+          , sigma2_(numeric::fdiv(args[sample | Sample()], (std::size_t)1))
+          , threshold_probability_(args[pot_threshold_probability])
+          , fit_parameters_(boost::make_tuple(0., 0., 0.))
+          , is_dirty_(true)
+        {
+        }
+
+        void operator ()(dont_care)
+        {
+            this->is_dirty_ = true;
+        }
+
+        template<typename Args>
+        result_type result(Args const &args) const
+        {
+            if (this->is_dirty_)
+            {
+                this->is_dirty_ = false;
+
+                std::size_t cnt = count(args);
+
+                // the n'th cached sample provides an approximate threshold value u
+                std::size_t n = static_cast<std::size_t>(
+                    std::ceil(
+                        cnt * ( ( is_same<LeftRight, left>::value ) ? this->threshold_probability_ : 1. - this->threshold_probability_ )
+                    )
+                );
+
+                // If n is in a valid range, return result, otherwise return NaN or throw exception
+                if ( n >= static_cast<std::size_t>(tail(args).size()))
+                {
+                    if (std::numeric_limits<float_type>::has_quiet_NaN)
+                    {
+                        return boost::make_tuple(
+                            std::numeric_limits<float_type>::quiet_NaN()
+                          , std::numeric_limits<float_type>::quiet_NaN()
+                          , std::numeric_limits<float_type>::quiet_NaN()
+                        );
+                    }
+                    else
+                    {
+                        std::ostringstream msg;
+                        msg << "index n = " << n << " is not in valid range [0, " << tail(args).size() << ")";
+                        boost::throw_exception(std::runtime_error(msg.str()));
+                        return boost::make_tuple(Sample(0), Sample(0), Sample(0));
+                    }
+                }
+                else
+                {
+                    float_type u = *(tail(args).begin() + n - 1) * sign::value;
+
+                    // compute mean and variance of samples above/under threshold value u
+                    for (std::size_t i = 0; i < n; ++i)
+                    {
+                        mu_ += *(tail(args).begin() + i);
+                        sigma2_ += *(tail(args).begin() + i) * (*(tail(args).begin() + i));
+                    }
+
+                    this->mu_ = sign::value * numeric::fdiv(this->mu_, n);
+                    this->sigma2_ = numeric::fdiv(this->sigma2_, n);
+                    this->sigma2_ -= this->mu_ * this->mu_;
+
+                    if (is_same<LeftRight, left>::value)
+                        this->threshold_probability_ = 1. - this->threshold_probability_;
+
+                    float_type tmp = numeric::fdiv(( this->mu_ - u )*( this->mu_ - u ), this->sigma2_);
+                    float_type xi_hat = 0.5 * ( 1. - tmp );
+                    float_type beta_hat = 0.5 * ( this->mu_ - u ) * ( 1. + tmp );
+                    float_type beta_bar = beta_hat * std::pow(1. - threshold_probability_, xi_hat);
+                    float_type u_bar = u - beta_bar * ( std::pow(1. - threshold_probability_, -xi_hat) - 1.)/xi_hat;
+                    this->fit_parameters_ = boost::make_tuple(u_bar, beta_bar, xi_hat);
+                }
+            }
+
+            return this->fit_parameters_;
+        }
+
+        // make this accumulator serializeable
+        // TODO: do we need to split to load/save and verify that threshold did not change?
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int file_version)
+        { 
+            ar & mu_;
+            ar & sigma2_;
+            ar & threshold_probability_;
+            ar & get<0>(fit_parameters_);
+            ar & get<1>(fit_parameters_);
+            ar & get<2>(fit_parameters_);
+            ar & is_dirty_;
+        }
+
+    private:
+        mutable float_type mu_;                     // mean of samples above threshold u
+        mutable float_type sigma2_;                 // variance of samples above threshold u
+        mutable float_type threshold_probability_;
+        mutable result_type fit_parameters_;        // boost::tuple that stores fit parameters
+        mutable bool is_dirty_;
+    };
+
+} // namespace impl
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::peaks_over_threshold
+//
+namespace tag
+{
+    template<typename LeftRight>
+    struct peaks_over_threshold
+      : depends_on<count>
+      , pot_threshold_value
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::peaks_over_threshold_impl<mpl::_1, LeftRight> impl;
+    };
+
+    template<typename LeftRight>
+    struct peaks_over_threshold_prob
+      : depends_on<count, tail<LeftRight> >
+      , pot_threshold_probability
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::peaks_over_threshold_prob_impl<mpl::_1, LeftRight> impl;
+    };
+
+    struct abstract_peaks_over_threshold
+      : depends_on<>
+    {
+    };
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// extract::peaks_over_threshold
+//
+namespace extract
+{
+    extractor<tag::abstract_peaks_over_threshold> const peaks_over_threshold = {};
+
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(peaks_over_threshold)
+}
+
+using extract::peaks_over_threshold;
+
+// peaks_over_threshold<LeftRight>(with_threshold_value) -> peaks_over_threshold<LeftRight>
+template<typename LeftRight>
+struct as_feature<tag::peaks_over_threshold<LeftRight>(with_threshold_value)>
+{
+    typedef tag::peaks_over_threshold<LeftRight> type;
+};
+
+// peaks_over_threshold<LeftRight>(with_threshold_probability) -> peaks_over_threshold_prob<LeftRight>
+template<typename LeftRight>
+struct as_feature<tag::peaks_over_threshold<LeftRight>(with_threshold_probability)>
+{
+    typedef tag::peaks_over_threshold_prob<LeftRight> type;
+};
+
+template<typename LeftRight>
+struct feature_of<tag::peaks_over_threshold<LeftRight> >
+  : feature_of<tag::abstract_peaks_over_threshold>
+{
+};
+
+template<typename LeftRight>
+struct feature_of<tag::peaks_over_threshold_prob<LeftRight> >
+  : feature_of<tag::abstract_peaks_over_threshold>
+{
+};
+
+// So that peaks_over_threshold can be automatically substituted
+// with weighted_peaks_over_threshold when the weight parameter is non-void.
+template<typename LeftRight>
+struct as_weighted_feature<tag::peaks_over_threshold<LeftRight> >
+{
+    typedef tag::weighted_peaks_over_threshold<LeftRight> type;
+};
+
+template<typename LeftRight>
+struct feature_of<tag::weighted_peaks_over_threshold<LeftRight> >
+  : feature_of<tag::peaks_over_threshold<LeftRight> >
+{};
+
+// So that peaks_over_threshold_prob can be automatically substituted
+// with weighted_peaks_over_threshold_prob when the weight parameter is non-void.
+template<typename LeftRight>
+struct as_weighted_feature<tag::peaks_over_threshold_prob<LeftRight> >
+{
+    typedef tag::weighted_peaks_over_threshold_prob<LeftRight> type;
+};
+
+template<typename LeftRight>
+struct feature_of<tag::weighted_peaks_over_threshold_prob<LeftRight> >
+  : feature_of<tag::peaks_over_threshold_prob<LeftRight> >
+{};
+
+}} // namespace boost::accumulators
+
+#ifdef _MSC_VER
+# pragma warning(pop)
+#endif
+
+#endif

+ 212 - 0
library/include/boost/accumulators/statistics/pot_quantile.hpp

@@ -0,0 +1,212 @@
+///////////////////////////////////////////////////////////////////////////////
+// pot_quantile.hpp
+//
+//  Copyright 2006 Daniel Egloff, Olivier Gygi. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_POT_QUANTILE_HPP_DE_01_01_2006
+#define BOOST_ACCUMULATORS_STATISTICS_POT_QUANTILE_HPP_DE_01_01_2006
+
+#include <vector>
+#include <limits>
+#include <numeric>
+#include <functional>
+#include <boost/parameter/keyword.hpp>
+#include <boost/tuple/tuple.hpp>
+#include <boost/mpl/if.hpp>
+#include <boost/type_traits/is_same.hpp>
+#include <boost/mpl/placeholders.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/numeric/functional.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+#include <boost/accumulators/statistics/tail.hpp>
+#include <boost/accumulators/statistics/peaks_over_threshold.hpp>
+#include <boost/accumulators/statistics/weighted_peaks_over_threshold.hpp>
+
+namespace boost { namespace accumulators
+{
+
+namespace impl
+{
+    ///////////////////////////////////////////////////////////////////////////////
+    // pot_quantile_impl
+    //
+    /**
+        @brief Quantile Estimation based on Peaks over Threshold Method (for both left and right tails)
+
+        Computes an estimate
+        \f[
+            \hat{q}_{\alpha} = \bar{u} + \frac{\bar{\beta}}{\xi}\left[(1-\alpha)^{-\xi}-1\right]
+        \f]
+        for a right or left extreme quantile, \f$\bar[u]\f$, \f$\bar{\beta}\f$ and \f$\xi\f$ being the parameters of the
+        generalized Pareto distribution that approximates the right tail of the distribution (or the mirrored left tail,
+        in case the left tail is used). In the latter case, the result is mirrored back, yielding the correct result.
+    */
+    template<typename Sample, typename Impl, typename LeftRight>
+    struct pot_quantile_impl
+      : accumulator_base
+    {
+        typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type float_type;
+        // for boost::result_of
+        typedef float_type result_type;
+
+        pot_quantile_impl(dont_care)
+          : sign_((is_same<LeftRight, left>::value) ? -1 : 1)
+        {
+        }
+
+        template<typename Args>
+        result_type result(Args const &args) const
+        {
+            typedef
+                typename mpl::if_<
+                    is_same<Impl, weighted>
+                  , tag::weighted_peaks_over_threshold<LeftRight>
+                  , tag::peaks_over_threshold<LeftRight>
+                >::type
+            peaks_over_threshold_tag;
+
+            extractor<peaks_over_threshold_tag> const some_peaks_over_threshold = {};
+
+            float_type u_bar    = some_peaks_over_threshold(args).template get<0>();
+            float_type beta_bar = some_peaks_over_threshold(args).template get<1>();
+            float_type xi_hat   = some_peaks_over_threshold(args).template get<2>();
+
+            return this->sign_ * (u_bar + beta_bar/xi_hat * ( std::pow(
+                    is_same<LeftRight, left>::value ? args[quantile_probability] : 1. - args[quantile_probability]
+                , -xi_hat
+              ) - 1.));
+        }
+    
+        // make this accumulator serializeable
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int file_version)
+        { 
+            ar & sign_;
+        }
+
+    private:
+        short sign_; // if the fit parameters from the mirrored left tail extreme values are used, mirror back the result
+    };
+
+} // namespace impl
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::pot_quantile<>
+// tag::pot_quantile_prob<>
+// tag::weighted_pot_quantile<>
+// tag::weighted_pot_quantile_prob<>
+//
+namespace tag
+{
+    template<typename LeftRight>
+    struct pot_quantile
+      : depends_on<peaks_over_threshold<LeftRight> >
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::pot_quantile_impl<mpl::_1, unweighted, LeftRight> impl;
+    };
+    template<typename LeftRight>
+    struct pot_quantile_prob
+      : depends_on<peaks_over_threshold_prob<LeftRight> >
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::pot_quantile_impl<mpl::_1, unweighted, LeftRight> impl;
+    };
+    template<typename LeftRight>
+    struct weighted_pot_quantile
+      : depends_on<weighted_peaks_over_threshold<LeftRight> >
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::pot_quantile_impl<mpl::_1, weighted, LeftRight> impl;
+    };
+    template<typename LeftRight>
+    struct weighted_pot_quantile_prob
+      : depends_on<weighted_peaks_over_threshold_prob<LeftRight> >
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::pot_quantile_impl<mpl::_1, weighted, LeftRight> impl;
+    };
+}
+
+// pot_quantile<LeftRight>(with_threshold_value) -> pot_quantile<LeftRight>
+template<typename LeftRight>
+struct as_feature<tag::pot_quantile<LeftRight>(with_threshold_value)>
+{
+    typedef tag::pot_quantile<LeftRight> type;
+};
+
+// pot_quantile<LeftRight>(with_threshold_probability) -> pot_quantile_prob<LeftRight>
+template<typename LeftRight>
+struct as_feature<tag::pot_quantile<LeftRight>(with_threshold_probability)>
+{
+    typedef tag::pot_quantile_prob<LeftRight> type;
+};
+
+// weighted_pot_quantile<LeftRight>(with_threshold_value) -> weighted_pot_quantile<LeftRight>
+template<typename LeftRight>
+struct as_feature<tag::weighted_pot_quantile<LeftRight>(with_threshold_value)>
+{
+    typedef tag::weighted_pot_quantile<LeftRight> type;
+};
+
+// weighted_pot_quantile<LeftRight>(with_threshold_probability) -> weighted_pot_quantile_prob<LeftRight>
+template<typename LeftRight>
+struct as_feature<tag::weighted_pot_quantile<LeftRight>(with_threshold_probability)>
+{
+    typedef tag::weighted_pot_quantile_prob<LeftRight> type;
+};
+
+// for the purposes of feature-based dependency resolution,
+// pot_quantile<LeftRight> and pot_quantile_prob<LeftRight> provide
+// the same feature as quantile
+template<typename LeftRight>
+struct feature_of<tag::pot_quantile<LeftRight> >
+  : feature_of<tag::quantile>
+{
+};
+
+template<typename LeftRight>
+struct feature_of<tag::pot_quantile_prob<LeftRight> >
+  : feature_of<tag::quantile>
+{
+};
+
+// So that pot_quantile can be automatically substituted
+// with weighted_pot_quantile when the weight parameter is non-void.
+template<typename LeftRight>
+struct as_weighted_feature<tag::pot_quantile<LeftRight> >
+{
+    typedef tag::weighted_pot_quantile<LeftRight> type;
+};
+
+template<typename LeftRight>
+struct feature_of<tag::weighted_pot_quantile<LeftRight> >
+  : feature_of<tag::pot_quantile<LeftRight> >
+{
+};
+
+// So that pot_quantile_prob can be automatically substituted
+// with weighted_pot_quantile_prob when the weight parameter is non-void.
+template<typename LeftRight>
+struct as_weighted_feature<tag::pot_quantile_prob<LeftRight> >
+{
+    typedef tag::weighted_pot_quantile_prob<LeftRight> type;
+};
+
+template<typename LeftRight>
+struct feature_of<tag::weighted_pot_quantile_prob<LeftRight> >
+  : feature_of<tag::pot_quantile_prob<LeftRight> >
+{
+};
+
+}} // namespace boost::accumulators
+
+#endif

+ 219 - 0
library/include/boost/accumulators/statistics/pot_tail_mean.hpp

@@ -0,0 +1,219 @@
+///////////////////////////////////////////////////////////////////////////////
+// pot_tail_mean.hpp
+//
+//  Copyright 2006 Daniel Egloff, Olivier Gygi. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_POT_TAIL_MEAN_HPP_DE_01_01_2006
+#define BOOST_ACCUMULATORS_STATISTICS_POT_TAIL_MEAN_HPP_DE_01_01_2006
+
+#include <vector>
+#include <limits>
+#include <numeric>
+#include <functional>
+#include <boost/range.hpp>
+#include <boost/parameter/keyword.hpp>
+#include <boost/tuple/tuple.hpp>
+#include <boost/mpl/if.hpp>
+#include <boost/mpl/placeholders.hpp>
+#include <boost/type_traits/is_same.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/numeric/functional.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+#include <boost/accumulators/statistics/peaks_over_threshold.hpp>
+#include <boost/accumulators/statistics/weighted_peaks_over_threshold.hpp>
+#include <boost/accumulators/statistics/pot_quantile.hpp>
+#include <boost/accumulators/statistics/tail_mean.hpp>
+
+namespace boost { namespace accumulators
+{
+
+namespace impl
+{
+    ///////////////////////////////////////////////////////////////////////////////
+    // pot_tail_mean_impl
+    //
+    /**
+        @brief Estimation of the (coherent) tail mean based on the peaks over threshold method (for both left and right tails)
+
+        Computes an estimate for the (coherent) tail mean
+        \f[
+            \widehat{CTM}_{\alpha} = \hat{q}_{\alpha} - \frac{\bar{\beta}}{\xi-1}(1-\alpha)^{-\xi},
+        \f]
+        where \f$\bar[u]\f$, \f$\bar{\beta}\f$ and \f$\xi\f$ are the parameters of the
+        generalized Pareto distribution that approximates the right tail of the distribution (or the
+        mirrored left tail, in case the left tail is used). In the latter case, the result is mirrored
+        back, yielding the correct result.
+    */
+    template<typename Sample, typename Impl, typename LeftRight>
+    struct pot_tail_mean_impl
+      : accumulator_base
+    {
+        typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type float_type;
+        // for boost::result_of
+        typedef float_type result_type;
+
+        pot_tail_mean_impl(dont_care)
+          : sign_((is_same<LeftRight, left>::value) ? -1 : 1)
+        {
+        }
+
+        template<typename Args>
+        result_type result(Args const &args) const
+        {
+            typedef
+                typename mpl::if_<
+                    is_same<Impl, weighted>
+                  , tag::weighted_peaks_over_threshold<LeftRight>
+                  , tag::peaks_over_threshold<LeftRight>
+                >::type
+            peaks_over_threshold_tag;
+
+            typedef
+                typename mpl::if_<
+                    is_same<Impl, weighted>
+                  , tag::weighted_pot_quantile<LeftRight>
+                  , tag::pot_quantile<LeftRight>
+                >::type
+            pot_quantile_tag;
+
+            extractor<peaks_over_threshold_tag> const some_peaks_over_threshold = {};
+            extractor<pot_quantile_tag> const some_pot_quantile = {};
+
+            float_type beta_bar = some_peaks_over_threshold(args).template get<1>();
+            float_type xi_hat   = some_peaks_over_threshold(args).template get<2>();
+
+            return some_pot_quantile(args) - this->sign_ * beta_bar/( xi_hat - 1. ) * std::pow(
+                is_same<LeftRight, left>::value ? args[quantile_probability] : 1. - args[quantile_probability]
+              , -xi_hat);
+        }
+    
+        // make this accumulator serializeable
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int file_version)
+        { 
+            ar & sign_;
+        }
+
+    private:
+        short sign_; // if the fit parameters from the mirrored left tail extreme values are used, mirror back the result
+    };
+} // namespace impl
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::pot_tail_mean
+// tag::pot_tail_mean_prob
+//
+namespace tag
+{
+    template<typename LeftRight>
+    struct pot_tail_mean
+      : depends_on<peaks_over_threshold<LeftRight>, pot_quantile<LeftRight> >
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::pot_tail_mean_impl<mpl::_1, unweighted, LeftRight> impl;
+    };
+    template<typename LeftRight>
+    struct pot_tail_mean_prob
+      : depends_on<peaks_over_threshold_prob<LeftRight>, pot_quantile_prob<LeftRight> >
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::pot_tail_mean_impl<mpl::_1, unweighted, LeftRight> impl;
+    };
+    template<typename LeftRight>
+    struct weighted_pot_tail_mean
+      : depends_on<weighted_peaks_over_threshold<LeftRight>, weighted_pot_quantile<LeftRight> >
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::pot_tail_mean_impl<mpl::_1, weighted, LeftRight> impl;
+    };
+    template<typename LeftRight>
+    struct weighted_pot_tail_mean_prob
+      : depends_on<weighted_peaks_over_threshold_prob<LeftRight>, weighted_pot_quantile_prob<LeftRight> >
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::pot_tail_mean_impl<mpl::_1, weighted, LeftRight> impl;
+    };
+}
+
+// pot_tail_mean<LeftRight>(with_threshold_value) -> pot_tail_mean<LeftRight>
+template<typename LeftRight>
+struct as_feature<tag::pot_tail_mean<LeftRight>(with_threshold_value)>
+{
+    typedef tag::pot_tail_mean<LeftRight> type;
+};
+
+// pot_tail_mean<LeftRight>(with_threshold_probability) -> pot_tail_mean_prob<LeftRight>
+template<typename LeftRight>
+struct as_feature<tag::pot_tail_mean<LeftRight>(with_threshold_probability)>
+{
+    typedef tag::pot_tail_mean_prob<LeftRight> type;
+};
+
+// weighted_pot_tail_mean<LeftRight>(with_threshold_value) -> weighted_pot_tail_mean<LeftRight>
+template<typename LeftRight>
+struct as_feature<tag::weighted_pot_tail_mean<LeftRight>(with_threshold_value)>
+{
+    typedef tag::weighted_pot_tail_mean<LeftRight> type;
+};
+
+// weighted_pot_tail_mean<LeftRight>(with_threshold_probability) -> weighted_pot_tail_mean_prob<LeftRight>
+template<typename LeftRight>
+struct as_feature<tag::weighted_pot_tail_mean<LeftRight>(with_threshold_probability)>
+{
+    typedef tag::weighted_pot_tail_mean_prob<LeftRight> type;
+};
+
+// for the purposes of feature-based dependency resolution,
+// pot_tail_mean<LeftRight> and pot_tail_mean_prob<LeftRight> provide
+// the same feature as tail_mean
+template<typename LeftRight>
+struct feature_of<tag::pot_tail_mean<LeftRight> >
+  : feature_of<tag::tail_mean>
+{
+};
+
+template<typename LeftRight>
+struct feature_of<tag::pot_tail_mean_prob<LeftRight> >
+  : feature_of<tag::tail_mean>
+{
+};
+
+// So that pot_tail_mean can be automatically substituted
+// with weighted_pot_tail_mean when the weight parameter is non-void.
+template<typename LeftRight>
+struct as_weighted_feature<tag::pot_tail_mean<LeftRight> >
+{
+    typedef tag::weighted_pot_tail_mean<LeftRight> type;
+};
+
+template<typename LeftRight>
+struct feature_of<tag::weighted_pot_tail_mean<LeftRight> >
+  : feature_of<tag::pot_tail_mean<LeftRight> >
+{
+};
+
+// So that pot_tail_mean_prob can be automatically substituted
+// with weighted_pot_tail_mean_prob when the weight parameter is non-void.
+template<typename LeftRight>
+struct as_weighted_feature<tag::pot_tail_mean_prob<LeftRight> >
+{
+    typedef tag::weighted_pot_tail_mean_prob<LeftRight> type;
+};
+
+template<typename LeftRight>
+struct feature_of<tag::weighted_pot_tail_mean_prob<LeftRight> >
+  : feature_of<tag::pot_tail_mean_prob<LeftRight> >
+{
+};
+
+}} // namespace boost::accumulators
+
+#endif

+ 84 - 0
library/include/boost/accumulators/statistics/rolling_count.hpp

@@ -0,0 +1,84 @@
+///////////////////////////////////////////////////////////////////////////////
+// rolling_count.hpp
+//
+// Copyright 2008 Eric Niebler. Distributed under the Boost
+// Software License, Version 1.0. (See accompanying file
+// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_ROLLING_COUNT_HPP_EAN_26_12_2008
+#define BOOST_ACCUMULATORS_STATISTICS_ROLLING_COUNT_HPP_EAN_26_12_2008
+
+#include <boost/mpl/placeholders.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/numeric/functional.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/framework/depends_on.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+#include <boost/accumulators/statistics/rolling_window.hpp>
+
+namespace boost { namespace accumulators
+{
+
+namespace impl
+{
+
+    ///////////////////////////////////////////////////////////////////////////////
+    // rolling_count_impl
+    //    returns the count of elements in the rolling window
+    template<typename Sample>
+    struct rolling_count_impl
+      : accumulator_base
+    {
+        typedef std::size_t result_type;
+
+        rolling_count_impl(dont_care)
+        {}
+
+        template<typename Args>
+        result_type result(Args const &args) const
+        {
+            return static_cast<std::size_t>(rolling_window_plus1(args).size()) - is_rolling_window_plus1_full(args);
+        }
+        
+        // serialization is done by accumulators it depends on
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int file_version) {}
+    };
+
+} // namespace impl
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::rolling_count
+//
+namespace tag
+{
+    struct rolling_count
+      : depends_on< rolling_window_plus1 >
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::rolling_count_impl< mpl::_1 > impl;
+
+        #ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED
+        /// tag::rolling_window::window_size named parameter
+        static boost::parameter::keyword<tag::rolling_window_size> const window_size;
+        #endif
+    };
+} // namespace tag
+
+///////////////////////////////////////////////////////////////////////////////
+// extract::rolling_count
+//
+namespace extract
+{
+    extractor<tag::rolling_count> const rolling_count = {};
+
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(rolling_count)
+}
+
+using extract::rolling_count;
+
+}} // namespace boost::accumulators
+
+#endif

+ 196 - 0
library/include/boost/accumulators/statistics/rolling_mean.hpp

@@ -0,0 +1,196 @@
+///////////////////////////////////////////////////////////////////////////////
+// rolling_mean.hpp
+// Copyright (C) 2008 Eric Niebler.
+// Copyright (C) 2012 Pieter Bastiaan Ober (Integricom).
+// Distributed under the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_ROLLING_MEAN_HPP_EAN_26_12_2008
+#define BOOST_ACCUMULATORS_STATISTICS_ROLLING_MEAN_HPP_EAN_26_12_2008
+
+#include <boost/mpl/placeholders.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/numeric/functional.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/framework/depends_on.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+#include <boost/accumulators/statistics/rolling_sum.hpp>
+#include <boost/accumulators/statistics/rolling_count.hpp>
+
+namespace boost { namespace accumulators
+{
+   namespace impl
+   {
+      ///////////////////////////////////////////////////////////////////////////////
+      // lazy_rolling_mean_impl
+      //    returns the mean over the rolling window and is calculated only
+      //    when the result is requested
+      template<typename Sample>
+      struct lazy_rolling_mean_impl
+         : accumulator_base
+      {
+         // for boost::result_of
+         typedef typename numeric::functional::fdiv<Sample, std::size_t, void, void>::result_type result_type;
+
+         lazy_rolling_mean_impl(dont_care)
+         {
+         }
+
+         template<typename Args>
+         result_type result(Args const &args) const
+         {
+            return numeric::fdiv(rolling_sum(args), rolling_count(args));
+         }
+        
+         // serialization is done by accumulators it depends on
+         template<class Archive>
+         void serialize(Archive & ar, const unsigned int file_version) {}
+      };
+
+      ///////////////////////////////////////////////////////////////////////////////
+      // immediate_rolling_mean_impl
+      //     The non-lazy version computes the rolling mean recursively when a new
+      //     sample is added
+      template<typename Sample>
+      struct immediate_rolling_mean_impl
+         : accumulator_base
+      {
+         // for boost::result_of
+         typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type result_type;
+
+         template<typename Args>
+         immediate_rolling_mean_impl(Args const &args)
+            : mean_(numeric::fdiv(args[sample | Sample()],numeric::one<std::size_t>::value))
+         {
+         }
+
+         template<typename Args>
+         void operator()(Args const &args)
+         {
+            if(is_rolling_window_plus1_full(args))
+            {
+               if (rolling_window_plus1(args).front() > args[sample])
+                  mean_ -= numeric::fdiv(rolling_window_plus1(args).front()-args[sample],rolling_count(args));
+               else if (rolling_window_plus1(args).front() < args[sample])
+                  mean_ += numeric::fdiv(args[sample]-rolling_window_plus1(args).front(),rolling_count(args));
+            }
+            else
+            {
+               result_type prev_mean = mean_;
+               if (prev_mean > args[sample])
+                   mean_ -= numeric::fdiv(prev_mean-args[sample],rolling_count(args));
+               else if (prev_mean < args[sample])
+                   mean_ += numeric::fdiv(args[sample]-prev_mean,rolling_count(args));
+            }
+         }
+
+         template<typename Args>
+         result_type result(Args const &) const
+         {
+            return mean_;
+         }
+        
+         // make this accumulator serializeable
+         template<class Archive>
+         void serialize(Archive & ar, const unsigned int file_version)
+         { 
+            ar & mean_;
+         }
+
+      private:
+
+         result_type mean_;
+      };
+   } // namespace impl
+
+   ///////////////////////////////////////////////////////////////////////////////
+   // tag::lazy_rolling_mean
+   // tag::immediate_rolling_mean
+   // tag::rolling_mean
+   //
+   namespace tag
+   {
+      struct lazy_rolling_mean
+         : depends_on< rolling_sum, rolling_count >
+      {
+         /// INTERNAL ONLY
+         ///
+         typedef accumulators::impl::lazy_rolling_mean_impl< mpl::_1 > impl;
+
+#ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED
+         /// tag::rolling_window::window_size named parameter
+         static boost::parameter::keyword<tag::rolling_window_size> const window_size;
+#endif
+      };
+
+      struct immediate_rolling_mean
+         : depends_on< rolling_window_plus1, rolling_count>
+      {
+         /// INTERNAL ONLY
+         ///
+         typedef accumulators::impl::immediate_rolling_mean_impl< mpl::_1> impl;
+
+#ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED
+         /// tag::rolling_window::window_size named parameter
+         static boost::parameter::keyword<tag::rolling_window_size> const window_size;
+#endif
+      };
+
+      // make immediate_rolling_mean the default implementation
+      struct rolling_mean : immediate_rolling_mean {};
+   } // namespace tag
+
+   ///////////////////////////////////////////////////////////////////////////////
+   // extract::lazy_rolling_mean
+   // extract::immediate_rolling_mean
+   // extract::rolling_mean
+   //
+   namespace extract
+   {
+      extractor<tag::lazy_rolling_mean> const lazy_rolling_mean = {};
+      extractor<tag::immediate_rolling_mean> const immediate_rolling_mean = {};
+      extractor<tag::rolling_mean> const rolling_mean = {};
+
+      BOOST_ACCUMULATORS_IGNORE_GLOBAL(lazy_rolling_mean)
+         BOOST_ACCUMULATORS_IGNORE_GLOBAL(immediate_rolling_mean)
+         BOOST_ACCUMULATORS_IGNORE_GLOBAL(rolling_mean)
+   }
+
+   using extract::lazy_rolling_mean;
+   using extract::immediate_rolling_mean;
+   using extract::rolling_mean;
+
+   // rolling_mean(lazy) -> lazy_rolling_mean
+   template<>
+   struct as_feature<tag::rolling_mean(lazy)>
+   {
+      typedef tag::lazy_rolling_mean type;
+   };
+
+   // rolling_mean(immediate) -> immediate_rolling_mean
+   template<>
+   struct as_feature<tag::rolling_mean(immediate)>
+   {
+      typedef tag::immediate_rolling_mean type;
+   };
+
+   // for the purposes of feature-based dependency resolution,
+   // immediate_rolling_mean provides the same feature as rolling_mean
+   template<>
+   struct feature_of<tag::immediate_rolling_mean>
+      : feature_of<tag::rolling_mean>
+   {
+   };
+
+   // for the purposes of feature-based dependency resolution,
+   // lazy_rolling_mean provides the same feature as rolling_mean
+   template<>
+   struct feature_of<tag::lazy_rolling_mean>
+      : feature_of<tag::rolling_mean>
+   {
+   };
+}} // namespace boost::accumulators
+
+#endif

+ 120 - 0
library/include/boost/accumulators/statistics/rolling_moment.hpp

@@ -0,0 +1,120 @@
+///////////////////////////////////////////////////////////////////////////////
+// rolling_moment.hpp
+// Copyright 2005 Eric Niebler.
+// Copyright (C) 2014 Pieter Bastiaan Ober (Integricom).
+// Distributed under the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_ROLLING_MOMENT_HPP_EAN_27_11_2005
+#define BOOST_ACCUMULATORS_STATISTICS_ROLLING_MOMENT_HPP_EAN_27_11_2005
+
+#include <boost/config/no_tr1/cmath.hpp>
+#include <boost/mpl/int.hpp>
+#include <boost/mpl/assert.hpp>
+#include <boost/mpl/placeholders.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/numeric/functional.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/framework/depends_on.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+#include <boost/accumulators/statistics/moment.hpp>
+#include <boost/accumulators/statistics/rolling_count.hpp>
+
+namespace boost { namespace accumulators
+{
+namespace impl
+{
+    ///////////////////////////////////////////////////////////////////////////////
+    // rolling_moment_impl
+    template<typename N, typename Sample>
+    struct rolling_moment_impl
+      : accumulator_base
+    {
+        BOOST_MPL_ASSERT_RELATION(N::value, >, 0);
+        // for boost::result_of
+        typedef typename numeric::functional::fdiv<Sample, std::size_t,void,void>::result_type result_type;
+
+        template<typename Args>
+        rolling_moment_impl(Args const &args)
+          : sum_(args[sample | Sample()])
+        {
+        }
+
+        template<typename Args>
+        void operator ()(Args const &args)
+        {
+            if(is_rolling_window_plus1_full(args))
+            {
+                this->sum_ -= numeric::pow(rolling_window_plus1(args).front(), N());
+            }
+            this->sum_ += numeric::pow(args[sample], N());
+        }
+
+        template<typename Args>
+        result_type result(Args const &args) const
+        {
+            return numeric::fdiv(this->sum_, rolling_count(args));
+        }
+
+        // make this accumulator serializeable
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int file_version)
+        { 
+            ar & sum_;
+        }
+
+    private:
+        result_type sum_;
+    };
+} // namespace impl
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::rolling_moment
+//
+namespace tag
+{
+    template<int N>
+    struct rolling_moment
+      : depends_on< rolling_window_plus1, rolling_count>
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::rolling_moment_impl<mpl::int_<N>, mpl::_1> impl;
+
+        #ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED
+        /// tag::rolling_window::window_size named parameter
+        static boost::parameter::keyword<tag::rolling_window_size> const window_size;
+        #endif
+    };
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// extract::rolling_moment
+//
+namespace extract
+{
+    BOOST_ACCUMULATORS_DEFINE_EXTRACTOR(tag, rolling_moment, (int))
+}
+
+using extract::rolling_moment;
+
+// There is no weighted_rolling_moment (yet)...
+//
+//// So that rolling_moment<N> can be automatically substituted with
+//// weighted_rolling_moment<N> when the weight parameter is non-void
+//template<int N>
+//struct as_weighted_feature<tag::rolling_moment<N> >
+//{
+//    typedef tag::weighted_rolling_moment<N> type;
+//};
+//
+//template<int N>
+//struct feature_of<tag::weighted_rolling_moment<N> >
+//  : feature_of<tag::rolling_moment<N> >
+//{
+//};
+}} // namespace boost::accumulators
+
+#endif

+ 98 - 0
library/include/boost/accumulators/statistics/rolling_sum.hpp

@@ -0,0 +1,98 @@
+///////////////////////////////////////////////////////////////////////////////
+// rolling_sum.hpp
+//
+// Copyright 2008 Eric Niebler. Distributed under the Boost
+// Software License, Version 1.0. (See accompanying file
+// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_ROLLING_SUM_HPP_EAN_26_12_2008
+#define BOOST_ACCUMULATORS_STATISTICS_ROLLING_SUM_HPP_EAN_26_12_2008
+
+#include <boost/mpl/placeholders.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/numeric/functional.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/framework/depends_on.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+#include <boost/accumulators/statistics/rolling_window.hpp>
+
+namespace boost { namespace accumulators
+{
+namespace impl
+{
+    ///////////////////////////////////////////////////////////////////////////////
+    // rolling_sum_impl
+    //    returns the sum of the samples in the rolling window
+    template<typename Sample>
+    struct rolling_sum_impl
+      : accumulator_base
+    {
+        typedef Sample result_type;
+
+        template<typename Args>
+        rolling_sum_impl(Args const &args)
+          : sum_(args[sample | Sample()])
+        {}
+
+        template<typename Args>
+        void operator ()(Args const &args)
+        {
+            if(is_rolling_window_plus1_full(args))
+            {
+                this->sum_ -= rolling_window_plus1(args).front();
+            }
+            this->sum_ += args[sample];
+        }
+
+        template<typename Args>
+        result_type result(Args const & /*args*/) const
+        {
+            return this->sum_;
+        }
+
+        // make this accumulator serializeable
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int file_version)
+        { 
+            ar & sum_;
+        }
+
+    private:
+        Sample sum_;
+    };
+} // namespace impl
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::rolling_sum
+//
+namespace tag
+{
+    struct rolling_sum
+      : depends_on< rolling_window_plus1 >
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::rolling_sum_impl< mpl::_1 > impl;
+
+        #ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED
+        /// tag::rolling_window::window_size named parameter
+        static boost::parameter::keyword<tag::rolling_window_size> const window_size;
+        #endif
+    };
+} // namespace tag
+
+///////////////////////////////////////////////////////////////////////////////
+// extract::rolling_sum
+//
+namespace extract
+{
+    extractor<tag::rolling_sum> const rolling_sum = {};
+
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(rolling_sum)
+}
+
+using extract::rolling_sum;
+}} // namespace boost::accumulators
+
+#endif

+ 259 - 0
library/include/boost/accumulators/statistics/rolling_variance.hpp

@@ -0,0 +1,259 @@
+///////////////////////////////////////////////////////////////////////////////
+// rolling_variance.hpp
+// Copyright (C) 2005 Eric Niebler
+// Copyright (C) 2014 Pieter Bastiaan Ober (Integricom).
+// Distributed under the Boost Software License, Version 1.0.
+// (See accompanying file LICENSE_1_0.txt or copy at
+// http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_ROLLING_VARIANCE_HPP_EAN_15_11_2011
+#define BOOST_ACCUMULATORS_STATISTICS_ROLLING_VARIANCE_HPP_EAN_15_11_2011
+
+#include <boost/accumulators/accumulators.hpp>
+#include <boost/accumulators/statistics/stats.hpp>
+
+#include <boost/mpl/placeholders.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/numeric/functional.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/framework/depends_on.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+#include <boost/accumulators/statistics/rolling_mean.hpp>
+#include <boost/accumulators/statistics/rolling_moment.hpp>
+
+#include <boost/type_traits/is_arithmetic.hpp>
+#include <boost/utility/enable_if.hpp>
+
+namespace boost { namespace accumulators
+{
+namespace impl
+{
+    //! Immediate (lazy) calculation of the rolling variance.
+    /*!
+    Calculation of sample variance \f$\sigma_n^2\f$ is done as follows, see also
+    http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance.
+    For a rolling window of size \f$N\f$, when \f$n <= N\f$, the variance is computed according to the formula
+    \f[
+    \sigma_n^2 = \frac{1}{n-1} \sum_{i = 1}^n (x_i - \mu_n)^2.
+    \f]
+    When \f$n > N\f$, the sample variance over the window becomes:
+    \f[
+    \sigma_n^2 = \frac{1}{N-1} \sum_{i = n-N+1}^n (x_i - \mu_n)^2.
+    \f]
+    */
+    ///////////////////////////////////////////////////////////////////////////////
+    // lazy_rolling_variance_impl
+    //
+    template<typename Sample>
+    struct lazy_rolling_variance_impl
+        : accumulator_base
+    {
+        // for boost::result_of
+        typedef typename numeric::functional::fdiv<Sample, std::size_t,void,void>::result_type result_type;
+
+        lazy_rolling_variance_impl(dont_care) {}
+
+        template<typename Args>
+        result_type result(Args const &args) const
+        {
+            result_type mean = rolling_mean(args);
+            size_t nr_samples = rolling_count(args);
+            if (nr_samples < 2) return result_type();
+            return nr_samples*(rolling_moment<2>(args) - mean*mean)/(nr_samples-1);
+        }
+        
+        // serialization is done by accumulators it depends on
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int file_version) {}
+    };
+
+    //! Iterative calculation of the rolling variance.
+    /*!
+    Iterative calculation of sample variance \f$\sigma_n^2\f$ is done as follows, see also
+    http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance.
+    For a rolling window of size \f$N\f$, for the first \f$N\f$ samples, the variance is computed according to the formula
+    \f[
+    \sigma_n^2 = \frac{1}{n-1} \sum_{i = 1}^n (x_i - \mu_n)^2 = \frac{1}{n-1}M_{2,n},
+    \f]
+    where the sum of squares \f$M_{2,n}\f$ can be recursively computed as:
+    \f[
+    M_{2,n} = \sum_{i = 1}^n (x_i - \mu_n)^2 = M_{2,n-1} + (x_n - \mu_n)(x_n - \mu_{n-1}),
+    \f]
+    and the estimate of the sample mean as:
+    \f[
+    \mu_n = \frac{1}{n} \sum_{i = 1}^n x_i = \mu_{n-1} + \frac{1}{n}(x_n - \mu_{n-1}).
+    \f]
+    For further samples, when the rolling window is fully filled with data, one has to take into account that the oldest
+    sample \f$x_{n-N}\f$ is dropped from the window. The sample variance over the window now becomes:
+    \f[
+    \sigma_n^2 = \frac{1}{N-1} \sum_{i = n-N+1}^n (x_i - \mu_n)^2 = \frac{1}{n-1}M_{2,n},
+    \f]
+    where the sum of squares \f$M_{2,n}\f$ now equals:
+    \f[
+    M_{2,n} = \sum_{i = n-N+1}^n (x_i - \mu_n)^2 = M_{2,n-1} + (x_n - \mu_n)(x_n - \mu_{n-1}) - (x_{n-N} - \mu_n)(x_{n-N} - \mu_{n-1}),
+    \f]
+    and the estimated mean is:
+    \f[
+    \mu_n = \frac{1}{N} \sum_{i = n-N+1}^n x_i = \mu_{n-1} + \frac{1}{n}(x_n - x_{n-N}).
+    \f]
+
+    Note that the sample variance is not defined for \f$n <= 1\f$.
+
+    */
+    ///////////////////////////////////////////////////////////////////////////////
+    // immediate_rolling_variance_impl
+    //
+    template<typename Sample>
+    struct immediate_rolling_variance_impl
+        : accumulator_base
+    {
+        // for boost::result_of
+        typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type result_type;
+
+        template<typename Args>
+        immediate_rolling_variance_impl(Args const &args)
+            : previous_mean_(numeric::fdiv(args[sample | Sample()], numeric::one<std::size_t>::value))
+            , sum_of_squares_(numeric::fdiv(args[sample | Sample()], numeric::one<std::size_t>::value))
+        {
+        }
+
+        template<typename Args>
+        void operator()(Args const &args)
+        {
+            Sample added_sample = args[sample];
+
+            result_type mean = immediate_rolling_mean(args);
+            sum_of_squares_ += (added_sample-mean)*(added_sample-previous_mean_);
+
+            if(is_rolling_window_plus1_full(args))
+            {
+                Sample removed_sample = rolling_window_plus1(args).front();
+                sum_of_squares_ -= (removed_sample-mean)*(removed_sample-previous_mean_);
+                prevent_underflow(sum_of_squares_);
+            }
+            previous_mean_ = mean;
+        }
+
+        template<typename Args>
+        result_type result(Args const &args) const
+        {
+            size_t nr_samples = rolling_count(args);
+            if (nr_samples < 2) return result_type();
+            return numeric::fdiv(sum_of_squares_,(nr_samples-1));
+        }
+        
+        // make this accumulator serializeable
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int file_version)
+        { 
+            ar & previous_mean_;
+            ar & sum_of_squares_;
+        }
+
+    private:
+
+        result_type previous_mean_;
+        result_type sum_of_squares_;
+
+        template<typename T>
+        void prevent_underflow(T &non_negative_number,typename boost::enable_if<boost::is_arithmetic<T>,T>::type* = 0)
+        {
+            if (non_negative_number < T(0)) non_negative_number = T(0);
+        }
+        template<typename T>
+        void prevent_underflow(T &non_arithmetic_quantity,typename boost::disable_if<boost::is_arithmetic<T>,T>::type* = 0)
+        {
+        }
+    };
+} // namespace impl
+
+///////////////////////////////////////////////////////////////////////////////
+// tag:: lazy_rolling_variance
+// tag:: immediate_rolling_variance
+// tag:: rolling_variance
+//
+namespace tag
+{
+    struct lazy_rolling_variance
+        : depends_on< rolling_count, rolling_mean, rolling_moment<2> >
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::lazy_rolling_variance_impl< mpl::_1 > impl;
+
+        #ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED
+        /// tag::rolling_window::window_size named parameter
+        static boost::parameter::keyword<tag::rolling_window_size> const window_size;
+        #endif
+    };
+
+    struct immediate_rolling_variance
+        : depends_on< rolling_window_plus1, rolling_count, immediate_rolling_mean>
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::immediate_rolling_variance_impl< mpl::_1> impl;
+
+        #ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED
+        /// tag::rolling_window::window_size named parameter
+        static boost::parameter::keyword<tag::rolling_window_size> const window_size;
+        #endif
+    };
+
+    // make immediate_rolling_variance the default implementation
+    struct rolling_variance : immediate_rolling_variance {};
+} // namespace tag
+
+///////////////////////////////////////////////////////////////////////////////
+// extract::lazy_rolling_variance
+// extract::immediate_rolling_variance
+// extract::rolling_variance
+//
+namespace extract
+{
+    extractor<tag::lazy_rolling_variance> const lazy_rolling_variance = {};
+    extractor<tag::immediate_rolling_variance> const immediate_rolling_variance = {};
+    extractor<tag::rolling_variance> const rolling_variance = {};
+
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(lazy_rolling_variance)
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(immediate_rolling_variance)
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(rolling_variance)
+}
+
+using extract::lazy_rolling_variance;
+using extract::immediate_rolling_variance;
+using extract::rolling_variance;
+
+// rolling_variance(lazy) -> lazy_rolling_variance
+template<>
+struct as_feature<tag::rolling_variance(lazy)>
+{
+    typedef tag::lazy_rolling_variance type;
+};
+
+// rolling_variance(immediate) -> immediate_rolling_variance
+template<>
+struct as_feature<tag::rolling_variance(immediate)>
+{
+    typedef tag::immediate_rolling_variance type;
+};
+
+// for the purposes of feature-based dependency resolution,
+// lazy_rolling_variance provides the same feature as rolling_variance
+template<>
+struct feature_of<tag::lazy_rolling_variance>
+    : feature_of<tag::rolling_variance>
+{
+};
+
+// for the purposes of feature-based dependency resolution,
+// immediate_rolling_variance provides the same feature as rolling_variance
+template<>
+struct feature_of<tag::immediate_rolling_variance>
+  : feature_of<tag::rolling_variance>
+{
+};
+}} // namespace boost::accumulators
+
+#endif

+ 221 - 0
library/include/boost/accumulators/statistics/rolling_window.hpp

@@ -0,0 +1,221 @@
+///////////////////////////////////////////////////////////////////////////////
+// rolling_window.hpp
+//
+// Copyright 2008 Eric Niebler. Distributed under the Boost
+// Software License, Version 1.0. (See accompanying file
+// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_ROLLING_WINDOW_HPP_EAN_26_12_2008
+#define BOOST_ACCUMULATORS_STATISTICS_ROLLING_WINDOW_HPP_EAN_26_12_2008
+
+#include <cstddef>
+#include <boost/version.hpp>
+#include <boost/assert.hpp>
+#include <boost/circular_buffer.hpp>
+#include <boost/range/iterator_range.hpp>
+#include <boost/accumulators/accumulators_fwd.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/framework/depends_on.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/framework/parameters/accumulator.hpp>
+#include <boost/accumulators/numeric/functional.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+#include <boost/serialization/split_free.hpp>
+
+namespace boost { namespace serialization {
+
+// implement serialization for boost::circular_buffer
+template <class Archive, class T>
+void save(Archive& ar, const circular_buffer<T>& b, const unsigned int /* version */)
+{
+    typename circular_buffer<T>::size_type size = b.size();
+    ar << b.capacity();
+    ar << size;
+    const typename circular_buffer<T>::const_array_range one = b.array_one();
+    const typename circular_buffer<T>::const_array_range two = b.array_two();
+    ar.save_binary(one.first, one.second*sizeof(T));
+    ar.save_binary(two.first, two.second*sizeof(T));
+}
+
+template <class Archive, class T>
+void load(Archive& ar, circular_buffer<T>& b, const unsigned int /* version */)
+{
+    typename circular_buffer<T>::capacity_type capacity;
+    typename circular_buffer<T>::size_type size;
+    ar >> capacity;
+    b.set_capacity(capacity);
+    ar >> size;
+    b.clear();
+    const typename circular_buffer<T>::pointer buff = new T[size*sizeof(T)];
+    ar.load_binary(buff, size*sizeof(T));
+    b.insert(b.begin(), buff, buff+size);
+    delete[] buff;
+}
+
+template<class Archive, class T>
+inline void serialize(Archive & ar, circular_buffer<T>& b, const unsigned int version)
+{
+    split_free(ar, b, version);
+}
+
+} } // end namespace boost::serialization
+
+namespace boost { namespace accumulators
+{
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::rolling_window::size named parameter
+BOOST_PARAMETER_NESTED_KEYWORD(tag, rolling_window_size, window_size)
+
+BOOST_ACCUMULATORS_IGNORE_GLOBAL(rolling_window_size)
+
+namespace impl
+{
+    ///////////////////////////////////////////////////////////////////////////////
+    // rolling_window_plus1_impl
+    //    stores the latest N+1 samples, where N is specified at construction time
+    //    with the rolling_window_size named parameter
+    template<typename Sample>
+    struct rolling_window_plus1_impl
+      : accumulator_base
+    {
+        typedef typename circular_buffer<Sample>::const_iterator const_iterator;
+        typedef iterator_range<const_iterator> result_type;
+
+        template<typename Args>
+        rolling_window_plus1_impl(Args const & args)
+          : buffer_(args[rolling_window_size] + 1)
+        {}
+
+        #if BOOST_VERSION < 103600
+        // Before Boost 1.36, copying a circular buffer didn't copy
+        // it's capacity, and we need that behavior.
+        rolling_window_plus1_impl(rolling_window_plus1_impl const &that)
+          : buffer_(that.buffer_)
+        {
+            this->buffer_.set_capacity(that.buffer_.capacity());
+        }
+
+        rolling_window_plus1_impl &operator =(rolling_window_plus1_impl const &that)
+        {
+            this->buffer_ = that.buffer_;
+            this->buffer_.set_capacity(that.buffer_.capacity());
+        }
+        #endif
+
+        template<typename Args>
+        void operator ()(Args const &args)
+        {
+            this->buffer_.push_back(args[sample]);
+        }
+
+        bool full() const
+        {
+            return this->buffer_.full();
+        }
+
+        // The result of a shifted rolling window is the range including
+        // everything except the most recently added element.
+        result_type result(dont_care) const
+        {
+            return result_type(this->buffer_.begin(), this->buffer_.end());
+        }
+
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int version)
+        {
+            ar & buffer_;
+        }
+
+    private:
+        circular_buffer<Sample> buffer_;
+    };
+
+    template<typename Args>
+    bool is_rolling_window_plus1_full(Args const &args)
+    {
+        return find_accumulator<tag::rolling_window_plus1>(args[accumulator]).full();
+    }
+
+    ///////////////////////////////////////////////////////////////////////////////
+    // rolling_window_impl
+    //    stores the latest N samples, where N is specified at construction type
+    //    with the rolling_window_size named parameter
+    template<typename Sample>
+    struct rolling_window_impl
+      : accumulator_base
+    {
+        typedef typename circular_buffer<Sample>::const_iterator const_iterator;
+        typedef iterator_range<const_iterator> result_type;
+
+        rolling_window_impl(dont_care)
+        {}
+
+        template<typename Args>
+        result_type result(Args const &args) const
+        {
+            return rolling_window_plus1(args).advance_begin(is_rolling_window_plus1_full(args));
+        }
+        
+        // serialization is done by accumulators it depends on
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int file_version) {}
+    };
+
+} // namespace impl
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::rolling_window_plus1
+// tag::rolling_window
+//
+namespace tag
+{
+    struct rolling_window_plus1
+      : depends_on<>
+      , tag::rolling_window_size
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::rolling_window_plus1_impl< mpl::_1 > impl;
+
+        #ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED
+        /// tag::rolling_window::size named parameter
+        static boost::parameter::keyword<tag::rolling_window_size> const window_size;
+        #endif
+    };
+
+    struct rolling_window
+      : depends_on< rolling_window_plus1 >
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::rolling_window_impl< mpl::_1 > impl;
+
+        #ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED
+        /// tag::rolling_window::size named parameter
+        static boost::parameter::keyword<tag::rolling_window_size> const window_size;
+        #endif
+    };
+
+} // namespace tag
+
+///////////////////////////////////////////////////////////////////////////////
+// extract::rolling_window_plus1
+// extract::rolling_window
+//
+namespace extract
+{
+    extractor<tag::rolling_window_plus1> const rolling_window_plus1 = {};
+    extractor<tag::rolling_window> const rolling_window = {};
+
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(rolling_window_plus1)
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(rolling_window)
+}
+
+using extract::rolling_window_plus1;
+using extract::rolling_window;
+
+}} // namespace boost::accumulators
+
+#endif

+ 118 - 0
library/include/boost/accumulators/statistics/skewness.hpp

@@ -0,0 +1,118 @@
+///////////////////////////////////////////////////////////////////////////////
+// skewness.hpp
+//
+//  Copyright 2006 Olivier Gygi, Daniel Egloff. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_SKEWNESS_HPP_EAN_28_10_2005
+#define BOOST_ACCUMULATORS_STATISTICS_SKEWNESS_HPP_EAN_28_10_2005
+
+#include <limits>
+#include <boost/mpl/placeholders.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/numeric/functional.hpp>
+#include <boost/accumulators/framework/depends_on.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+#include <boost/accumulators/statistics/moment.hpp>
+#include <boost/accumulators/statistics/mean.hpp>
+
+
+namespace boost { namespace accumulators
+{
+
+namespace impl
+{
+    ///////////////////////////////////////////////////////////////////////////////
+    // skewness_impl
+    /**
+        @brief Skewness estimation
+
+        The skewness of a sample distribution is defined as the ratio of the 3rd central moment and the \f$ 3/2 \f$-th power
+        of the 2nd central moment (the variance) of the samples 3. The skewness can also be expressed by the simple moments:
+
+        \f[
+            \hat{g}_1 =
+                \frac
+                {\widehat{m}_n^{(3)}-3\widehat{m}_n^{(2)}\hat{\mu}_n+2\hat{\mu}_n^3}
+                {\left(\widehat{m}_n^{(2)} - \hat{\mu}_n^{2}\right)^{3/2}}
+        \f]
+
+        where \f$ \widehat{m}_n^{(i)} \f$ are the \f$ i \f$-th moment and \f$ \hat{\mu}_n \f$ the mean (first moment) of the
+        \f$ n \f$ samples.
+    */
+    template<typename Sample>
+    struct skewness_impl
+      : accumulator_base
+    {
+        // for boost::result_of
+        typedef typename numeric::functional::fdiv<Sample, Sample>::result_type result_type;
+
+        skewness_impl(dont_care)
+        {
+        }
+
+        template<typename Args>
+        result_type result(Args const &args) const
+        {
+            return numeric::fdiv(
+                        accumulators::moment<3>(args)
+                        - 3. * accumulators::moment<2>(args) * mean(args)
+                        + 2. * mean(args) * mean(args) * mean(args)
+                      , ( accumulators::moment<2>(args) - mean(args) * mean(args) )
+                        * std::sqrt( accumulators::moment<2>(args) - mean(args) * mean(args) )
+                   );
+        }
+        
+        // serialization is done by accumulators it depends on
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int file_version) {}
+    };
+
+} // namespace impl
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::skewness
+//
+namespace tag
+{
+    struct skewness
+      : depends_on<mean, moment<2>, moment<3> >
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::skewness_impl<mpl::_1> impl;
+    };
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// extract::skewness
+//
+namespace extract
+{
+    extractor<tag::skewness> const skewness = {};
+
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(skewness)
+}
+
+using extract::skewness;
+
+// So that skewness can be automatically substituted with
+// weighted_skewness when the weight parameter is non-void
+template<>
+struct as_weighted_feature<tag::skewness>
+{
+    typedef tag::weighted_skewness type;
+};
+
+template<>
+struct feature_of<tag::weighted_skewness>
+  : feature_of<tag::skewness>
+{
+};
+
+}} // namespace boost::accumulators
+
+#endif

+ 29 - 0
library/include/boost/accumulators/statistics/stats.hpp

@@ -0,0 +1,29 @@
+///////////////////////////////////////////////////////////////////////////////
+/// \file stats.hpp
+/// Contains the stats<> template.
+///
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_STATS_HPP_EAN_28_10_2005
+#define BOOST_ACCUMULATORS_STATISTICS_STATS_HPP_EAN_28_10_2005
+
+#include <boost/preprocessor/repetition/enum_params.hpp>
+#include <boost/mpl/vector.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+
+namespace boost { namespace accumulators
+{
+
+///////////////////////////////////////////////////////////////////////////////
+/// An MPL sequence of statistics.
+template<BOOST_PP_ENUM_PARAMS(BOOST_ACCUMULATORS_MAX_FEATURES, typename Stat)>
+struct stats
+  : mpl::vector<BOOST_PP_ENUM_PARAMS(BOOST_ACCUMULATORS_MAX_FEATURES, Stat)>
+{
+};
+
+}} // namespace boost::accumulators
+
+#endif

+ 146 - 0
library/include/boost/accumulators/statistics/sum.hpp

@@ -0,0 +1,146 @@
+///////////////////////////////////////////////////////////////////////////////
+// sum.hpp
+//
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_SUM_HPP_EAN_28_10_2005
+#define BOOST_ACCUMULATORS_STATISTICS_SUM_HPP_EAN_28_10_2005
+
+#include <boost/mpl/placeholders.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/numeric/functional.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/framework/parameters/weight.hpp>
+#include <boost/accumulators/framework/accumulators/external_accumulator.hpp>
+#include <boost/accumulators/framework/depends_on.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+#include <boost/accumulators/statistics/count.hpp>
+
+namespace boost { namespace accumulators
+{
+
+namespace impl
+{
+    ///////////////////////////////////////////////////////////////////////////////
+    // sum_impl
+    template<typename Sample, typename Tag>
+    struct sum_impl
+      : accumulator_base
+    {
+        // for boost::result_of
+        typedef Sample result_type;
+
+        template<typename Args>
+        sum_impl(Args const &args)
+          : sum(args[parameter::keyword<Tag>::get() | Sample()])
+        {
+        }
+
+        template<typename Args>
+        void operator ()(Args const &args)
+        {
+            // what about overflow?
+            this->sum += args[parameter::keyword<Tag>::get()];
+        }
+
+        result_type result(dont_care) const
+        {
+            return this->sum;
+        }
+
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int /* file_version */)
+        {
+            ar & sum;
+        }
+
+    private:
+        Sample sum;
+    };
+
+} // namespace impl
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::sum
+// tag::sum_of_weights
+// tag::sum_of_variates
+//
+namespace tag
+{
+    struct sum
+      : depends_on<>
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::sum_impl<mpl::_1, tag::sample> impl;
+    };
+
+    struct sum_of_weights
+      : depends_on<>
+    {
+        typedef mpl::true_ is_weight_accumulator;
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::sum_impl<mpl::_2, tag::weight> impl;
+    };
+
+    template<typename VariateType, typename VariateTag>
+    struct sum_of_variates
+      : depends_on<>
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef mpl::always<accumulators::impl::sum_impl<VariateType, VariateTag> > impl;
+    };
+
+    struct abstract_sum_of_variates
+      : depends_on<>
+    {
+    };
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// extract::sum
+// extract::sum_of_weights
+// extract::sum_of_variates
+//
+namespace extract
+{
+    extractor<tag::sum> const sum = {};
+    extractor<tag::sum_of_weights> const sum_of_weights = {};
+    extractor<tag::abstract_sum_of_variates> const sum_of_variates = {};
+
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(sum)
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(sum_of_weights)
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(sum_of_variates)
+}
+
+using extract::sum;
+using extract::sum_of_weights;
+using extract::sum_of_variates;
+
+// So that mean can be automatically substituted with
+// weighted_mean when the weight parameter is non-void.
+template<>
+struct as_weighted_feature<tag::sum>
+{
+    typedef tag::weighted_sum type;
+};
+
+template<>
+struct feature_of<tag::weighted_sum>
+  : feature_of<tag::sum>
+{};
+
+template<typename VariateType, typename VariateTag>
+struct feature_of<tag::sum_of_variates<VariateType, VariateTag> >
+  : feature_of<tag::abstract_sum_of_variates>
+{
+};
+
+}} // namespace boost::accumulators
+
+#endif

+ 196 - 0
library/include/boost/accumulators/statistics/sum_kahan.hpp

@@ -0,0 +1,196 @@
+///////////////////////////////////////////////////////////////////////////////
+// sum_kahan.hpp
+//
+//  Copyright 2010 Gaetano Mendola, 2011 Simon West. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_SUM_KAHAN_HPP_EAN_26_07_2010
+#define BOOST_ACCUMULATORS_STATISTICS_SUM_KAHAN_HPP_EAN_26_07_2010
+
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+#include <boost/accumulators/statistics/sum.hpp>
+#include <boost/accumulators/statistics/weighted_sum_kahan.hpp>
+#include <boost/numeric/conversion/cast.hpp>
+
+namespace boost { namespace accumulators
+{
+
+namespace impl
+{
+
+#if _MSC_VER > 1400
+# pragma float_control(push)
+# pragma float_control(precise, on)
+#endif
+
+template<typename Sample, typename Tag>
+struct sum_kahan_impl
+  : accumulator_base
+{
+    typedef Sample result_type;
+
+    ////////////////////////////////////////////////////////////////////////////
+    // sum_kahan_impl
+    /**
+        @brief Kahan summation algorithm
+
+        The Kahan summation algorithm reduces the numerical error obtained with standard
+        sequential sum.
+
+    */
+    template<typename Args>
+    sum_kahan_impl(Args const & args)
+      : sum(args[parameter::keyword<Tag>::get() | Sample()]),
+        compensation(boost::numeric_cast<Sample>(0.0))
+    {
+    }
+
+    template<typename Args>
+    void 
+#if BOOST_ACCUMULATORS_GCC_VERSION > 40305
+    __attribute__((__optimize__("no-associative-math")))
+#endif
+    operator ()(Args const & args)
+    {
+        const Sample myTmp1 = args[parameter::keyword<Tag>::get()] - this->compensation;
+        const Sample myTmp2 = this->sum + myTmp1;
+        this->compensation = (myTmp2 - this->sum) - myTmp1;
+        this->sum = myTmp2;
+    }
+
+    result_type result(dont_care) const
+    {
+      return this->sum;
+    }
+
+    // make this accumulator serializeable
+    template<class Archive>
+    void serialize(Archive & ar, const unsigned int file_version)
+    { 
+        ar & sum;
+        ar & compensation;
+    }
+
+private:
+    Sample sum;
+    Sample compensation;
+};
+
+#if _MSC_VER > 1400
+# pragma float_control(pop)
+#endif
+
+} // namespace impl
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::sum_kahan
+// tag::sum_of_weights_kahan
+// tag::sum_of_variates_kahan
+//
+namespace tag
+{
+
+    struct sum_kahan
+      : depends_on<>
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef impl::sum_kahan_impl< mpl::_1, tag::sample > impl;
+    };
+
+    struct sum_of_weights_kahan
+      : depends_on<>
+    {
+        typedef mpl::true_ is_weight_accumulator;
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::sum_kahan_impl<mpl::_2, tag::weight> impl;
+    };
+
+    template<typename VariateType, typename VariateTag>
+    struct sum_of_variates_kahan
+      : depends_on<>
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef mpl::always<accumulators::impl::sum_kahan_impl<VariateType, VariateTag> > impl;
+    };
+
+} // namespace tag
+
+///////////////////////////////////////////////////////////////////////////////
+// extract::sum_kahan
+// extract::sum_of_weights_kahan
+// extract::sum_of_variates_kahan
+//
+namespace extract
+{
+    extractor<tag::sum_kahan> const sum_kahan = {};
+    extractor<tag::sum_of_weights_kahan> const sum_of_weights_kahan = {};
+    extractor<tag::abstract_sum_of_variates> const sum_of_variates_kahan = {};
+
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(sum_kahan)
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(sum_of_weights_kahan)
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(sum_of_variates_kahan)
+} // namespace extract
+
+using extract::sum_kahan;
+using extract::sum_of_weights_kahan;
+using extract::sum_of_variates_kahan;
+
+// sum(kahan) -> sum_kahan
+template<>
+struct as_feature<tag::sum(kahan)>
+{
+    typedef tag::sum_kahan type;
+};
+
+// sum_of_weights(kahan) -> sum_of_weights_kahan
+template<>
+struct as_feature<tag::sum_of_weights(kahan)>
+{
+    typedef tag::sum_of_weights_kahan type;
+};
+
+// So that sum_kahan can be automatically substituted with
+// weighted_sum_kahan when the weight parameter is non-void.
+template<>
+struct as_weighted_feature<tag::sum_kahan>
+{
+    typedef tag::weighted_sum_kahan type;
+};
+
+template<>
+struct feature_of<tag::weighted_sum_kahan>
+  : feature_of<tag::sum>
+{};
+
+// for the purposes of feature-based dependency resolution,
+// sum_kahan provides the same feature as sum
+template<>
+struct feature_of<tag::sum_kahan>
+  : feature_of<tag::sum>
+{
+};
+
+// for the purposes of feature-based dependency resolution,
+// sum_of_weights_kahan provides the same feature as sum_of_weights
+template<>
+struct feature_of<tag::sum_of_weights_kahan>
+  : feature_of<tag::sum_of_weights>
+{
+};
+
+template<typename VariateType, typename VariateTag>
+struct feature_of<tag::sum_of_variates_kahan<VariateType, VariateTag> >
+  : feature_of<tag::abstract_sum_of_variates>
+{
+};
+
+}} // namespace boost::accumulators
+
+#endif
+

+ 352 - 0
library/include/boost/accumulators/statistics/tail.hpp

@@ -0,0 +1,352 @@
+///////////////////////////////////////////////////////////////////////////////
+// tail.hpp
+//
+//  Copyright 2005 Eric Niebler, Michael Gauckler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_TAIL_HPP_EAN_28_10_2005
+#define BOOST_ACCUMULATORS_STATISTICS_TAIL_HPP_EAN_28_10_2005
+
+#include <vector>
+#include <functional>
+#include <boost/assert.hpp>
+#include <boost/range.hpp>
+#include <boost/mpl/if.hpp>
+#include <boost/mpl/or.hpp>
+#include <boost/mpl/placeholders.hpp>
+#include <boost/parameter/keyword.hpp>
+#include <boost/iterator/reverse_iterator.hpp>
+#include <boost/iterator/permutation_iterator.hpp>
+#include <boost/accumulators/accumulators_fwd.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/numeric/functional.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/framework/depends_on.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+
+namespace boost { namespace accumulators
+{
+///////////////////////////////////////////////////////////////////////////////
+// cache_size named parameters
+BOOST_PARAMETER_NESTED_KEYWORD(tag, right_tail_cache_size, cache_size)
+BOOST_PARAMETER_NESTED_KEYWORD(tag, left_tail_cache_size, cache_size)
+
+BOOST_ACCUMULATORS_IGNORE_GLOBAL(right_tail_cache_size)
+BOOST_ACCUMULATORS_IGNORE_GLOBAL(left_tail_cache_size)
+
+namespace detail
+{
+    ///////////////////////////////////////////////////////////////////////////////
+    // tail_range
+    /// INTERNAL ONLY
+    ///
+    template<typename ElementIterator, typename IndexIterator>
+    struct tail_range
+    {
+        typedef boost::iterator_range<
+            boost::reverse_iterator<boost::permutation_iterator<ElementIterator, IndexIterator> >
+        > type;
+    };
+
+    ///////////////////////////////////////////////////////////////////////////////
+    // make_tail_range
+    /// INTERNAL ONLY
+    ///
+    template<typename ElementIterator, typename IndexIterator>
+    typename tail_range<ElementIterator, IndexIterator>::type
+    make_tail_range(ElementIterator elem_begin, IndexIterator index_begin, IndexIterator index_end)
+    {
+        return boost::make_iterator_range(
+            boost::make_reverse_iterator(
+                boost::make_permutation_iterator(elem_begin, index_end)
+            )
+          , boost::make_reverse_iterator(
+                boost::make_permutation_iterator(elem_begin, index_begin)
+            )
+        );
+    }
+
+    ///////////////////////////////////////////////////////////////////////////////
+    // stat_assign_visitor
+    /// INTERNAL ONLY
+    ///
+    template<typename Args>
+    struct stat_assign_visitor
+    {
+        stat_assign_visitor(Args const &a, std::size_t i)
+          : args(a)
+          , index(i)
+        {
+        }
+
+        template<typename Stat>
+        void operator ()(Stat &stat) const
+        {
+            stat.assign(this->args, this->index);
+        }
+
+    private:
+        BOOST_DELETED_FUNCTION(stat_assign_visitor &operator =(stat_assign_visitor const &))
+        Args const &args;
+        std::size_t index;
+    };
+
+    ///////////////////////////////////////////////////////////////////////////////
+    // stat_assign
+    /// INTERNAL ONLY
+    ///
+    template<typename Args>
+    inline stat_assign_visitor<Args> const stat_assign(Args const &args, std::size_t index)
+    {
+        return stat_assign_visitor<Args>(args, index);
+    }
+
+    ///////////////////////////////////////////////////////////////////////////////
+    // is_tail_variate_feature
+    /// INTERNAL ONLY
+    ///
+    template<typename Stat, typename LeftRight>
+    struct is_tail_variate_feature
+      : mpl::false_
+    {
+    };
+
+    /// INTERNAL ONLY
+    ///
+    template<typename VariateType, typename VariateTag, typename LeftRight>
+    struct is_tail_variate_feature<tag::tail_variate<VariateType, VariateTag, LeftRight>, LeftRight>
+      : mpl::true_
+    {
+    };
+
+    /// INTERNAL ONLY
+    ///
+    template<typename LeftRight>
+    struct is_tail_variate_feature<tag::tail_weights<LeftRight>, LeftRight>
+      : mpl::true_
+    {
+    };
+
+} // namespace detail
+
+namespace impl
+{
+    ///////////////////////////////////////////////////////////////////////////////
+    // tail_impl
+    template<typename Sample, typename LeftRight>
+    struct tail_impl
+      : accumulator_base
+    {
+        // LeftRight must be either right or left
+        BOOST_MPL_ASSERT((
+            mpl::or_<is_same<LeftRight, right>, is_same<LeftRight, left> >
+        ));
+
+        typedef
+            typename mpl::if_<
+                is_same<LeftRight, right>
+              , numeric::functional::greater<Sample const, Sample const>
+              , numeric::functional::less<Sample const, Sample const>
+            >::type
+        predicate_type;
+
+        // for boost::result_of
+        typedef typename detail::tail_range<
+            typename std::vector<Sample>::const_iterator
+          , std::vector<std::size_t>::iterator
+        >::type result_type;
+
+        template<typename Args>
+        tail_impl(Args const &args)
+          : is_sorted(false)
+          , indices()
+          , samples(args[tag::tail<LeftRight>::cache_size], args[sample | Sample()])
+        {
+            this->indices.reserve(this->samples.size());
+        }
+
+        tail_impl(tail_impl const &that)
+          : is_sorted(that.is_sorted)
+          , indices(that.indices)
+          , samples(that.samples)
+        {
+            this->indices.reserve(this->samples.size());
+        }
+
+        // This just stores the heap and the samples.
+        // In operator()() below, if we are adding a new sample
+        // to the sample cache, we force all the
+        // tail_variates to update also. (It's not
+        // good enough to wait for the accumulator_set to do it
+        // for us because then information about whether a sample
+        // was stored and where is lost, and would need to be
+        // queried at runtime, which would be slow.) This is
+        // implemented as a filtered visitation over the stats,
+        // which we can access because args[accumulator] gives us
+        // all the stats.
+
+        template<typename Args>
+        void operator ()(Args const &args)
+        {
+            if(this->indices.size() < this->samples.size())
+            {
+                this->indices.push_back(this->indices.size());
+                this->assign(args, this->indices.back());
+            }
+            else if(predicate_type()(args[sample], this->samples[this->indices[0]]))
+            {
+                std::pop_heap(this->indices.begin(), this->indices.end(), indirect_cmp(this->samples));
+                this->assign(args, this->indices.back());
+            }
+        }
+
+        result_type result(dont_care) const
+        {
+            if(!this->is_sorted)
+            {
+                // Must use the same predicate here as in push_heap/pop_heap above.
+                std::sort_heap(this->indices.begin(), this->indices.end(), indirect_cmp(this->samples));
+                // sort_heap puts elements in reverse order. Calling std::reverse
+                // turns the sorted sequence back into a valid heap.
+                std::reverse(this->indices.begin(), this->indices.end());
+                this->is_sorted = true;
+            }
+
+            return detail::make_tail_range(
+                this->samples.begin()
+              , this->indices.begin()
+              , this->indices.end()
+            );
+        }
+
+    private:
+
+        struct is_tail_variate
+        {
+            template<typename T>
+            struct apply
+              : detail::is_tail_variate_feature<
+                    typename detail::feature_tag<T>::type
+                  , LeftRight
+                >
+            {};
+        };
+
+        template<typename Args>
+        void assign(Args const &args, std::size_t index)
+        {
+            BOOST_ASSERT(index < this->samples.size());
+            this->samples[index] = args[sample];
+            std::push_heap(this->indices.begin(), this->indices.end(), indirect_cmp(this->samples));
+            this->is_sorted = false;
+            // Tell the tail variates to store their values also
+            args[accumulator].template visit_if<is_tail_variate>(detail::stat_assign(args, index));
+        }
+
+        ///////////////////////////////////////////////////////////////////////////////
+        //
+        struct indirect_cmp
+        {
+            typedef std::size_t first_argument_type;
+            typedef std::size_t second_argument_type;
+            typedef bool result_type;
+
+            indirect_cmp(std::vector<Sample> const &s)
+              : samples(s)
+            {
+            }
+
+            bool operator ()(std::size_t left, std::size_t right) const
+            {
+                return predicate_type()(this->samples[left], this->samples[right]);
+            }
+
+        private:
+            BOOST_DELETED_FUNCTION(indirect_cmp &operator =(indirect_cmp const &))
+            std::vector<Sample> const &samples;
+        };
+
+    public:
+        // make this accumulator serializeable
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int file_version)
+        { 
+            ar & is_sorted;
+            ar & indices;
+            ar & samples;
+        }
+
+    private:
+        mutable bool is_sorted;
+        mutable std::vector<std::size_t> indices;
+        std::vector<Sample> samples;
+    };
+
+} // namespace impl
+
+// TODO The templatized tag::tail below should inherit from the correct named parameter.
+// The following lines provide a workaround, but there must be a better way of doing this.
+template<typename T>
+struct tail_cache_size_named_arg
+{
+};
+template<>
+struct tail_cache_size_named_arg<left>
+  : tag::left_tail_cache_size
+{
+};
+template<>
+struct tail_cache_size_named_arg<right>
+  : tag::right_tail_cache_size
+{
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::tail<>
+//
+namespace tag
+{
+    template<typename LeftRight>
+    struct tail
+      : depends_on<>
+      , tail_cache_size_named_arg<LeftRight>
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::tail_impl<mpl::_1, LeftRight> impl;
+
+        #ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED
+        /// tag::tail<LeftRight>::cache_size named parameter
+        static boost::parameter::keyword<tail_cache_size_named_arg<LeftRight> > const cache_size;
+        #endif
+    };
+
+    struct abstract_tail
+      : depends_on<>
+    {
+    };
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// extract::tail
+//
+namespace extract
+{
+    extractor<tag::abstract_tail> const tail = {};
+
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(tail)
+}
+
+using extract::tail;
+
+template<typename LeftRight>
+struct feature_of<tag::tail<LeftRight> >
+  : feature_of<tag::abstract_tail>
+{
+};
+
+}} // namespace boost::accumulators
+
+#endif

+ 254 - 0
library/include/boost/accumulators/statistics/tail_mean.hpp

@@ -0,0 +1,254 @@
+///////////////////////////////////////////////////////////////////////////////
+// tail_mean.hpp
+//
+//  Copyright 2006 Daniel Egloff, Olivier Gygi. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_TAIL_MEAN_HPP_DE_01_01_2006
+#define BOOST_ACCUMULATORS_STATISTICS_TAIL_MEAN_HPP_DE_01_01_2006
+
+#include <numeric>
+#include <vector>
+#include <limits>
+#include <functional>
+#include <sstream>
+#include <stdexcept>
+#include <boost/throw_exception.hpp>
+#include <boost/parameter/keyword.hpp>
+#include <boost/mpl/placeholders.hpp>
+#include <boost/type_traits/is_same.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/numeric/functional.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+#include <boost/accumulators/statistics/count.hpp>
+#include <boost/accumulators/statistics/tail.hpp>
+#include <boost/accumulators/statistics/tail_quantile.hpp>
+#include <boost/accumulators/statistics/parameters/quantile_probability.hpp>
+
+#ifdef _MSC_VER
+# pragma warning(push)
+# pragma warning(disable: 4127) // conditional expression is constant
+#endif
+
+namespace boost { namespace accumulators
+{
+
+namespace impl
+{
+
+    ///////////////////////////////////////////////////////////////////////////////
+    // coherent_tail_mean_impl
+    //
+    /**
+        @brief Estimation of the coherent tail mean based on order statistics (for both left and right tails)
+
+        The coherent tail mean \f$\widehat{CTM}_{n,\alpha}(X)\f$ is equal to the non-coherent tail mean \f$\widehat{NCTM}_{n,\alpha}(X)\f$
+        plus a correction term that ensures coherence in case of non-continuous distributions.
+
+        \f[
+            \widehat{CTM}_{n,\alpha}^{\mathrm{right}}(X) = \widehat{NCTM}_{n,\alpha}^{\mathrm{right}}(X) +
+            \frac{1}{\lceil n(1-\alpha)\rceil}\hat{q}_{n,\alpha}(X)\left(1 - \alpha - \frac{1}{n}\lceil n(1-\alpha)\rceil \right)
+        \f]
+
+        \f[
+            \widehat{CTM}_{n,\alpha}^{\mathrm{left}}(X) = \widehat{NCTM}_{n,\alpha}^{\mathrm{left}}(X) +
+            \frac{1}{\lceil n\alpha\rceil}\hat{q}_{n,\alpha}(X)\left(\alpha - \frac{1}{n}\lceil n\alpha\rceil \right)
+        \f]
+    */
+    template<typename Sample, typename LeftRight>
+    struct coherent_tail_mean_impl
+      : accumulator_base
+    {
+        typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type float_type;
+        // for boost::result_of
+        typedef float_type result_type;
+
+        coherent_tail_mean_impl(dont_care) {}
+
+        template<typename Args>
+        result_type result(Args const &args) const
+        {
+            std::size_t cnt = count(args);
+
+            std::size_t n = static_cast<std::size_t>(
+                std::ceil(
+                    cnt * ( ( is_same<LeftRight, left>::value ) ? args[quantile_probability] : 1. - args[quantile_probability] )
+                )
+            );
+
+            extractor<tag::non_coherent_tail_mean<LeftRight> > const some_non_coherent_tail_mean = {};
+
+            return some_non_coherent_tail_mean(args)
+                 + numeric::fdiv(quantile(args), n)
+                 * (
+                     ( is_same<LeftRight, left>::value ) ? args[quantile_probability] : 1. - args[quantile_probability]
+                     - numeric::fdiv(n, count(args))
+                   );
+        }
+        
+        // serialization is done by accumulators it depends on
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int file_version) {}
+    };
+
+    ///////////////////////////////////////////////////////////////////////////////
+    // non_coherent_tail_mean_impl
+    //
+    /**
+        @brief Estimation of the (non-coherent) tail mean based on order statistics (for both left and right tails)
+
+        An estimation of the non-coherent tail mean \f$\widehat{NCTM}_{n,\alpha}(X)\f$ is given by the mean of the
+        \f$\lceil n\alpha\rceil\f$ smallest samples (left tail) or the mean of the  \f$\lceil n(1-\alpha)\rceil\f$
+        largest samples (right tail), \f$n\f$ being the total number of samples and \f$\alpha\f$ the quantile level:
+
+        \f[
+            \widehat{NCTM}_{n,\alpha}^{\mathrm{right}}(X) = \frac{1}{\lceil n(1-\alpha)\rceil} \sum_{i=\lceil \alpha n \rceil}^n X_{i:n}
+        \f]
+
+        \f[
+            \widehat{NCTM}_{n,\alpha}^{\mathrm{left}}(X) = \frac{1}{\lceil n\alpha\rceil} \sum_{i=1}^{\lceil \alpha n \rceil} X_{i:n}
+        \f]
+
+        It thus requires the caching of at least the \f$\lceil n\alpha\rceil\f$ smallest or the \f$\lceil n(1-\alpha)\rceil\f$
+        largest samples.
+
+        @param quantile_probability
+    */
+    template<typename Sample, typename LeftRight>
+    struct non_coherent_tail_mean_impl
+      : accumulator_base
+    {
+        typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type float_type;
+        // for boost::result_of
+        typedef float_type result_type;
+
+        non_coherent_tail_mean_impl(dont_care) {}
+
+        template<typename Args>
+        result_type result(Args const &args) const
+        {
+            std::size_t cnt = count(args);
+
+            std::size_t n = static_cast<std::size_t>(
+                std::ceil(
+                    cnt * ( ( is_same<LeftRight, left>::value ) ? args[quantile_probability] : 1. - args[quantile_probability] )
+                )
+            );
+
+            // If n is in a valid range, return result, otherwise return NaN or throw exception
+            if (n <= static_cast<std::size_t>(tail(args).size()))
+                return numeric::fdiv(
+                    std::accumulate(
+                        tail(args).begin()
+                      , tail(args).begin() + n
+                      , Sample(0)
+                    )
+                  , n
+                );
+            else
+            {
+                if (std::numeric_limits<result_type>::has_quiet_NaN)
+                {
+                    return std::numeric_limits<result_type>::quiet_NaN();
+                }
+                else
+                {
+                    std::ostringstream msg;
+                    msg << "index n = " << n << " is not in valid range [0, " << tail(args).size() << ")";
+                    boost::throw_exception(std::runtime_error(msg.str()));
+                    return Sample(0);
+                }
+            }
+        }
+        
+        // serialization is done by accumulators it depends on
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int file_version) {}
+    };
+
+} // namespace impl
+
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::coherent_tail_mean<>
+// tag::non_coherent_tail_mean<>
+//
+namespace tag
+{
+    template<typename LeftRight>
+    struct coherent_tail_mean
+      : depends_on<count, quantile, non_coherent_tail_mean<LeftRight> >
+    {
+        typedef accumulators::impl::coherent_tail_mean_impl<mpl::_1, LeftRight> impl;
+    };
+
+    template<typename LeftRight>
+    struct non_coherent_tail_mean
+      : depends_on<count, tail<LeftRight> >
+    {
+        typedef accumulators::impl::non_coherent_tail_mean_impl<mpl::_1, LeftRight> impl;
+    };
+
+    struct abstract_non_coherent_tail_mean
+      : depends_on<>
+    {
+    };
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// extract::non_coherent_tail_mean;
+// extract::coherent_tail_mean;
+//
+namespace extract
+{
+    extractor<tag::abstract_non_coherent_tail_mean> const non_coherent_tail_mean = {};
+    extractor<tag::tail_mean> const coherent_tail_mean = {};
+
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(non_coherent_tail_mean)
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(coherent_tail_mean)
+}
+
+using extract::non_coherent_tail_mean;
+using extract::coherent_tail_mean;
+
+// for the purposes of feature-based dependency resolution,
+// coherent_tail_mean<LeftRight> provides the same feature as tail_mean
+template<typename LeftRight>
+struct feature_of<tag::coherent_tail_mean<LeftRight> >
+  : feature_of<tag::tail_mean>
+{
+};
+
+template<typename LeftRight>
+struct feature_of<tag::non_coherent_tail_mean<LeftRight> >
+  : feature_of<tag::abstract_non_coherent_tail_mean>
+{
+};
+
+// So that non_coherent_tail_mean can be automatically substituted
+// with weighted_non_coherent_tail_mean when the weight parameter is non-void.
+template<typename LeftRight>
+struct as_weighted_feature<tag::non_coherent_tail_mean<LeftRight> >
+{
+    typedef tag::non_coherent_weighted_tail_mean<LeftRight> type;
+};
+
+template<typename LeftRight>
+struct feature_of<tag::non_coherent_weighted_tail_mean<LeftRight> >
+  : feature_of<tag::non_coherent_tail_mean<LeftRight> >
+{};
+
+// NOTE that non_coherent_tail_mean cannot be feature-grouped with tail_mean,
+// which is the base feature for coherent tail means, since (at least for
+// non-continuous distributions) non_coherent_tail_mean is a different measure!
+
+}} // namespace boost::accumulators
+
+#ifdef _MSC_VER
+# pragma warning(pop)
+#endif
+
+#endif

+ 162 - 0
library/include/boost/accumulators/statistics/tail_quantile.hpp

@@ -0,0 +1,162 @@
+///////////////////////////////////////////////////////////////////////////////
+// tail_quantile.hpp
+//
+//  Copyright 2006 Daniel Egloff, Olivier Gygi. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_TAIL_QUANTILE_HPP_DE_01_01_2006
+#define BOOST_ACCUMULATORS_STATISTICS_TAIL_QUANTILE_HPP_DE_01_01_2006
+
+#include <vector>
+#include <limits>
+#include <functional>
+#include <sstream>
+#include <stdexcept>
+#include <boost/config/no_tr1/cmath.hpp>             // For ceil
+#include <boost/throw_exception.hpp>
+#include <boost/parameter/keyword.hpp>
+#include <boost/mpl/placeholders.hpp>
+#include <boost/mpl/if.hpp>
+#include <boost/type_traits/is_same.hpp>
+#include <boost/accumulators/framework/depends_on.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/numeric/functional.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+#include <boost/accumulators/statistics/tail.hpp>
+#include <boost/accumulators/statistics/count.hpp>
+#include <boost/accumulators/statistics/parameters/quantile_probability.hpp>
+
+#ifdef _MSC_VER
+# pragma warning(push)
+# pragma warning(disable: 4127) // conditional expression is constant
+#endif
+
+namespace boost { namespace accumulators
+{
+
+namespace impl
+{
+    ///////////////////////////////////////////////////////////////////////////////
+    // tail_quantile_impl
+    //  Tail quantile estimation based on order statistics
+    /**
+        @brief Tail quantile estimation based on order statistics (for both left and right tails)
+
+        The estimation of a tail quantile \f$\hat{q}\f$ with level \f$\alpha\f$ based on order statistics requires the
+        caching of at least the \f$\lceil n\alpha\rceil\f$ smallest or the \f$\lceil n(1-\alpha)\rceil\f$ largest samples,
+        \f$n\f$ being the total number of samples. The largest of the \f$\lceil n\alpha\rceil\f$ smallest samples or the
+        smallest of the \f$\lceil n(1-\alpha)\rceil\f$ largest samples provides an estimate for the quantile:
+
+        \f[
+            \hat{q}_{n,\alpha} = X_{\lceil \alpha n \rceil:n}
+        \f]
+
+        @param quantile_probability
+    */
+    template<typename Sample, typename LeftRight>
+    struct tail_quantile_impl
+      : accumulator_base
+    {
+        // for boost::result_of
+        typedef Sample result_type;
+
+        tail_quantile_impl(dont_care) {}
+
+        template<typename Args>
+        result_type result(Args const &args) const
+        {
+            std::size_t cnt = count(args);
+
+            std::size_t n = static_cast<std::size_t>(
+                std::ceil(
+                    cnt * ( ( is_same<LeftRight, left>::value ) ? args[quantile_probability] : 1. - args[quantile_probability] )
+                )
+            );
+
+            // If n is in a valid range, return result, otherwise return NaN or throw exception
+            if ( n < static_cast<std::size_t>(tail(args).size()))
+            {
+               // Note that the cached samples of the left are sorted in ascending order,
+               // whereas the samples of the right tail are sorted in descending order
+               return *(boost::begin(tail(args)) + n - 1);
+            }
+            else
+            {
+                if (std::numeric_limits<result_type>::has_quiet_NaN)
+                {
+                    return std::numeric_limits<result_type>::quiet_NaN();
+                }
+                else
+                {
+                    std::ostringstream msg;
+                    msg << "index n = " << n << " is not in valid range [0, " << tail(args).size() << ")";
+                    boost::throw_exception(std::runtime_error(msg.str()));
+                    return Sample(0);
+                }
+            }
+        }
+        
+        // serialization is done by accumulators it depends on
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int file_version) {}
+    };
+} // namespace impl
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::tail_quantile<>
+//
+namespace tag
+{
+    template<typename LeftRight>
+    struct tail_quantile
+      : depends_on<count, tail<LeftRight> >
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::tail_quantile_impl<mpl::_1, LeftRight> impl;
+    };
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// extract::tail_quantile
+//
+namespace extract
+{
+    extractor<tag::quantile> const tail_quantile = {};
+
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(tail_quantile)
+}
+
+using extract::tail_quantile;
+
+// for the purposes of feature-based dependency resolution,
+// tail_quantile<LeftRight> provide the same feature as quantile
+template<typename LeftRight>
+struct feature_of<tag::tail_quantile<LeftRight> >
+  : feature_of<tag::quantile>
+{
+};
+
+// So that tail_quantile can be automatically substituted with
+// weighted_tail_quantile when the weight parameter is non-void.
+template<typename LeftRight>
+struct as_weighted_feature<tag::tail_quantile<LeftRight> >
+{
+    typedef tag::weighted_tail_quantile<LeftRight> type;
+};
+
+template<typename LeftRight>
+struct feature_of<tag::weighted_tail_quantile<LeftRight> >
+  : feature_of<tag::tail_quantile<LeftRight> >
+{};
+
+}} // namespace boost::accumulators
+
+#ifdef _MSC_VER
+# pragma warning(pop)
+#endif
+
+#endif

+ 150 - 0
library/include/boost/accumulators/statistics/tail_variate.hpp

@@ -0,0 +1,150 @@
+///////////////////////////////////////////////////////////////////////////////
+// tail_variate.hpp
+//
+//  Copyright 2005 Eric Niebler, Michael Gauckler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_STAT_STATISTICS_TAIL_VARIATE_HPP_EAN_28_10_2005
+#define BOOST_STAT_STATISTICS_TAIL_VARIATE_HPP_EAN_28_10_2005
+
+#include <boost/range.hpp>
+#include <boost/mpl/always.hpp>
+#include <boost/mpl/placeholders.hpp>
+#include <boost/iterator/reverse_iterator.hpp>
+#include <boost/iterator/permutation_iterator.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/framework/depends_on.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+#include <boost/accumulators/statistics/tail.hpp>
+#include <boost/serialization/vector.hpp>
+
+namespace boost { namespace accumulators
+{
+
+namespace impl
+{
+    ///////////////////////////////////////////////////////////////////////////////
+    // tail_variate_impl
+    template<typename VariateType, typename VariateTag, typename LeftRight>
+    struct tail_variate_impl
+      : accumulator_base
+    {
+        // for boost::result_of
+        typedef
+            typename detail::tail_range<
+                typename std::vector<VariateType>::const_iterator
+              , std::vector<std::size_t>::iterator
+            >::type
+        result_type;
+
+        template<typename Args>
+        tail_variate_impl(Args const &args)
+          : variates(args[tag::tail<LeftRight>::cache_size], args[parameter::keyword<VariateTag>::get() | VariateType()])
+        {
+        }
+
+        template<typename Args>
+        void assign(Args const &args, std::size_t index)
+        {
+            this->variates[index] = args[parameter::keyword<VariateTag>::get()];
+        }
+
+        template<typename Args>
+        result_type result(Args const &args) const
+        {
+            // getting the order result causes the indices vector to be sorted.
+            extractor<tag::tail<LeftRight> > const some_tail = {};
+            return this->do_result(some_tail(args));
+        }
+
+    private:
+        template<typename TailRng>
+        result_type do_result(TailRng const &rng) const
+        {
+            return detail::make_tail_range(
+                this->variates.begin()
+              , rng.end().base().base()   // the index iterator
+              , rng.begin().base().base() // (begin and end reversed because these are reverse iterators)
+            );
+        }
+
+        // make this accumulator serializeable
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int file_version)
+        { 
+            ar & variates;
+        }
+
+    private:
+        std::vector<VariateType> variates;
+    };
+
+} // namespace impl
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::tail_variate<>
+//
+namespace tag
+{
+    template<typename VariateType, typename VariateTag, typename LeftRight>
+    struct tail_variate
+      : depends_on<tail<LeftRight> >
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef mpl::always<accumulators::impl::tail_variate_impl<VariateType, VariateTag, LeftRight> > impl;
+    };
+
+    struct abstract_tail_variate
+      : depends_on<>
+    {
+    };
+
+    template<typename LeftRight>
+    struct tail_weights
+      : depends_on<tail<LeftRight> >
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::tail_variate_impl<mpl::_2, tag::weight, LeftRight> impl;
+    };
+
+    struct abstract_tail_weights
+      : depends_on<>
+    {
+    };
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// extract::tail_variate
+// extract::tail_weights
+//
+namespace extract
+{
+    extractor<tag::abstract_tail_variate> const tail_variate = {};
+    extractor<tag::abstract_tail_weights> const tail_weights = {};
+
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(tail_variate)
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(tail_weights)
+}
+
+using extract::tail_variate;
+using extract::tail_weights;
+
+template<typename VariateType, typename VariateTag, typename LeftRight>
+struct feature_of<tag::tail_variate<VariateType, VariateTag, LeftRight> >
+  : feature_of<tag::abstract_tail_variate>
+{
+};
+
+template<typename LeftRight>
+struct feature_of<tag::tail_weights<LeftRight> >
+{
+    typedef tag::abstract_tail_weights type;
+};
+
+}} // namespace boost::accumulators
+
+#endif

+ 270 - 0
library/include/boost/accumulators/statistics/tail_variate_means.hpp

@@ -0,0 +1,270 @@
+///////////////////////////////////////////////////////////////////////////////
+// tail_variate_means.hpp
+//
+//  Copyright 2006 Daniel Egloff, Olivier Gygi. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_TAIL_VARIATE_MEANS_HPP_DE_01_01_2006
+#define BOOST_ACCUMULATORS_STATISTICS_TAIL_VARIATE_MEANS_HPP_DE_01_01_2006
+
+#include <numeric>
+#include <vector>
+#include <limits>
+#include <functional>
+#include <sstream>
+#include <stdexcept>
+#include <boost/throw_exception.hpp>
+#include <boost/parameter/keyword.hpp>
+#include <boost/mpl/placeholders.hpp>
+#include <boost/type_traits/is_same.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/numeric/functional.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+#include <boost/accumulators/statistics/tail.hpp>
+#include <boost/accumulators/statistics/tail_variate.hpp>
+#include <boost/accumulators/statistics/tail_mean.hpp>
+#include <boost/accumulators/statistics/parameters/quantile_probability.hpp>
+#include <boost/serialization/vector.hpp>
+
+#ifdef _MSC_VER
+# pragma warning(push)
+# pragma warning(disable: 4127) // conditional expression is constant
+#endif
+
+namespace boost { namespace accumulators
+{
+
+namespace impl
+{
+    /**
+        @brief Estimation of the absolute and relative tail variate means (for both left and right tails)
+
+        For all \f$j\f$-th variates associated to the \f$\lceil n(1-\alpha)\rceil\f$ largest samples (or the
+        \f$\lceil n(1-\alpha)\rceil\f$ smallest samples in case of the left tail), the absolute tail means
+        \f$\widehat{ATM}_{n,\alpha}(X, j)\f$ are computed and returned as an iterator range. Alternatively,
+        the relative tail means \f$\widehat{RTM}_{n,\alpha}(X, j)\f$ are returned, which are the absolute
+        tail means normalized with the (non-coherent) sample tail mean \f$\widehat{NCTM}_{n,\alpha}(X)\f$.
+
+        \f[
+            \widehat{ATM}_{n,\alpha}^{\mathrm{right}}(X, j) =
+                \frac{1}{\lceil n(1-\alpha) \rceil}
+                \sum_{i=\lceil \alpha n \rceil}^n \xi_{j,i}
+        \f]
+
+        \f[
+            \widehat{ATM}_{n,\alpha}^{\mathrm{left}}(X, j) =
+                \frac{1}{\lceil n\alpha \rceil}
+                \sum_{i=1}^{\lceil n\alpha \rceil} \xi_{j,i}
+        \f]
+
+        \f[
+            \widehat{RTM}_{n,\alpha}^{\mathrm{right}}(X, j) =
+                \frac{\sum_{i=\lceil n\alpha \rceil}^n \xi_{j,i}}
+            {\lceil n(1-\alpha)\rceil\widehat{NCTM}_{n,\alpha}^{\mathrm{right}}(X)}
+        \f]
+
+        \f[
+            \widehat{RTM}_{n,\alpha}^{\mathrm{left}}(X, j) =
+                \frac{\sum_{i=1}^{\lceil n\alpha \rceil} \xi_{j,i}}
+            {\lceil n\alpha\rceil\widehat{NCTM}_{n,\alpha}^{\mathrm{left}}(X)}
+        \f]
+    */
+
+    ///////////////////////////////////////////////////////////////////////////////
+    // tail_variate_means_impl
+    //  by default: absolute tail_variate_means
+    template<typename Sample, typename Impl, typename LeftRight, typename VariateTag>
+    struct tail_variate_means_impl
+      : accumulator_base
+    {
+        typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type float_type;
+        typedef std::vector<float_type> array_type;
+        // for boost::result_of
+        typedef iterator_range<typename array_type::iterator> result_type;
+
+        tail_variate_means_impl(dont_care) {}
+
+        template<typename Args>
+        result_type result(Args const &args) const
+        {
+            std::size_t cnt = count(args);
+
+            std::size_t n = static_cast<std::size_t>(
+                std::ceil(
+                    cnt * ( ( is_same<LeftRight, left>::value ) ? args[quantile_probability] : 1. - args[quantile_probability] )
+                )
+            );
+
+            std::size_t num_variates = tail_variate(args).begin()->size();
+
+            this->tail_means_.clear();
+            this->tail_means_.resize(num_variates, Sample(0));
+
+            // If n is in a valid range, return result, otherwise return NaN or throw exception
+            if (n < static_cast<std::size_t>(tail(args).size()))
+            {
+                this->tail_means_ = std::accumulate(
+                    tail_variate(args).begin()
+                  , tail_variate(args).begin() + n
+                  , this->tail_means_
+                  , numeric::plus
+                );
+
+                float_type factor = n * ( (is_same<Impl, relative>::value) ? non_coherent_tail_mean(args) : 1. );
+
+                std::transform(
+                    this->tail_means_.begin()
+                  , this->tail_means_.end()
+                  , this->tail_means_.begin()
+#ifdef BOOST_NO_CXX98_BINDERS
+                  , std::bind(std::divides<float_type>(), std::placeholders::_1, factor)
+#else
+                  , std::bind2nd(std::divides<float_type>(), factor)
+#endif
+                );
+            }
+            else
+            {
+                if (std::numeric_limits<float_type>::has_quiet_NaN)
+                {
+                    std::fill(
+                        this->tail_means_.begin()
+                      , this->tail_means_.end()
+                      , std::numeric_limits<float_type>::quiet_NaN()
+                    );
+                }
+                else
+                {
+                    std::ostringstream msg;
+                    msg << "index n = " << n << " is not in valid range [0, " << tail(args).size() << ")";
+                    boost::throw_exception(std::runtime_error(msg.str()));
+                }
+            }
+            return make_iterator_range(this->tail_means_);
+        }
+
+        // make this accumulator serializeable
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int file_version)
+        { 
+            ar & tail_means_;
+        }
+
+    private:
+
+        mutable array_type tail_means_;
+
+    };
+
+} // namespace impl
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::absolute_tail_variate_means
+// tag::relative_tail_variate_means
+//
+namespace tag
+{
+    template<typename LeftRight, typename VariateType, typename VariateTag>
+    struct absolute_tail_variate_means
+      : depends_on<count, non_coherent_tail_mean<LeftRight>, tail_variate<VariateType, VariateTag, LeftRight> >
+    {
+        typedef accumulators::impl::tail_variate_means_impl<mpl::_1, absolute, LeftRight, VariateTag> impl;
+    };
+    template<typename LeftRight, typename VariateType, typename VariateTag>
+    struct relative_tail_variate_means
+      : depends_on<count, non_coherent_tail_mean<LeftRight>, tail_variate<VariateType, VariateTag, LeftRight> >
+    {
+        typedef accumulators::impl::tail_variate_means_impl<mpl::_1, relative, LeftRight, VariateTag> impl;
+    };
+    struct abstract_absolute_tail_variate_means
+      : depends_on<>
+    {
+    };
+    struct abstract_relative_tail_variate_means
+      : depends_on<>
+    {
+    };
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// extract::tail_variate_means
+// extract::relative_tail_variate_means
+//
+namespace extract
+{
+    extractor<tag::abstract_absolute_tail_variate_means> const tail_variate_means = {};
+    extractor<tag::abstract_relative_tail_variate_means> const relative_tail_variate_means = {};
+
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(tail_variate_means)
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(relative_tail_variate_means)
+}
+
+using extract::tail_variate_means;
+using extract::relative_tail_variate_means;
+
+// tail_variate_means<LeftRight, VariateType, VariateTag>(absolute) -> absolute_tail_variate_means<LeftRight, VariateType, VariateTag>
+template<typename LeftRight, typename VariateType, typename VariateTag>
+struct as_feature<tag::tail_variate_means<LeftRight, VariateType, VariateTag>(absolute)>
+{
+    typedef tag::absolute_tail_variate_means<LeftRight, VariateType, VariateTag> type;
+};
+
+// tail_variate_means<LeftRight, VariateType, VariateTag>(relative) ->relative_tail_variate_means<LeftRight, VariateType, VariateTag>
+template<typename LeftRight, typename VariateType, typename VariateTag>
+struct as_feature<tag::tail_variate_means<LeftRight, VariateType, VariateTag>(relative)>
+{
+    typedef tag::relative_tail_variate_means<LeftRight, VariateType, VariateTag> type;
+};
+
+// Provides non-templatized extractor
+template<typename LeftRight, typename VariateType, typename VariateTag>
+struct feature_of<tag::absolute_tail_variate_means<LeftRight, VariateType, VariateTag> >
+  : feature_of<tag::abstract_absolute_tail_variate_means>
+{
+};
+
+// Provides non-templatized extractor
+template<typename LeftRight, typename VariateType, typename VariateTag>
+struct feature_of<tag::relative_tail_variate_means<LeftRight, VariateType, VariateTag> >
+  : feature_of<tag::abstract_relative_tail_variate_means>
+{
+};
+
+// So that absolute_tail_means can be automatically substituted
+// with absolute_weighted_tail_means when the weight parameter is non-void.
+template<typename LeftRight, typename VariateType, typename VariateTag>
+struct as_weighted_feature<tag::absolute_tail_variate_means<LeftRight, VariateType, VariateTag> >
+{
+    typedef tag::absolute_weighted_tail_variate_means<LeftRight, VariateType, VariateTag> type;
+};
+
+template<typename LeftRight, typename VariateType, typename VariateTag>
+struct feature_of<tag::absolute_weighted_tail_variate_means<LeftRight, VariateType, VariateTag> >
+  : feature_of<tag::absolute_tail_variate_means<LeftRight, VariateType, VariateTag> >
+{
+};
+
+// So that relative_tail_means can be automatically substituted
+// with relative_weighted_tail_means when the weight parameter is non-void.
+template<typename LeftRight, typename VariateType, typename VariateTag>
+struct as_weighted_feature<tag::relative_tail_variate_means<LeftRight, VariateType, VariateTag> >
+{
+    typedef tag::relative_weighted_tail_variate_means<LeftRight, VariateType, VariateTag> type;
+};
+
+template<typename LeftRight, typename VariateType, typename VariateTag>
+struct feature_of<tag::relative_weighted_tail_variate_means<LeftRight, VariateType, VariateTag> >
+  : feature_of<tag::relative_tail_variate_means<LeftRight, VariateType, VariateTag> >
+{
+};
+
+}} // namespace boost::accumulators
+
+#ifdef _MSC_VER
+# pragma warning(pop)
+#endif
+
+#endif

+ 70 - 0
library/include/boost/accumulators/statistics/times2_iterator.hpp

@@ -0,0 +1,70 @@
+///////////////////////////////////////////////////////////////////////////////
+// times2_iterator.hpp
+//
+//  Copyright 2006 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_TIMES2_ITERATOR_HPP_DE_01_01_2006
+#define BOOST_ACCUMULATORS_STATISTICS_TIMES2_ITERATOR_HPP_DE_01_01_2006
+
+#include <functional>
+#include <boost/detail/workaround.hpp>
+#include <boost/range/begin.hpp>
+#include <boost/range/end.hpp>
+#include <boost/range/iterator_range.hpp>
+#include <boost/iterator/transform_iterator.hpp>
+#include <boost/iterator/counting_iterator.hpp>
+#include <boost/iterator/permutation_iterator.hpp>
+
+namespace boost { namespace accumulators
+{
+
+namespace detail
+{
+    typedef transform_iterator<
+#ifdef BOOST_NO_CXX98_BINDERS
+        decltype(std::bind(std::multiplies<std::size_t>(), 2, std::placeholders::_1))
+#else
+        std::binder1st<std::multiplies<std::size_t> >
+#endif
+      , counting_iterator<std::size_t>
+    > times2_iterator;
+
+    inline times2_iterator make_times2_iterator(std::size_t i)
+    {
+        return make_transform_iterator(
+            make_counting_iterator(i)
+#ifdef BOOST_NO_CXX98_BINDERS
+          , std::bind(std::multiplies<std::size_t>(), 2, std::placeholders::_1)
+#else
+          , std::bind1st(std::multiplies<std::size_t>(), 2)
+#endif
+        );
+    }
+
+    ///////////////////////////////////////////////////////////////////////////////
+    // lvalue_index_iterator
+    template<typename Base>
+    struct lvalue_index_iterator
+      : Base
+    {
+        lvalue_index_iterator()
+          : Base()
+        {}
+
+        lvalue_index_iterator(Base base)
+          : Base(base)
+        {
+        }
+
+        typename Base::reference operator [](typename Base::difference_type n) const
+        {
+            return *(*this + n);
+        }
+    };
+} // namespace detail
+
+}}
+
+#endif

+ 247 - 0
library/include/boost/accumulators/statistics/variance.hpp

@@ -0,0 +1,247 @@
+///////////////////////////////////////////////////////////////////////////////
+// variance.hpp
+//
+//  Copyright 2005 Daniel Egloff, Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_VARIANCE_HPP_EAN_28_10_2005
+#define BOOST_ACCUMULATORS_STATISTICS_VARIANCE_HPP_EAN_28_10_2005
+
+#include <boost/mpl/placeholders.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/numeric/functional.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/framework/depends_on.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+#include <boost/accumulators/statistics/count.hpp>
+#include <boost/accumulators/statistics/sum.hpp>
+#include <boost/accumulators/statistics/mean.hpp>
+#include <boost/accumulators/statistics/moment.hpp>
+
+namespace boost { namespace accumulators
+{
+
+namespace impl
+{
+    //! Lazy calculation of variance.
+    /*!
+        Default sample variance implementation based on the second moment \f$ M_n^{(2)} \f$ moment<2>, mean and count.
+        \f[
+            \sigma_n^2 = M_n^{(2)} - \mu_n^2.
+        \f]
+        where
+        \f[
+            \mu_n = \frac{1}{n} \sum_{i = 1}^n x_i.
+        \f]
+        is the estimate of the sample mean and \f$n\f$ is the number of samples.
+    */
+    template<typename Sample, typename MeanFeature>
+    struct lazy_variance_impl
+      : accumulator_base
+    {
+        // for boost::result_of
+        typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type result_type;
+
+        lazy_variance_impl(dont_care) {}
+
+        template<typename Args>
+        result_type result(Args const &args) const
+        {
+            extractor<MeanFeature> mean;
+            result_type tmp = mean(args);
+            return accumulators::moment<2>(args) - tmp * tmp;
+        }
+        
+        // serialization is done by accumulators it depends on
+        template<class Archive>
+        void serialize(Archive & /* ar */, const unsigned int /* file_version */) {}
+    };
+
+    //! Iterative calculation of variance.
+    /*!
+        Iterative calculation of sample variance \f$\sigma_n^2\f$ according to the formula
+        \f[
+            \sigma_n^2 = \frac{1}{n} \sum_{i = 1}^n (x_i - \mu_n)^2 = \frac{n-1}{n} \sigma_{n-1}^2 + \frac{1}{n-1}(x_n - \mu_n)^2.
+        \f]
+        where
+        \f[
+            \mu_n = \frac{1}{n} \sum_{i = 1}^n x_i.
+        \f]
+        is the estimate of the sample mean and \f$n\f$ is the number of samples.
+
+        Note that the sample variance is not defined for \f$n <= 1\f$.
+
+        A simplification can be obtained by the approximate recursion
+        \f[
+            \sigma_n^2 \approx \frac{n-1}{n} \sigma_{n-1}^2 + \frac{1}{n}(x_n - \mu_n)^2.
+        \f]
+        because the difference
+        \f[
+            \left(\frac{1}{n-1} - \frac{1}{n}\right)(x_n - \mu_n)^2 = \frac{1}{n(n-1)}(x_n - \mu_n)^2.
+        \f]
+        converges to zero as \f$n \rightarrow \infty\f$. However, for small \f$ n \f$ the difference
+        can be non-negligible.
+    */
+    template<typename Sample, typename MeanFeature, typename Tag>
+    struct variance_impl
+      : accumulator_base
+    {
+        // for boost::result_of
+        typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type result_type;
+
+        template<typename Args>
+        variance_impl(Args const &args)
+          : variance(numeric::fdiv(args[sample | Sample()], numeric::one<std::size_t>::value))
+        {
+        }
+
+        template<typename Args>
+        void operator ()(Args const &args)
+        {
+            std::size_t cnt = count(args);
+
+            if(cnt > 1)
+            {
+                extractor<MeanFeature> mean;
+                result_type tmp = args[parameter::keyword<Tag>::get()] - mean(args);
+                this->variance =
+                    numeric::fdiv(this->variance * (cnt - 1), cnt)
+                  + numeric::fdiv(tmp * tmp, cnt - 1);
+            }
+        }
+
+        result_type result(dont_care) const
+        {
+            return this->variance;
+        }
+
+        // make this accumulator serializeable
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int /* file_version */)
+        {
+            ar & variance;
+        }
+
+    private:
+        result_type variance;
+    };
+
+} // namespace impl
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::variance
+// tag::immediate_variance
+//
+namespace tag
+{
+    struct lazy_variance
+      : depends_on<moment<2>, mean>
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::lazy_variance_impl<mpl::_1, mean> impl;
+    };
+
+    struct variance
+      : depends_on<count, immediate_mean>
+    {
+        /// INTERNAL ONLY
+        ///
+        typedef accumulators::impl::variance_impl<mpl::_1, mean, sample> impl;
+    };
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// extract::lazy_variance
+// extract::variance
+//
+namespace extract
+{
+    extractor<tag::lazy_variance> const lazy_variance = {};
+    extractor<tag::variance> const variance = {};
+
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(lazy_variance)
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(variance)
+}
+
+using extract::lazy_variance;
+using extract::variance;
+
+// variance(lazy) -> lazy_variance
+template<>
+struct as_feature<tag::variance(lazy)>
+{
+    typedef tag::lazy_variance type;
+};
+
+// variance(immediate) -> variance
+template<>
+struct as_feature<tag::variance(immediate)>
+{
+    typedef tag::variance type;
+};
+
+// for the purposes of feature-based dependency resolution,
+// immediate_variance provides the same feature as variance
+template<>
+struct feature_of<tag::lazy_variance>
+  : feature_of<tag::variance>
+{
+};
+
+// So that variance can be automatically substituted with
+// weighted_variance when the weight parameter is non-void.
+template<>
+struct as_weighted_feature<tag::variance>
+{
+    typedef tag::weighted_variance type;
+};
+
+// for the purposes of feature-based dependency resolution,
+// weighted_variance provides the same feature as variance
+template<>
+struct feature_of<tag::weighted_variance>
+  : feature_of<tag::variance>
+{
+};
+
+// So that immediate_variance can be automatically substituted with
+// immediate_weighted_variance when the weight parameter is non-void.
+template<>
+struct as_weighted_feature<tag::lazy_variance>
+{
+    typedef tag::lazy_weighted_variance type;
+};
+
+// for the purposes of feature-based dependency resolution,
+// immediate_weighted_variance provides the same feature as immediate_variance
+template<>
+struct feature_of<tag::lazy_weighted_variance>
+  : feature_of<tag::lazy_variance>
+{
+};
+
+////////////////////////////////////////////////////////////////////////////
+//// droppable_accumulator<variance_impl>
+////  need to specialize droppable lazy variance to cache the result at the
+////  point the accumulator is dropped.
+///// INTERNAL ONLY
+/////
+//template<typename Sample, typename MeanFeature>
+//struct droppable_accumulator<impl::variance_impl<Sample, MeanFeature> >
+//  : droppable_accumulator_base<
+//        with_cached_result<impl::variance_impl<Sample, MeanFeature> >
+//    >
+//{
+//    template<typename Args>
+//    droppable_accumulator(Args const &args)
+//      : droppable_accumulator::base(args)
+//    {
+//    }
+//};
+
+}} // namespace boost::accumulators
+
+#endif

+ 25 - 0
library/include/boost/accumulators/statistics/variates/covariate.hpp

@@ -0,0 +1,25 @@
+///////////////////////////////////////////////////////////////////////////////
+// weight.hpp
+//
+//  Copyright 2005 Eric Niebler. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_VARIATES_COVARIATE_HPP_EAN_03_11_2005
+#define BOOST_ACCUMULATORS_STATISTICS_VARIATES_COVARIATE_HPP_EAN_03_11_2005
+
+#include <boost/parameter/keyword.hpp>
+#include <boost/accumulators/accumulators_fwd.hpp>
+
+namespace boost { namespace accumulators
+{
+
+BOOST_PARAMETER_KEYWORD(tag, covariate1)
+BOOST_PARAMETER_KEYWORD(tag, covariate2)
+
+BOOST_ACCUMULATORS_IGNORE_GLOBAL(covariate1)
+BOOST_ACCUMULATORS_IGNORE_GLOBAL(covariate2)
+
+}} // namespace boost::accumulators
+
+#endif

+ 140 - 0
library/include/boost/accumulators/statistics/weighted_covariance.hpp

@@ -0,0 +1,140 @@
+///////////////////////////////////////////////////////////////////////////////
+// weighted_covariance.hpp
+//
+//  Copyright 2006 Daniel Egloff, Olivier Gygi. Distributed under the Boost
+//  Software License, Version 1.0. (See accompanying file
+//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+#ifndef BOOST_ACCUMULATORS_STATISTICS_WEIGHTED_COVARIANCE_HPP_DE_01_01_2006
+#define BOOST_ACCUMULATORS_STATISTICS_WEIGHTED_COVARIANCE_HPP_DE_01_01_2006
+
+#include <vector>
+#include <limits>
+#include <numeric>
+#include <functional>
+#include <complex>
+#include <boost/mpl/assert.hpp>
+#include <boost/mpl/bool.hpp>
+#include <boost/range.hpp>
+#include <boost/parameter/keyword.hpp>
+#include <boost/mpl/placeholders.hpp>
+#include <boost/numeric/ublas/io.hpp>
+#include <boost/numeric/ublas/matrix.hpp>
+#include <boost/type_traits/is_scalar.hpp>
+#include <boost/type_traits/is_same.hpp>
+#include <boost/accumulators/framework/accumulator_base.hpp>
+#include <boost/accumulators/framework/extractor.hpp>
+#include <boost/accumulators/numeric/functional.hpp>
+#include <boost/accumulators/framework/parameters/sample.hpp>
+#include <boost/accumulators/statistics_fwd.hpp>
+#include <boost/accumulators/statistics/count.hpp>
+#include <boost/accumulators/statistics/covariance.hpp> // for numeric::outer_product() and type traits
+#include <boost/accumulators/statistics/weighted_mean.hpp>
+
+namespace boost { namespace accumulators
+{
+
+namespace impl
+{
+    ///////////////////////////////////////////////////////////////////////////////
+    // weighted_covariance_impl
+    //
+    /**
+        @brief Weighted Covariance Estimator
+
+        An iterative Monte Carlo estimator for the weighted covariance \f$\mathrm{Cov}(X,X')\f$, where \f$X\f$ is a sample
+        and \f$X'\f$ a variate, is given by:
+
+        \f[
+            \hat{c}_n = \frac{\bar{w}_n-w_n}{\bar{w}_n} \hat{c}_{n-1} + \frac{w_n}{\bar{w}_n-w_n}(X_n - \hat{\mu}_n)(X_n' - \hat{\mu}_n'),
+            \quad n\ge2,\quad\hat{c}_1 = 0,
+        \f]
+
+        \f$\hat{\mu}_n\f$ and \f$\hat{\mu}_n'\f$ being the weighted means of the samples and variates and
+        \f$\bar{w}_n\f$ the sum of the \f$n\f$ first weights \f$w_i\f$.
+    */
+    template<typename Sample, typename Weight, typename VariateType, typename VariateTag>
+    struct weighted_covariance_impl
+      : accumulator_base
+    {
+        typedef typename numeric::functional::multiplies<Weight, typename numeric::functional::fdiv<Sample, std::size_t>::result_type>::result_type weighted_sample_type;
+        typedef typename numeric::functional::multiplies<Weight, typename numeric::functional::fdiv<VariateType, std::size_t>::result_type>::result_type weighted_variate_type;
+        // for boost::result_of
+        typedef typename numeric::functional::outer_product<weighted_sample_type, weighted_variate_type>::result_type result_type;
+
+        template<typename Args>
+        weighted_covariance_impl(Args const &args)
+          : cov_(
+                numeric::outer_product(
+                    numeric::fdiv(args[sample | Sample()], (std::size_t)1)
+                      * numeric::one<Weight>::value
+                  , numeric::fdiv(args[parameter::keyword<VariateTag>::get() | VariateType()], (std::size_t)1)
+                      * numeric::one<Weight>::value
+                )
+            )
+        {
+        }
+
+        template<typename Args>
+        void operator ()(Args const &args)
+        {
+            std::size_t cnt = count(args);
+
+            if (cnt > 1)
+            {
+                extractor<tag::weighted_mean_of_variates<VariateType, VariateTag> > const some_weighted_mean_of_variates = {};
+
+                this->cov_ = this->cov_ * (sum_of_weights(args) - args[weight]) / sum_of_weights(args)
+                           + numeric::outer_product(
+                                 some_weighted_mean_of_variates(args) - args[parameter::keyword<VariateTag>::get()]
+                               , weighted_mean(args) - args[sample]
+                             ) * args[weight] / (sum_of_weights(args) - args[weight]);
+            }
+        }
+
+        result_type result(dont_care) const
+        {
+            return this->cov_;
+        }
+
+        // make this accumulator serializeable
+        template<class Archive>
+        void serialize(Archive & ar, const unsigned int file_version)
+        { 
+            ar & cov_;
+        }
+
+    private:
+        result_type cov_;
+    };
+
+} // namespace impl
+
+///////////////////////////////////////////////////////////////////////////////
+// tag::weighted_covariance
+//
+namespace tag
+{
+    template<typename VariateType, typename VariateTag>
+    struct weighted_covariance
+      : depends_on<count, sum_of_weights, weighted_mean, weighted_mean_of_variates<VariateType, VariateTag> >
+    {
+        typedef accumulators::impl::weighted_covariance_impl<mpl::_1, mpl::_2, VariateType, VariateTag> impl;
+    };
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// extract::weighted_covariance
+//
+namespace extract
+{
+    extractor<tag::abstract_covariance> const weighted_covariance = {};
+
+    BOOST_ACCUMULATORS_IGNORE_GLOBAL(weighted_covariance)
+}
+
+using extract::weighted_covariance;
+
+}} // namespace boost::accumulators
+
+#endif

部分文件因为文件数量过多而无法显示