[libosmium] 01/01: Imported Upstream version 2.12.0

Bas Couwenberg sebastic at debian.org
Tue Mar 7 18:01:39 UTC 2017


This is an automated email from the git hooks/post-receive script.

sebastic pushed a commit to branch upstream
in repository libosmium.

commit d65850aeb70310b9a953d685fa00ae3d948b7f1c
Author: Bas Couwenberg <sebastic at xs4all.nl>
Date:   Tue Mar 7 18:32:25 2017 +0100

    Imported Upstream version 2.12.0
---
 CHANGELOG.md                                       |   60 +-
 CMakeLists.txt                                     |    5 +-
 benchmarks/CMakeLists.txt                          |    1 +
 cmake/FindOsmium.cmake                             |   14 +
 examples/CMakeLists.txt                            |    1 +
 include/osmium/area/assembler.hpp                  | 1355 +-----------
 include/osmium/area/assembler_config.hpp           |  152 ++
 include/osmium/area/detail/basic_assembler.hpp     | 1204 +++++++++++
 include/osmium/area/detail/segment_list.hpp        |   28 +-
 include/osmium/area/detail/vector.hpp              |    2 +-
 include/osmium/area/geom_assembler.hpp             |  131 ++
 include/osmium/area/problem_reporter.hpp           |    9 +
 include/osmium/area/problem_reporter_exception.hpp |   42 +-
 include/osmium/area/problem_reporter_ogr.hpp       |   12 +-
 include/osmium/area/problem_reporter_stream.hpp    |    5 +
 include/osmium/area/stats.hpp                      |    5 +-
 include/osmium/builder/builder.hpp                 |   18 +-
 include/osmium/builder/builder_helper.hpp          |    6 +-
 include/osmium/builder/osm_object_builder.hpp      |   20 +-
 include/osmium/geom/factory.hpp                    |    2 +-
 include/osmium/geom/mercator_projection.hpp        |    6 +-
 include/osmium/geom/projection.hpp                 |   54 +-
 include/osmium/handler/node_locations_for_ways.hpp |   14 +-
 include/osmium/index/id_set.hpp                    |    1 +
 include/osmium/index/map/sparse_mem_table.hpp      |    2 +-
 .../osmium/{version.hpp => index/nwr_array.hpp}    |   31 +-
 include/osmium/index/relations_map.hpp             |  280 ++-
 include/osmium/io/detail/pbf_input_format.hpp      |    2 +-
 include/osmium/io/detail/pbf_output_format.hpp     |    1 -
 include/osmium/io/detail/protobuf_tags.hpp         |    2 +-
 include/osmium/io/detail/string_util.hpp           |    2 +-
 include/osmium/io/detail/write_thread.hpp          |    2 +-
 include/osmium/io/detail/xml_input_format.hpp      |    6 +-
 include/osmium/io/detail/xml_output_format.hpp     |    1 -
 include/osmium/io/file_compression.hpp             |    9 +-
 include/osmium/io/file_format.hpp                  |    9 +-
 include/osmium/io/reader.hpp                       |    8 +-
 include/osmium/object_pointer_collection.hpp       |   24 +-
 include/osmium/osm/crc.hpp                         |    2 +-
 include/osmium/osm/item_type.hpp                   |   21 +-
 include/osmium/relations/collector.hpp             |   11 -
 include/osmium/tags/filter.hpp                     |   39 +-
 include/osmium/tags/matcher.hpp                    |  123 ++
 include/osmium/tags/regex_filter.hpp               |    5 +-
 include/osmium/tags/taglist.hpp                    |   13 +-
 include/osmium/tags/tags_filter.hpp                |  146 ++
 include/osmium/thread/function_wrapper.hpp         |    2 +-
 include/osmium/thread/pool.hpp                     |    2 +-
 include/osmium/thread/util.hpp                     |    2 +-
 include/osmium/util/file.hpp                       |   11 +-
 include/osmium/util/memory_mapping.hpp             |   10 +-
 include/osmium/util/string_matcher.hpp             |  429 ++++
 include/osmium/version.hpp                         |    4 +-
 test/CMakeLists.txt                                |    8 +
 test/data-tests/CMakeLists.txt                     |    4 +
 test/data-tests/testdata-xml.cpp                   |  659 +++---
 test/include/catch.hpp                             | 2261 +++++++++++++-------
 test/t/area/test_assembler.cpp                     |  143 ++
 test/t/geom/test_projection.cpp                    |    4 +-
 test/t/index/test_relations_map.cpp                |   68 +-
 test/t/io/test_compression_factory.cpp             |   11 +-
 test/t/io/test_opl_parser.cpp                      |  153 +-
 test/t/io/test_reader.cpp                          |   24 +-
 test/t/io/test_reader_fileformat.cpp               |   10 +
 test/t/io/test_writer.cpp                          |    6 +-
 test/t/io/test_writer_with_mock_compression.cpp    |   12 +-
 test/t/io/test_writer_with_mock_encoder.cpp        |   12 +-
 test/t/osm/test_location.cpp                       |    8 +-
 test/t/tags/test_tag_list.cpp                      |   17 +-
 test/t/tags/test_tag_matcher.cpp                   |   93 +
 test/t/tags/test_tags_filter.cpp                   |   79 +
 test/t/util/test_cast_with_assert.cpp              |  115 +-
 test/t/util/test_delta.cpp                         |   44 +-
 test/t/util/test_double.cpp                        |   51 +-
 test/t/util/test_memory_mapping.cpp                |  546 +++--
 test/t/util/test_minmax.cpp                        |   81 +-
 test/t/util/test_options.cpp                       |    2 -
 test/t/util/test_string.cpp                        |   94 +-
 test/t/util/test_string_matcher.cpp                |  156 ++
 79 files changed, 5736 insertions(+), 3271 deletions(-)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index d12bb76..011a169 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,62 @@ This project adheres to [Semantic Versioning](http://semver.org/).
 ### Fixed
 
 
+## [2.12.0] - 2017-03-07
+
+### Added
+
+- `TagMatcher` and `TagsFilter` classes for more flexibly matching tags and
+  selecting objects based on tags. This obsoletes the less flexible classes
+  based on `osmium::tags::Filter` classes.
+- Extended `index::RelationsMap(Stash|Index)` classes to also allow
+  parent-to-member lookups.
+- New `nrw_array` helper class.
+- `ObjectPointerCollection::unique()` function.
+
+### Changed
+
+- Area assembler can now detect invalid locations and report them in the
+  stats and through the problem reporter. If the new config option
+  `ignore_invalid_locations` is set, the Assembler will pretend they weren't
+  even referenced in the ways. (Issue #195.)
+- `osmium::area::Assembler::operator()` will now return a boolean reporting
+  whether building of the area(s) was successful.
+- Split up area `Assembler` class into three classes: The
+  `detail::BasicAssembler` is now the parent class. `Assembler` is the child
+  class for usual use. The new `GeomAssembler` also derives from
+  `BasicAssembler` and builds areas without taking tags into account at all.
+  This is to support osm2pgsql which does tag handling itself. (Issue #194.)
+- The `Projection` class can do any projection supported by the Proj.4
+  library. As a special case it now uses our own Mercator projection
+  functions when the web mercator projection (EPSG 3857) is used. This is
+  much faster than going through Proj.4.
+- Better error messages for low-level file utility functions.
+- Mark `build_tag_list*` functions in `builder_helper.hpp` as deprecated. You
+  should use the functions from `osmium/builder/attr.hpp` instead.
+- Improved performance of the `osmium::tags::match_(any|all|none)_of`
+  functions.
+- Improved performance of string comparison in `tags::Filter`.
+- Update version of Catch unit test framework to 1.8.1. This meant some
+  tests had to be updated.
+- Use `get_noexcept()` in `NodeLocationsForWays` handler.
+- And lots of code and test cleanups...
+
+### Fixed
+
+- Terminate called on full non-auto-growing buffer. (Issue #189.)
+- When file formats were used that were not compiled into the binary, it
+  terminated instead of throwing. (Issue #197.)
+- Windows build problem related to including two different winsock versions.
+- Windows build problem related to forced build for old Windows versions.
+  (Issue #196.)
+- Clear stream contents in ProblemReporterException correctly.
+- Add `-pthread` compiler and linker options on Linux/OSX. This should fix
+  a problem where some linker versions will not link binaries correctly when
+  the `--as-needed` option is used.
+- The `Filter::count()` method didn't compile at all.
+- XML reader doesn't fail on relation member ref=0 any more.
+
+
 ## [2.11.0] - 2017-01-14
 
 ### Added
@@ -525,7 +581,9 @@ This project adheres to [Semantic Versioning](http://semver.org/).
   Doxygen (up to version 1.8.8). This version contains a workaround to fix
   this.
 
-[unreleased]: https://github.com/osmcode/libosmium/compare/v2.10.3...HEAD
+[unreleased]: https://github.com/osmcode/libosmium/compare/v2.12.0...HEAD
+[2.12.0]: https://github.com/osmcode/libosmium/compare/v2.11.0...v2.12.0
+[2.11.0]: https://github.com/osmcode/libosmium/compare/v2.10.3...v2.11.0
 [2.10.3]: https://github.com/osmcode/libosmium/compare/v2.10.2...v2.10.3
 [2.10.2]: https://github.com/osmcode/libosmium/compare/v2.10.1...v2.10.2
 [2.10.1]: https://github.com/osmcode/libosmium/compare/v2.10.0...v2.10.1
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 21478ec..13de6a2 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -24,7 +24,7 @@ set(CMAKE_CONFIGURATION_TYPES "Debug;Release;RelWithDebInfo;MinSizeRel;Dev;Cover
 project(libosmium)
 
 set(LIBOSMIUM_VERSION_MAJOR 2)
-set(LIBOSMIUM_VERSION_MINOR 11)
+set(LIBOSMIUM_VERSION_MINOR 12)
 set(LIBOSMIUM_VERSION_PATCH 0)
 
 set(LIBOSMIUM_VERSION
@@ -208,8 +208,7 @@ else()
 endif()
 
 if(WIN32)
-    add_definitions(-DWIN32 -D_WIN32 -DMSWIN32 -DBGDWIN32
-                    -DWINVER=0x0500 -D_WIN32_WINNT=0x0500 -D_WIN32_IE=0x0600)
+    add_definitions(-DWIN32 -D_WIN32 -DMSWIN32 -DBGDWIN32)
 endif()
 
 set(CMAKE_CXX_FLAGS_DEV "${USUAL_COMPILE_OPTIONS}"
diff --git a/benchmarks/CMakeLists.txt b/benchmarks/CMakeLists.txt
index 4b76fcb..5d8b3c1 100644
--- a/benchmarks/CMakeLists.txt
+++ b/benchmarks/CMakeLists.txt
@@ -33,6 +33,7 @@ foreach(benchmark ${BENCHMARKS})
     target_link_libraries(osmium_benchmark_${benchmark}
                           ${OSMIUM_IO_LIBRARIES}
                           ${BENCHMARK_LIBS_${benchmark}})
+    set_pthread_on_target(osmium_benchmark_${benchmark})
     configure_file(run_benchmark_${benchmark}.sh
                    ${CMAKE_CURRENT_BINARY_DIR}/run_benchmark_${benchmark}.sh
                    @ONLY)
diff --git a/cmake/FindOsmium.cmake b/cmake/FindOsmium.cmake
index 2224e18..0877ef2 100644
--- a/cmake/FindOsmium.cmake
+++ b/cmake/FindOsmium.cmake
@@ -298,6 +298,20 @@ unset(OSMIUM_EXTRA_FIND_VARS)
 
 #----------------------------------------------------------------------
 #
+#  A function for setting the -pthread option in compilers/linkers
+#
+#----------------------------------------------------------------------
+function(set_pthread_on_target _target)
+    if(NOT MSVC)
+        set_target_properties(${_target} PROPERTIES COMPILE_FLAGS "-pthread")
+        if(NOT APPLE)
+            set_target_properties(${_target} PROPERTIES LINK_FLAGS "-pthread")
+        endif()
+    endif()
+endfunction()
+
+#----------------------------------------------------------------------
+#
 #  Add compiler flags
 #
 #----------------------------------------------------------------------
diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt
index 442fda7..43c7277 100644
--- a/examples/CMakeLists.txt
+++ b/examples/CMakeLists.txt
@@ -58,6 +58,7 @@ message(STATUS "Configuring examples - Building these examples:")
 foreach(example ${EXAMPLES})
     message(STATUS "  - osmium_${example}")
     add_executable(osmium_${example} "osmium_${example}.cpp")
+    set_pthread_on_target(osmium_${example})
     target_link_libraries(osmium_${example} ${OSMIUM_IO_LIBRARIES} ${EXAMPLE_LIBS_${example}})
 endforeach()
 
diff --git a/include/osmium/area/assembler.hpp b/include/osmium/area/assembler.hpp
index 3509b57..8ec7935 100644
--- a/include/osmium/area/assembler.hpp
+++ b/include/osmium/area/assembler.hpp
@@ -38,253 +38,50 @@ DEALINGS IN THE SOFTWARE.
 #include <cstdint>
 #include <cstdlib>
 #include <cstring>
+#include <functional>
 #include <iostream>
 #include <iterator>
-#include <list>
 #include <set>
 #include <string>
 #include <map>
-#include <unordered_map>
-#include <unordered_set>
 #include <utility>
 #include <vector>
 
+#include <osmium/area/detail/basic_assembler.hpp>
 #include <osmium/builder/osm_object_builder.hpp>
 #include <osmium/memory/buffer.hpp>
 #include <osmium/osm/area.hpp>
 #include <osmium/osm/item_type.hpp>
 #include <osmium/osm/location.hpp>
-#include <osmium/osm/node_ref.hpp>
 #include <osmium/osm/relation.hpp>
 #include <osmium/osm/tag.hpp>
 #include <osmium/osm/types.hpp>
 #include <osmium/osm/way.hpp>
 #include <osmium/tags/filter.hpp>
 #include <osmium/util/compatibility.hpp>
-#include <osmium/util/iterator.hpp>
-#include <osmium/util/timer.hpp>
-
-#include <osmium/area/detail/proto_ring.hpp>
-#include <osmium/area/detail/node_ref_segment.hpp>
-#include <osmium/area/detail/segment_list.hpp>
-#include <osmium/area/problem_reporter.hpp>
-#include <osmium/area/stats.hpp>
 
 namespace osmium {
 
     namespace area {
 
         /**
-         * Configuration for osmium::area::Assembler objects. Create this
-         * once, set the options you want and then re-use it every time you
-         * create an Assembler object.
-         */
-        struct AssemblerConfig {
-
-            /**
-             * Optional pointer to problem reporter.
-             */
-            osmium::area::ProblemReporter* problem_reporter = nullptr;
-
-            /**
-             * Debug level. If this is greater than zero, debug messages will
-             * be printed to stderr. Available levels are 1 to 3. Note that
-             * level 2 and above will generate a lot of messages!
-             */
-            int debug_level = 0;
-
-            /**
-             * The roles of multipolygon members are ignored when assembling
-             * multipolygons, because they are often missing or wrong. If this
-             * is set, the roles are checked after the multipolygons are built
-             * against what the assembly process decided where the inner and
-             * outer rings are. This slows down the processing, so it only
-             * makes sense if you want to get the problem reports.
-             */
-            bool check_roles = false;
-
-            /**
-             * When the assembler can't create an area, usually because its
-             * geometry would be invalid, it will create an "empty" area object
-             * without rings. This allows you to detect where an area was
-             * invalid.
-             *
-             * If this is set to false, invalid areas will simply be discarded.
-             */
-            bool create_empty_areas = true;
-
-            /**
-             * Create areas for (multi)polygons where the tags are on the
-             * relation.
-             *
-             * If this is set to false, those areas will simply be discarded.
-             */
-            bool create_new_style_polygons = true;
-
-            /**
-             * Create areas for (multi)polygons where the tags are on the
-             * outer way(s).
-             *
-             * If this is set to false, those areas will simply be discarded.
-             */
-            bool create_old_style_polygons = true;
-
-            /**
-             * Create areas for polygons created from ways.
-             *
-             * If this is set to false, those areas will simply be discarded.
-             */
-            bool create_way_polygons = true;
-
-            /**
-             * Keep the type tag from multipolygon relations on the area
-             * object. By default this is false, and the type tag will be
-             * removed.
-             */
-            bool keep_type_tag = false;
-
-            AssemblerConfig() noexcept = default;
-
-            /**
-             * Constructor
-             * @deprecated Use default constructor and set values afterwards.
-             */
-            explicit AssemblerConfig(osmium::area::ProblemReporter* pr, bool d = false) :
-                problem_reporter(pr),
-                debug_level(d) {
-            }
-
-            /**
-             * Enable or disable debug output to stderr. This is for Osmium
-             * developers only.
-             *
-             * @deprecated Set debug_level directly.
-             */
-            OSMIUM_DEPRECATED void enable_debug_output(bool d = true) {
-                debug_level = d;
-            }
-
-        }; // struct AssemblerConfig
-
-        namespace detail {
-
-            using open_ring_its_type = std::list<std::list<detail::ProtoRing>::iterator>;
-
-            struct location_to_ring_map {
-                osmium::Location location;
-                open_ring_its_type::iterator ring_it;
-                bool start;
-
-                location_to_ring_map(const osmium::Location& l, const open_ring_its_type::iterator& r, bool s) noexcept :
-                    location(l),
-                    ring_it(r),
-                    start(s) {
-                }
-
-                explicit location_to_ring_map(const osmium::Location& l) noexcept :
-                    location(l),
-                    ring_it(),
-                    start(false) {
-                }
-
-                const detail::ProtoRing& ring() const noexcept {
-                    return **ring_it;
-                }
-
-            }; // struct location_to_ring_map
-
-            inline bool operator==(const location_to_ring_map& lhs, const location_to_ring_map& rhs) noexcept {
-                return lhs.location == rhs.location;
-            }
-
-            inline bool operator<(const location_to_ring_map& lhs, const location_to_ring_map& rhs) noexcept {
-                return lhs.location < rhs.location;
-            }
-
-        } // namespace detail
-
-        /**
          * Assembles area objects from closed ways or multipolygon relations
          * and their members.
          */
-        class Assembler {
-
-            using open_ring_its_type = detail::open_ring_its_type;
-            using location_to_ring_map = detail::location_to_ring_map;
-
-            struct slocation {
-
-                static constexpr const uint32_t invalid_item = 1 << 30;
-
-                uint32_t item : 31;
-                uint32_t reverse : 1;
-
-                slocation() noexcept :
-                    item(invalid_item),
-                    reverse(false) {
-                }
-
-                explicit slocation(uint32_t n, bool r = false) noexcept :
-                    item(n),
-                    reverse(r) {
-                }
-
-                osmium::Location location(const detail::SegmentList& segment_list) const noexcept {
-                    const auto& segment = segment_list[item];
-                    return reverse ? segment.second().location() : segment.first().location();
-                }
-
-                const osmium::NodeRef& node_ref(const detail::SegmentList& segment_list) const noexcept {
-                    const auto& segment = segment_list[item];
-                    return reverse ? segment.second() : segment.first();
-                }
-
-                osmium::Location location(const detail::SegmentList& segment_list, const osmium::Location& default_location) const noexcept {
-                    if (item == invalid_item) {
-                        return default_location;
-                    }
-                    return location(segment_list);
-                }
-
-            }; // struct slocation
-
-            // Configuration settings for this Assembler
-            const AssemblerConfig& m_config;
-
-            // List of segments (connection between two nodes)
-            osmium::area::detail::SegmentList m_segment_list;
-
-            // The rings we are building from the segments
-            std::list<detail::ProtoRing> m_rings;
-
-            // All node locations
-            std::vector<slocation> m_locations;
-
-            // All locations where more than two segments start/end
-            std::vector<Location> m_split_locations;
-
-            // Statistics
-            area_stats m_stats;
-
-            // The number of members the multipolygon relation has
-            size_t m_num_members = 0;
-
-            bool debug() const noexcept {
-                return m_config.debug_level > 1;
-            }
+        class Assembler : public detail::BasicAssembler {
 
             bool report_ways() const noexcept {
-                if (!m_config.problem_reporter) {
+                if (!config().problem_reporter) {
                     return false;
                 }
-                return m_stats.duplicate_nodes ||
-                       m_stats.duplicate_segments ||
-                       m_stats.intersections ||
-                       m_stats.open_rings ||
-                       m_stats.short_ways ||
-                       m_stats.touching_rings ||
-                       m_stats.ways_in_multiple_rings ||
-                       m_stats.wrong_role;
+                return stats().duplicate_nodes ||
+                    stats().duplicate_segments ||
+                    stats().intersections ||
+                    stats().open_rings ||
+                    stats().short_ways ||
+                    stats().touching_rings ||
+                    stats().ways_in_multiple_rings ||
+                    stats().wrong_role;
             }
 
             void add_tags_to_area(osmium::builder::AreaBuilder& builder, const osmium::Way& way) const {
@@ -295,7 +92,7 @@ namespace osmium {
                 std::map<std::string, size_t> counter;
                 for (const osmium::Way* way : ways) {
                     for (const auto& tag : way->tags()) {
-                        std::string kv {tag.key()};
+                        std::string kv{tag.key()};
                         kv.append(1, '\0');
                         kv.append(tag.value());
                         ++counter[kv];
@@ -342,7 +139,7 @@ namespace osmium {
             }
 
             void add_tags_to_area(osmium::builder::AreaBuilder& builder, const osmium::Relation& relation) {
-                const auto count = std::count_if(relation.tags().cbegin(), relation.tags().cend(), filter());
+                const auto count = std::count_if(relation.tags().cbegin(), relation.tags().cend(), std::cref(filter()));
 
                 if (debug()) {
                     std::cerr << "  found " << count << " tags on relation (without ignored ones)\n";
@@ -353,18 +150,18 @@ namespace osmium {
                         std::cerr << "    use tags from relation\n";
                     }
 
-                    if (m_config.keep_type_tag) {
+                    if (config().keep_type_tag) {
                         builder.add_item(relation.tags());
                     } else {
                         copy_tags_without_type(builder, relation.tags());
                     }
                 } else {
-                    ++m_stats.no_tags_on_relation;
+                    ++stats().no_tags_on_relation;
                     if (debug()) {
                         std::cerr << "    use tags from outer ways\n";
                     }
                     std::set<const osmium::Way*> ways;
-                    for (const auto& ring : m_rings) {
+                    for (const auto& ring : rings()) {
                         if (ring.is_outer()) {
                             ring.get_ways(ways);
                         }
@@ -384,989 +181,12 @@ namespace osmium {
                 }
             }
 
-            template <typename TBuilder>
-            static void build_ring_from_proto_ring(osmium::builder::AreaBuilder& builder, const detail::ProtoRing& ring) {
-                TBuilder ring_builder{builder};
-                ring_builder.add_node_ref(ring.get_node_ref_start());
-                for (const auto& segment : ring.segments()) {
-                    ring_builder.add_node_ref(segment->stop());
-                }
-            }
-
-            /**
-             * Append each outer ring together with its inner rings to the
-             * area in the buffer.
-             */
-            void add_rings_to_area(osmium::builder::AreaBuilder& builder) const {
-                for (const detail::ProtoRing& ring : m_rings) {
-                    if (ring.is_outer()) {
-                        build_ring_from_proto_ring<osmium::builder::OuterRingBuilder>(builder, ring);
-                        for (const detail::ProtoRing* inner : ring.inner_rings()) {
-                            build_ring_from_proto_ring<osmium::builder::InnerRingBuilder>(builder, *inner);
-                        }
-                    }
-                }
-            }
-
-            void check_inner_outer_roles() {
-                if (debug()) {
-                    std::cerr << "    Checking inner/outer roles\n";
-                }
-
-                std::unordered_map<const osmium::Way*, const detail::ProtoRing*> way_rings;
-                std::unordered_set<const osmium::Way*> ways_in_multiple_rings;
-
-                for (const detail::ProtoRing& ring : m_rings) {
-                    for (const auto& segment : ring.segments()) {
-                        assert(segment->way());
-
-                        if (!segment->role_empty() && (ring.is_outer() ? !segment->role_outer() : !segment->role_inner())) {
-                            ++m_stats.wrong_role;
-                            if (debug()) {
-                                std::cerr << "      Segment " << *segment << " from way " << segment->way()->id() << " has role '" << segment->role_name()
-                                          << "', but should have role '" << (ring.is_outer() ? "outer" : "inner") << "'\n";
-                            }
-                            if (m_config.problem_reporter) {
-                                if (ring.is_outer()) {
-                                    m_config.problem_reporter->report_role_should_be_outer(segment->way()->id(), segment->first().location(), segment->second().location());
-                                } else {
-                                    m_config.problem_reporter->report_role_should_be_inner(segment->way()->id(), segment->first().location(), segment->second().location());
-                                }
-                            }
-                        }
-
-                        auto& r = way_rings[segment->way()];
-                        if (!r) {
-                            r = ˚
-                        } else if (r != &ring) {
-                            ways_in_multiple_rings.insert(segment->way());
-                        }
-
-                    }
-                }
-
-                for (const osmium::Way* way : ways_in_multiple_rings) {
-                    ++m_stats.ways_in_multiple_rings;
-                    if (debug()) {
-                        std::cerr << "      Way " << way->id() << " is in multiple rings\n";
-                    }
-                    if (m_config.problem_reporter) {
-                        m_config.problem_reporter->report_way_in_multiple_rings(*way);
-                    }
-                }
-
-            }
-
-            detail::NodeRefSegment* get_next_segment(const osmium::Location& location) {
-                auto it = std::lower_bound(m_locations.begin(), m_locations.end(), slocation{}, [this, &location](const slocation& lhs, const slocation& rhs) {
-                    return lhs.location(m_segment_list, location) < rhs.location(m_segment_list, location);
-                });
-
-                assert(it != m_locations.end());
-                if (m_segment_list[it->item].is_done()) {
-                    ++it;
-                }
-                assert(it != m_locations.end());
-
-                assert(!m_segment_list[it->item].is_done());
-                return &m_segment_list[it->item];
-            }
-
-            class rings_stack_element {
-
-                int32_t m_y;
-                detail::ProtoRing* m_ring_ptr;
-
-            public:
-
-                rings_stack_element(int32_t y, detail::ProtoRing* ring_ptr) :
-                    m_y(y),
-                    m_ring_ptr(ring_ptr) {
-                }
-
-                int32_t y() const noexcept {
-                    return m_y;
-                }
-
-                const detail::ProtoRing& ring() const noexcept {
-                    return *m_ring_ptr;
-                }
-
-                detail::ProtoRing* ring_ptr() noexcept {
-                    return m_ring_ptr;
-                }
-
-                bool operator==(const rings_stack_element& rhs) const noexcept {
-                    return m_ring_ptr == rhs.m_ring_ptr;
-                }
-
-                bool operator<(const rings_stack_element& rhs) const noexcept {
-                    return m_y < rhs.m_y;
-                }
-
-            }; // class ring_stack_element
-
-            using rings_stack = std::vector<rings_stack_element>;
-
-            void remove_duplicates(rings_stack& outer_rings) {
-                while (true) {
-                    const auto it = std::adjacent_find(outer_rings.begin(), outer_rings.end());
-                    if (it == outer_rings.end()) {
-                        return;
-                    }
-                    outer_rings.erase(it, std::next(it, 2));
-                }
-            }
-
-            detail::ProtoRing* find_enclosing_ring(detail::NodeRefSegment* segment) {
-                if (debug()) {
-                    std::cerr << "    Looking for ring enclosing " << *segment << "\n";
-                }
-
-                const auto location = segment->first().location();
-                const auto end_location = segment->second().location();
-
-                while (segment->first().location() == location) {
-                    if (segment == &m_segment_list.back()) {
-                        break;
-                    }
-                    ++segment;
-                }
-
-                int nesting = 0;
-
-                rings_stack outer_rings;
-                while (segment >= &m_segment_list.front()) {
-                    if (!segment->is_direction_done()) {
-                        --segment;
-                        continue;
-                    }
-                    if (debug()) {
-                        std::cerr << "      Checking against " << *segment << "\n";
-                    }
-                    const osmium::Location& a = segment->first().location();
-                    const osmium::Location& b = segment->second().location();
-
-                    if (segment->first().location() == location) {
-                        const int64_t ax = a.x();
-                        const int64_t bx = b.x();
-                        const int64_t lx = end_location.x();
-                        const int64_t ay = a.y();
-                        const int64_t by = b.y();
-                        const int64_t ly = end_location.y();
-                        const auto z = (bx - ax)*(ly - ay) - (by - ay)*(lx - ax);
-                        if (debug()) {
-                            std::cerr << "      Segment XXXX z=" << z << "\n";
-                        }
-                        if (z > 0) {
-                            nesting += segment->is_reverse() ? -1 : 1;
-                            if (debug()) {
-                                std::cerr << "        Segment is below (nesting=" << nesting << ")\n";
-                            }
-                            if (segment->ring()->is_outer()) {
-                                if (debug()) {
-                                    std::cerr << "        Segment belongs to outer ring\n";
-                                }
-                                outer_rings.emplace_back(a.y(), segment->ring());
-                            }
-                        }
-                    } else if (a.x() <= location.x() && location.x() < b.x()) {
-                        if (debug()) {
-                            std::cerr << "        Is in x range\n";
-                        }
-
-                        const int64_t ax = a.x();
-                        const int64_t bx = b.x();
-                        const int64_t lx = location.x();
-                        const int64_t ay = a.y();
-                        const int64_t by = b.y();
-                        const int64_t ly = location.y();
-                        const auto z = (bx - ax)*(ly - ay) - (by - ay)*(lx - ax);
-
-                        if (z >= 0) {
-                            nesting += segment->is_reverse() ? -1 : 1;
-                            if (debug()) {
-                                std::cerr << "        Segment is below (nesting=" << nesting << ")\n";
-                            }
-                            if (segment->ring()->is_outer()) {
-                                if (debug()) {
-                                    std::cerr << "        Segment belongs to outer ring\n";
-                                }
-                                const int32_t y = int32_t(ay + (by - ay) * (lx - ax) / (bx - ax));
-                                outer_rings.emplace_back(y, segment->ring());
-                            }
-                        }
-                    }
-                    --segment;
-                }
-
-                if (nesting % 2 == 0) {
-                    if (debug()) {
-                        std::cerr << "    Decided that this is an outer ring\n";
-                    }
-                    return nullptr;
-                } else {
-                    if (debug()) {
-                        std::cerr << "    Decided that this is an inner ring\n";
-                    }
-                    assert(!outer_rings.empty());
-
-                    std::sort(outer_rings.rbegin(), outer_rings.rend());
-                    if (debug()) {
-                        for (const auto& o : outer_rings) {
-                            std::cerr << "        y=" << o.y() << " " << o.ring() << "\n";
-                        }
-                    }
-
-                    remove_duplicates(outer_rings);
-                    if (debug()) {
-                        std::cerr << "      after remove duplicates:\n";
-                        for (const auto& o : outer_rings) {
-                            std::cerr << "        y=" << o.y() << " " << o.ring() << "\n";
-                        }
-                    }
-
-                    assert(!outer_rings.empty());
-                    return outer_rings.front().ring_ptr();
-                }
-            }
-
-            bool is_split_location(const osmium::Location& location) const noexcept {
-                return std::find(m_split_locations.cbegin(), m_split_locations.cend(), location) != m_split_locations.cend();
-            }
-
-            uint32_t add_new_ring(slocation& node) {
-                detail::NodeRefSegment* segment = &m_segment_list[node.item];
-                assert(!segment->is_done());
-
-                if (debug()) {
-                    std::cerr << "  Starting new ring at location " << node.location(m_segment_list) << " with segment " << *segment << "\n";
-                }
-
-                if (node.reverse) {
-                    segment->reverse();
-                }
-
-                detail::ProtoRing* outer_ring = nullptr;
-
-                if (segment != &m_segment_list.front()) {
-                    outer_ring = find_enclosing_ring(segment);
-                }
-                segment->mark_direction_done();
-
-                m_rings.emplace_back(segment);
-                detail::ProtoRing* ring = &m_rings.back();
-                if (outer_ring) {
-                    if (debug()) {
-                        std::cerr << "    This is an inner ring. Outer ring is " << *outer_ring << "\n";
-                    }
-                    outer_ring->add_inner_ring(ring);
-                    ring->set_outer_ring(outer_ring);
-                } else if (debug()) {
-                    std::cerr << "    This is an outer ring\n";
-                }
-
-                const osmium::Location& first_location = node.location(m_segment_list);
-                osmium::Location last_location = segment->stop().location();
-
-                uint32_t nodes = 1;
-                while (first_location != last_location) {
-                    ++nodes;
-                    detail::NodeRefSegment* next_segment = get_next_segment(last_location);
-                    next_segment->mark_direction_done();
-                    if (next_segment->start().location() != last_location) {
-                        next_segment->reverse();
-                    }
-                    ring->add_segment_back(next_segment);
-                    if (debug()) {
-                        std::cerr << "    Next segment is " << *next_segment << "\n";
-                    }
-                    last_location = next_segment->stop().location();
-                }
-
-                ring->fix_direction();
-
-                if (debug()) {
-                    std::cerr << "    Completed ring: " << *ring << "\n";
-                }
-
-                return nodes;
-            }
-
-            uint32_t add_new_ring_complex(slocation& node) {
-                detail::NodeRefSegment* segment = &m_segment_list[node.item];
-                assert(!segment->is_done());
-
-                if (debug()) {
-                    std::cerr << "  Starting new ring at location " << node.location(m_segment_list) << " with segment " << *segment << "\n";
-                }
-
-                if (node.reverse) {
-                    segment->reverse();
-                }
-
-                m_rings.emplace_back(segment);
-                detail::ProtoRing* ring = &m_rings.back();
-
-                const osmium::Location& first_location = node.location(m_segment_list);
-                osmium::Location last_location = segment->stop().location();
-
-                uint32_t nodes = 1;
-                while (first_location != last_location && !is_split_location(last_location)) {
-                    ++nodes;
-                    detail::NodeRefSegment* next_segment = get_next_segment(last_location);
-                    if (next_segment->start().location() != last_location) {
-                        next_segment->reverse();
-                    }
-                    ring->add_segment_back(next_segment);
-                    if (debug()) {
-                        std::cerr << "    Next segment is " << *next_segment << "\n";
-                    }
-                    last_location = next_segment->stop().location();
-                }
-
-                if (debug()) {
-                    if (first_location == last_location) {
-                        std::cerr << "    Completed ring: " << *ring << "\n";
-                    } else {
-                        std::cerr << "    Completed partial ring: " << *ring << "\n";
-                    }
-                }
-
-                return nodes;
-            }
-
-            void create_locations_list() {
-                m_locations.reserve(m_segment_list.size() * 2);
-
-                for (uint32_t n = 0; n < m_segment_list.size(); ++n) {
-                    m_locations.emplace_back(n, false);
-                    m_locations.emplace_back(n, true);
-                }
-
-                std::stable_sort(m_locations.begin(), m_locations.end(), [this](const slocation& lhs, const slocation& rhs) {
-                    return lhs.location(m_segment_list) < rhs.location(m_segment_list);
-                });
-            }
-
-            void find_inner_outer_complex(detail::ProtoRing* ring) {
-                detail::ProtoRing* outer_ring = find_enclosing_ring(ring->min_segment());
-                if (outer_ring) {
-                    outer_ring->add_inner_ring(ring);
-                    ring->set_outer_ring(outer_ring);
-                }
-                ring->fix_direction();
-                ring->mark_direction_done();
-            }
-
-            void find_inner_outer_complex() {
-                if (debug()) {
-                    std::cerr << "  Finding inner/outer rings\n";
-                }
-                std::vector<detail::ProtoRing*> rings;
-                rings.reserve(m_rings.size());
-                for (auto& ring : m_rings) {
-                    if (ring.closed()) {
-                        rings.push_back(&ring);
-                    }
-                }
-
-                if (rings.empty()) {
-                    return;
-                }
-
-                std::sort(rings.begin(), rings.end(), [](detail::ProtoRing* a, detail::ProtoRing* b) {
-                    return a->min_segment() < b->min_segment();
-                });
-
-                rings.front()->fix_direction();
-                rings.front()->mark_direction_done();
-                if (debug()) {
-                    std::cerr << "    First ring is outer: " << *rings.front() << "\n";
-                }
-                for (auto it = std::next(rings.begin()); it != rings.end(); ++it) {
-                    if (debug()) {
-                        std::cerr << "    Checking (at min segment " << *((*it)->min_segment()) << ") ring " << **it << "\n";
-                    }
-                    find_inner_outer_complex(*it);
-                    if (debug()) {
-                        std::cerr << "    Ring is " << ((*it)->is_outer() ? "OUTER: " : "INNER: ") << **it << "\n";
-                    }
-                }
-            }
-
-            /**
-             * Finds all locations where more than two segments meet. If there
-             * are any open rings found along the way, they are reported
-             * and the function returns false.
-             */
-            bool find_split_locations() {
-                osmium::Location previous_location;
-                for (auto it = m_locations.cbegin(); it != m_locations.cend(); ++it) {
-                    const osmium::NodeRef& nr = it->node_ref(m_segment_list);
-                    const osmium::Location& loc = nr.location();
-                    if (std::next(it) == m_locations.cend() || loc != std::next(it)->location(m_segment_list)) {
-                        if (debug()) {
-                            std::cerr << "  Found open ring at " << nr << "\n";
-                        }
-                        if (m_config.problem_reporter) {
-                            const auto& segment = m_segment_list[it->item];
-                            m_config.problem_reporter->report_ring_not_closed(nr, segment.way());
-                        }
-                        ++m_stats.open_rings;
-                    } else {
-                        if (loc == previous_location && (m_split_locations.empty() || m_split_locations.back() != previous_location )) {
-                            m_split_locations.push_back(previous_location);
-                        }
-                        ++it;
-                        if (it == m_locations.end()) {
-                            break;
-                        }
-                    }
-                    previous_location = loc;
-                }
-                return m_stats.open_rings == 0;
-            }
-
-            void create_rings_simple_case() {
-                auto count_remaining = m_segment_list.size();
-                for (slocation& sl : m_locations) {
-                    const detail::NodeRefSegment& segment = m_segment_list[sl.item];
-                    if (!segment.is_done()) {
-                        count_remaining -= add_new_ring(sl);
-                        if (count_remaining == 0) {
-                            return;
-                        }
-                    }
-                }
-            }
-
-            std::vector<location_to_ring_map> create_location_to_ring_map(open_ring_its_type& open_ring_its) {
-                std::vector<location_to_ring_map> xrings;
-                xrings.reserve(open_ring_its.size() * 2);
-
-                for (auto it = open_ring_its.begin(); it != open_ring_its.end(); ++it) {
-                    if (debug()) {
-                        std::cerr << "      Ring: " << **it << "\n";
-                    }
-                    xrings.emplace_back((*it)->get_node_ref_start().location(), it, true);
-                    xrings.emplace_back((*it)->get_node_ref_stop().location(), it, false);
-                }
-
-                std::sort(xrings.begin(), xrings.end());
-
-                return xrings;
-            }
-
-            void merge_two_rings(open_ring_its_type& open_ring_its, const location_to_ring_map& m1, const location_to_ring_map& m2) {
-                auto& r1 = *m1.ring_it;
-                auto& r2 = *m2.ring_it;
-
-                if (r1->get_node_ref_stop().location() == r2->get_node_ref_start().location()) {
-                    r1->join_forward(*r2);
-                } else if (r1->get_node_ref_stop().location() == r2->get_node_ref_stop().location()) {
-                    r1->join_backward(*r2);
-                } else if (r1->get_node_ref_start().location() == r2->get_node_ref_start().location()) {
-                    r1->reverse();
-                    r1->join_forward(*r2);
-                } else if (r1->get_node_ref_start().location() == r2->get_node_ref_stop().location()) {
-                    r1->reverse();
-                    r1->join_backward(*r2);
-                } else {
-                    assert(false);
-                }
-
-                m_rings.erase(r2);
-                open_ring_its.remove(r2);
-
-                if (r1->closed()) {
-                    open_ring_its.remove(r1);
-                }
-            }
-
-            bool try_to_merge(open_ring_its_type& open_ring_its) {
-                if (open_ring_its.empty()) {
-                    return false;
-                }
-
-                if (debug()) {
-                    std::cerr << "    Trying to merge " << open_ring_its.size() << " open rings\n";
-                }
-
-                std::vector<location_to_ring_map> xrings = create_location_to_ring_map(open_ring_its);
-
-                auto it = xrings.cbegin();
-                while (it != xrings.cend()) {
-                    it = std::adjacent_find(it, xrings.cend());
-                    if (it == xrings.cend()) {
-                        return false;
-                    }
-                    auto after = std::next(it, 2);
-                    if (after == xrings.cend() || after->location != it->location) {
-                        if (debug()) {
-                            std::cerr << "      Merging two rings\n";
-                        }
-                        merge_two_rings(open_ring_its, *it, *std::next(it));
-                        return true;
-                    }
-                    while (it != xrings.cend() && it->location == after->location) {
-                        ++it;
-                    }
-                }
-
-                return false;
-            }
-
-            bool there_are_open_rings() const noexcept {
-                return std::any_of(m_rings.cbegin(), m_rings.cend(), [](const detail::ProtoRing& ring){
-                    return !ring.closed();
-                });
-            }
-
-            struct candidate {
-                int64_t sum;
-                std::vector<std::pair<location_to_ring_map, bool>> rings;
-                osmium::Location start_location;
-                osmium::Location stop_location;
-
-                explicit candidate(location_to_ring_map& ring, bool reverse) :
-                    sum(ring.ring().sum()),
-                    rings(),
-                    start_location(ring.ring().get_node_ref_start().location()),
-                    stop_location(ring.ring().get_node_ref_stop().location()) {
-                    rings.emplace_back(ring, reverse);
-                }
-
-                bool closed() const noexcept {
-                    return start_location == stop_location;
-                }
-
-            };
-
-            void find_candidates(std::vector<candidate>& candidates, std::unordered_set<osmium::Location>& loc_done, const std::vector<location_to_ring_map>& xrings, candidate& cand) {
-                if (debug()) {
-                    std::cerr << "      find_candidates sum=" << cand.sum << " start=" << cand.start_location << " stop=" << cand.stop_location << "\n";
-                    for (const auto& ring : cand.rings) {
-                        std::cerr << "        " << ring.first.ring() << (ring.second ? " reverse" : "") << "\n";
-                    }
-                }
-
-                const auto connections = make_range(std::equal_range(xrings.cbegin(),
-                                                                     xrings.cend(),
-                                                                     location_to_ring_map{cand.stop_location}));
-
-                assert(connections.begin() != connections.end());
-
-                assert(!cand.rings.empty());
-                const detail::ProtoRing* ring_leading_here = &cand.rings.back().first.ring();
-                for (const location_to_ring_map& m : connections) {
-                    const detail::ProtoRing& ring = m.ring();
-
-                    if (&ring != ring_leading_here) {
-                        if (debug()) {
-                            std::cerr << "        next possible connection: " << ring << (m.start ? "" : " reverse") << "\n";
-                        }
-
-                        candidate c = cand;
-                        if (m.start) {
-                            c.rings.emplace_back(m, false);
-                            c.stop_location = ring.get_node_ref_stop().location();
-                            c.sum += ring.sum();
-                        } else {
-                            c.rings.emplace_back(m, true);
-                            c.stop_location = ring.get_node_ref_start().location();
-                            c.sum -= ring.sum();
-                        }
-                        if (c.closed()) {
-                            if (debug()) {
-                                std::cerr << "          found candidate\n";
-                            }
-                            candidates.push_back(c);
-                        } else if (loc_done.count(c.stop_location) == 0) {
-                            if (debug()) {
-                                std::cerr << "          recurse...\n";
-                            }
-                            loc_done.insert(c.stop_location);
-                            find_candidates(candidates, loc_done, xrings, c);
-                            if (debug()) {
-                                std::cerr << "          ...back\n";
-                            }
-                        } else if (debug()) {
-                            std::cerr << "          loop found\n";
-                        }
-                    }
-                }
-            }
-
-            /**
-             * If there are multiple open rings and mltiple ways to join them,
-             * this function is called. It will take the first open ring and
-             * try recursively all ways of closing it. Of all the candidates
-             * the one with the smallest area is chosen and closed. If it
-             * can't close this ring, an error is reported and the function
-             * returns false.
-             */
-            bool join_connected_rings(open_ring_its_type& open_ring_its) {
-                assert(!open_ring_its.empty());
-
-                if (debug()) {
-                    std::cerr << "    Trying to merge " << open_ring_its.size() << " open rings\n";
-                }
-
-                std::vector<location_to_ring_map> xrings = create_location_to_ring_map(open_ring_its);
-
-                const auto ring_min = std::min_element(xrings.begin(), xrings.end(), [](const location_to_ring_map& lhs, const location_to_ring_map& rhs) {
-                    return lhs.ring().min_segment() < rhs.ring().min_segment();
-                });
-
-                find_inner_outer_complex();
-                detail::ProtoRing* outer_ring = find_enclosing_ring(ring_min->ring().min_segment());
-                bool ring_min_is_outer = !outer_ring;
-                if (debug()) {
-                    std::cerr << "  Open ring is " << (ring_min_is_outer ? "outer" : "inner") << " ring\n";
-                }
-                for (auto& ring : m_rings) {
-                    ring.reset();
-                }
-
-                candidate cand{*ring_min, false};
-
-                // Locations we have visited while finding candidates, used
-                // to detect loops.
-                std::unordered_set<osmium::Location> loc_done;
-
-                loc_done.insert(cand.stop_location);
-
-                std::vector<candidate> candidates;
-                find_candidates(candidates, loc_done, xrings, cand);
-
-                if (candidates.empty()) {
-                    if (debug()) {
-                        std::cerr << "    Found no candidates\n";
-                    }
-                    if (!open_ring_its.empty()) {
-                        ++m_stats.open_rings;
-                        if (m_config.problem_reporter) {
-                            for (auto& it : open_ring_its) {
-                                m_config.problem_reporter->report_ring_not_closed(it->get_node_ref_start());
-                                m_config.problem_reporter->report_ring_not_closed(it->get_node_ref_stop());
-                            }
-                        }
-                    }
-                    return false;
-                }
-
-                if (debug()) {
-                    std::cerr << "    Found candidates:\n";
-                    for (const auto& cand : candidates) {
-                        std::cerr << "      sum=" << cand.sum << "\n";
-                        for (const auto& ring : cand.rings) {
-                            std::cerr << "        " << ring.first.ring() << (ring.second ? " reverse" : "") << "\n";
-                        }
-                    }
-                }
-
-                // Find the candidate with the smallest/largest area
-                const auto chosen_cand = ring_min_is_outer ?
-                     std::min_element(candidates.cbegin(), candidates.cend(), [](const candidate& lhs, const candidate& rhs) {
-                        return std::abs(lhs.sum) < std::abs(rhs.sum);
-                     }) :
-                     std::max_element(candidates.cbegin(), candidates.cend(), [](const candidate& lhs, const candidate& rhs) {
-                        return std::abs(lhs.sum) < std::abs(rhs.sum);
-                     });
-
-                if (debug()) {
-                    std::cerr << "    Decided on: sum=" << chosen_cand->sum << "\n";
-                    for (const auto& ring : chosen_cand->rings) {
-                        std::cerr << "        " << ring.first.ring() << (ring.second ? " reverse" : "") << "\n";
-                    }
-                }
-
-                // Join all (open) rings in the candidate to get one closed ring.
-                assert(chosen_cand->rings.size() > 1);
-                const auto& first_ring = chosen_cand->rings.front().first;
-                for (auto it = chosen_cand->rings.begin() + 1; it != chosen_cand->rings.end(); ++it) {
-                    merge_two_rings(open_ring_its, first_ring, it->first);
-                }
-
-                if (debug()) {
-                    std::cerr << "    Merged to " << first_ring.ring() << "\n";
-                }
-
-                return true;
-            }
-
-            bool create_rings_complex_case() {
-                // First create all the (partial) rings starting at the split locations
-                auto count_remaining = m_segment_list.size();
-                for (const osmium::Location& location : m_split_locations) {
-                    const auto locs = make_range(std::equal_range(m_locations.begin(),
-                                                                  m_locations.end(),
-                                                                  slocation{},
-                                                                  [this, &location](const slocation& lhs, const slocation& rhs) {
-                        return lhs.location(m_segment_list, location) < rhs.location(m_segment_list, location);
-                    }));
-                    for (auto& loc : locs) {
-                        if (!m_segment_list[loc.item].is_done()) {
-                            count_remaining -= add_new_ring_complex(loc);
-                            if (count_remaining == 0) {
-                                break;
-                            }
-                        }
-                    }
-                }
-
-                // Now find all the rest of the rings (ie not starting at split locations)
-                if (count_remaining > 0) {
-                    for (slocation& sl : m_locations) {
-                        const detail::NodeRefSegment& segment = m_segment_list[sl.item];
-                        if (!segment.is_done()) {
-                            count_remaining -= add_new_ring_complex(sl);
-                            if (count_remaining == 0) {
-                                break;
-                            }
-                        }
-                    }
-                }
-
-                // Now all segments are in exactly one (partial) ring.
-
-                // If there are open rings, try to join them to create closed
-                // rings.
-                if (there_are_open_rings()) {
-                    ++m_stats.area_really_complex_case;
-
-                    open_ring_its_type open_ring_its;
-                    for (auto it = m_rings.begin(); it != m_rings.end(); ++it) {
-                        if (!it->closed()) {
-                            open_ring_its.push_back(it);
-                        }
-                    }
-
-                    while (!open_ring_its.empty()) {
-                        if (debug()) {
-                            std::cerr << "  There are " << open_ring_its.size() << " open rings\n";
-                        }
-                        while (try_to_merge(open_ring_its));
-
-                        if (!open_ring_its.empty()) {
-                            if (debug()) {
-                                std::cerr << "  After joining obvious cases there are still " << open_ring_its.size() << " open rings\n";
-                            }
-                            if (!join_connected_rings(open_ring_its)) {
-                                return false;
-                            }
-                        }
-                    }
-
-                    if (debug()) {
-                        std::cerr << "  Joined all open rings\n";
-                    }
-                }
-
-                // Now all rings are complete.
-
-                find_inner_outer_complex();
-
-                return true;
-            }
-
-            /**
-             * Checks if any ways were completely removed in the
-             * erase_duplicate_segments step.
-             */
-            bool ways_were_lost() {
-                std::unordered_set<const osmium::Way*> ways_in_segments;
-
-                for (const auto& segment : m_segment_list) {
-                    ways_in_segments.insert(segment.way());
-                }
-
-                return ways_in_segments.size() < m_num_members;
-            }
-
-            /**
-             * Create rings from segments.
-             */
-            bool create_rings() {
-                m_stats.nodes += m_segment_list.size();
-
-                // Sort the list of segments (from left to right and bottom
-                // to top).
-                osmium::Timer timer_sort;
-                m_segment_list.sort();
-                timer_sort.stop();
-
-                // Remove duplicate segments. Removal is in pairs, so if there
-                // are two identical segments, they will both be removed. If
-                // there are three, two will be removed and one remains.
-                osmium::Timer timer_dupl;
-                m_stats.duplicate_segments = m_segment_list.erase_duplicate_segments(m_config.problem_reporter);
-                timer_dupl.stop();
-
-                // If there are no segments left at this point, this isn't
-                // a valid area.
-                if (m_segment_list.empty()) {
-                    if (debug()) {
-                        std::cerr << "  No segments left\n";
-                    }
-                    return false;
-                }
-
-                // If one or more complete ways was removed because of
-                // duplicate segments, this isn't a valid area.
-                if (ways_were_lost()) {
-                    if (debug()) {
-                        std::cerr << "  Complete ways removed because of duplicate segments\n";
-                    }
-                    return false;
-                }
-
-                if (m_config.debug_level >= 3) {
-                    std::cerr << "Sorted de-duplicated segment list:\n";
-                    for (const auto& s : m_segment_list) {
-                        std::cerr << "  " << s << "\n";
-                    }
-                }
-
-                // Now we look for segments crossing each other. If there are
-                // any, the multipolygon is invalid.
-                // In the future this could be improved by trying to fix those
-                // cases.
-                osmium::Timer timer_intersection;
-                m_stats.intersections = m_segment_list.find_intersections(m_config.problem_reporter);
-                timer_intersection.stop();
-
-                if (m_stats.intersections) {
-                    return false;
-                }
-
-                // This creates an ordered list of locations of both endpoints
-                // of all segments with pointers back to the segments. We will
-                // use this list later to quickly find which segment(s) fits
-                // onto a known segment.
-                osmium::Timer timer_locations_list;
-                create_locations_list();
-                timer_locations_list.stop();
-
-                // Find all locations where more than two segments start or
-                // end. We call those "split" locations. If there are any
-                // "spike" segments found while doing this, we know the area
-                // geometry isn't valid and return.
-                osmium::Timer timer_split;
-                if (!find_split_locations()) {
-                    return false;
-                }
-                timer_split.stop();
-
-                // Now report all split locations to the problem reporter.
-                m_stats.touching_rings += m_split_locations.size();
-                if (!m_split_locations.empty()) {
-                    if (debug()) {
-                        std::cerr << "  Found split locations:\n";
-                    }
-                    for (const auto& location : m_split_locations) {
-                        if (m_config.problem_reporter) {
-                            auto it = std::lower_bound(m_locations.cbegin(), m_locations.cend(), slocation{}, [this, &location](const slocation& lhs, const slocation& rhs) {
-                                return lhs.location(m_segment_list, location) < rhs.location(m_segment_list, location);
-                            });
-                            assert(it != m_locations.cend());
-                            const osmium::object_id_type id = it->node_ref(m_segment_list).ref();
-                            m_config.problem_reporter->report_touching_ring(id, location);
-                        }
-                        if (debug()) {
-                            std::cerr << "    " << location << "\n";
-                        }
-                    }
-                }
-
-                // From here on we use two different algorithms depending on
-                // whether there were any split locations or not. If there
-                // are no splits, we use the faster "simple algorithm", if
-                // there are, we use the slower "complex algorithm".
-                osmium::Timer timer_simple_case;
-                osmium::Timer timer_complex_case;
-                if (m_split_locations.empty()) {
-                    if (debug()) {
-                        std::cerr << "  No split locations -> using simple algorithm\n";
-                    }
-                    ++m_stats.area_simple_case;
-
-                    timer_simple_case.start();
-                    create_rings_simple_case();
-                    timer_simple_case.stop();
-                } else {
-                    if (debug()) {
-                        std::cerr << "  Found split locations -> using complex algorithm\n";
-                    }
-                    ++m_stats.area_touching_rings_case;
-
-                    timer_complex_case.start();
-                    if (!create_rings_complex_case()) {
-                        return false;
-                    }
-                    timer_complex_case.stop();
-                }
-
-                // If the assembler was so configured, now check whether the
-                // member roles are correctly tagged.
-                if (m_config.check_roles && m_stats.from_relations) {
-                    osmium::Timer timer_roles;
-                    check_inner_outer_roles();
-                    timer_roles.stop();
-                }
-
-                m_stats.outer_rings = std::count_if(m_rings.cbegin(), m_rings.cend(), [](const detail::ProtoRing& ring){
-                    return ring.is_outer();
-                });
-                m_stats.inner_rings = m_rings.size() - m_stats.outer_rings;
-
-#ifdef OSMIUM_WITH_TIMER
-                std::cout << m_stats.nodes << ' ' << m_stats.outer_rings << ' ' << m_stats.inner_rings <<
-                                              ' ' << timer_sort.elapsed_microseconds() <<
-                                              ' ' << timer_dupl.elapsed_microseconds() <<
-                                              ' ' << timer_intersection.elapsed_microseconds() <<
-                                              ' ' << timer_locations_list.elapsed_microseconds() <<
-                                              ' ' << timer_split.elapsed_microseconds();
-
-                if (m_split_locations.empty()) {
-                    std::cout << ' ' << timer_simple_case.elapsed_microseconds() <<
-                                 " 0";
-                } else {
-                    std::cout << " 0" <<
-                                 ' ' << timer_complex_case.elapsed_microseconds();
-                }
-
-                std::cout <<
-# ifdef OSMIUM_AREA_CHECK_INNER_OUTER_ROLES
-                             ' ' << timer_roles.elapsed_microseconds() <<
-# else
-                             " 0" <<
-# endif
-                             '\n';
-#endif
-
-                return true;
-            }
-
-#ifdef OSMIUM_WITH_TIMER
-            static bool print_header() {
-                std::cout << "nodes outer_rings inner_rings sort dupl intersection locations split simple_case complex_case roles_check\n";
-                return true;
-            }
-
-            static bool init_header() {
-                static bool printed_print_header = print_header();
-                return printed_print_header;
-            }
-#endif
-
             bool create_area(osmium::memory::Buffer& out_buffer, const osmium::Way& way) {
                 osmium::builder::AreaBuilder builder{out_buffer};
                 builder.initialize_from_object(way);
 
                 const bool area_okay = create_rings();
-                if (area_okay || m_config.create_empty_areas) {
+                if (area_okay || config().create_empty_areas) {
                     add_tags_to_area(builder, way);
                 }
                 if (area_okay) {
@@ -1374,19 +194,19 @@ namespace osmium {
                 }
 
                 if (report_ways()) {
-                    m_config.problem_reporter->report_way(way);
+                    config().problem_reporter->report_way(way);
                 }
 
-                return area_okay || m_config.create_empty_areas;
+                return area_okay || config().create_empty_areas;
             }
 
             bool create_area(osmium::memory::Buffer& out_buffer, const osmium::Relation& relation, const std::vector<const osmium::Way*>& members) {
-                m_num_members = members.size();
+                set_num_members(members.size());
                 osmium::builder::AreaBuilder builder{out_buffer};
                 builder.initialize_from_object(relation);
 
                 const bool area_okay = create_rings();
-                if (area_okay || m_config.create_empty_areas) {
+                if (area_okay || config().create_empty_areas) {
                     add_tags_to_area(builder, relation);
                 }
                 if (area_okay) {
@@ -1395,11 +215,11 @@ namespace osmium {
 
                 if (report_ways()) {
                     for (const osmium::Way* way : members) {
-                        m_config.problem_reporter->report_way(*way);
+                        config().problem_reporter->report_way(*way);
                     }
                 }
 
-                return area_okay || m_config.create_empty_areas;
+                return area_okay || config().create_empty_areas;
             }
 
         public:
@@ -1407,11 +227,7 @@ namespace osmium {
             using config_type = osmium::area::AssemblerConfig;
 
             explicit Assembler(const config_type& config) :
-                m_config(config),
-                m_segment_list(config.debug_level > 1) {
-#ifdef OSMIUM_WITH_TIMER
-                init_header();
-#endif
+                detail::BasicAssembler(config) {
             }
 
             ~Assembler() noexcept = default;
@@ -1419,52 +235,63 @@ namespace osmium {
             /**
              * Assemble an area from the given way.
              * The resulting area is put into the out_buffer.
+             *
+             * @returns false if there was some kind of error building the
+             *          area, true otherwise.
              */
-            void operator()(const osmium::Way& way, osmium::memory::Buffer& out_buffer) {
-                if (!m_config.create_way_polygons) {
-                    return;
+            bool operator()(const osmium::Way& way, osmium::memory::Buffer& out_buffer) {
+                if (!config().create_way_polygons) {
+                    return true;
                 }
 
                 if (way.tags().has_tag("area", "no")) {
-                    return;
+                    return true;
                 }
 
-                if (m_config.problem_reporter) {
-                    m_config.problem_reporter->set_object(osmium::item_type::way, way.id());
-                    m_config.problem_reporter->set_nodes(way.nodes().size());
+                if (config().problem_reporter) {
+                    config().problem_reporter->set_object(osmium::item_type::way, way.id());
+                    config().problem_reporter->set_nodes(way.nodes().size());
                 }
 
                 // Ignore (but count) ways without segments.
                 if (way.nodes().size() < 2) {
-                    ++m_stats.short_ways;
-                    return;
+                    ++stats().short_ways;
+                    return false;
                 }
 
                 if (!way.ends_have_same_id()) {
-                    ++m_stats.duplicate_nodes;
-                    if (m_config.problem_reporter) {
-                        m_config.problem_reporter->report_duplicate_node(way.nodes().front().ref(), way.nodes().back().ref(), way.nodes().front().location());
+                    ++stats().duplicate_nodes;
+                    if (config().problem_reporter) {
+                        config().problem_reporter->report_duplicate_node(way.nodes().front().ref(), way.nodes().back().ref(), way.nodes().front().location());
                     }
                 }
 
-                ++m_stats.from_ways;
-                m_stats.duplicate_nodes += m_segment_list.extract_segments_from_way(m_config.problem_reporter, way);
+                ++stats().from_ways;
+                stats().invalid_locations = segment_list().extract_segments_from_way(config().problem_reporter,
+                                                                                     stats().duplicate_nodes,
+                                                                                     way);
+                if (!config().ignore_invalid_locations && stats().invalid_locations > 0) {
+                    return false;
+                }
 
-                if (m_config.debug_level > 0) {
-                    std::cerr << "\nAssembling way " << way.id() << " containing " << m_segment_list.size() << " nodes\n";
+                if (config().debug_level > 0) {
+                    std::cerr << "\nAssembling way " << way.id() << " containing " << segment_list().size() << " nodes\n";
                 }
 
                 // Now create the Area object and add the attributes and tags
                 // from the way.
-                if (create_area(out_buffer, way)) {
+                const bool okay = create_area(out_buffer, way);
+                if (okay) {
                     out_buffer.commit();
                 } else {
                     out_buffer.rollback();
                 }
 
                 if (debug()) {
-                    std::cerr << "Done: " << m_stats << "\n";
+                    std::cerr << "Done: " << stats() << "\n";
                 }
+
+                return okay;
             }
 
             /**
@@ -1489,38 +316,48 @@ namespace osmium {
             /**
              * Assemble an area from the given relation and its members.
              * The resulting area is put into the out_buffer.
+             *
+             * @returns false if there was some kind of error building the
+             *          area(s), true otherwise.
              */
-            void operator()(const osmium::Relation& relation, const std::vector<const osmium::Way*>& members, osmium::memory::Buffer& out_buffer) {
+            bool operator()(const osmium::Relation& relation, const std::vector<const osmium::Way*>& members, osmium::memory::Buffer& out_buffer) {
                 assert(relation.members().size() >= members.size());
 
-                if (m_config.problem_reporter) {
-                    m_config.problem_reporter->set_object(osmium::item_type::relation, relation.id());
+                if (config().problem_reporter) {
+                    config().problem_reporter->set_object(osmium::item_type::relation, relation.id());
                 }
 
                 if (relation.members().empty()) {
-                    ++m_stats.no_way_in_mp_relation;
-                    return;
+                    ++stats().no_way_in_mp_relation;
+                    return false;
                 }
 
-                ++m_stats.from_relations;
-                m_stats.duplicate_nodes += m_segment_list.extract_segments_from_ways(m_config.problem_reporter, relation, members);
-                m_stats.member_ways = members.size();
+                ++stats().from_relations;
+                stats().invalid_locations = segment_list().extract_segments_from_ways(config().problem_reporter,
+                                                                                      stats().duplicate_nodes,
+                                                                                      relation,
+                                                                                      members);
+                if (!config().ignore_invalid_locations && stats().invalid_locations > 0) {
+                    return false;
+                }
+                stats().member_ways = members.size();
 
-                if (m_stats.member_ways == 1) {
-                    ++m_stats.single_way_in_mp_relation;
+                if (stats().member_ways == 1) {
+                    ++stats().single_way_in_mp_relation;
                 }
 
-                if (m_config.debug_level > 0) {
-                    std::cerr << "\nAssembling relation " << relation.id() << " containing " << members.size() << " way members with " << m_segment_list.size() << " nodes\n";
+                if (config().debug_level > 0) {
+                    std::cerr << "\nAssembling relation " << relation.id() << " containing " << members.size() << " way members with " << segment_list().size() << " nodes\n";
                 }
 
                 const size_t area_offset = out_buffer.committed();
 
                 // Now create the Area object and add the attributes and tags
                 // from the relation.
-                if (create_area(out_buffer, relation, members)) {
-                    if ((m_config.create_new_style_polygons && m_stats.no_tags_on_relation == 0) ||
-                        (m_config.create_old_style_polygons && m_stats.no_tags_on_relation != 0)) {
+                bool okay = create_area(out_buffer, relation, members);
+                if (okay) {
+                    if ((config().create_new_style_polygons && stats().no_tags_on_relation == 0) ||
+                        (config().create_old_style_polygons && stats().no_tags_on_relation != 0)) {
                         out_buffer.commit();
                     } else {
                         out_buffer.rollback();
@@ -1536,23 +373,23 @@ namespace osmium {
                 // just built, add them to a list and later build areas for
                 // them, too.
                 std::vector<const osmium::Way*> ways_that_should_be_areas;
-                if (m_stats.wrong_role == 0) {
+                if (stats().wrong_role == 0) {
                     detail::for_each_member(relation, members, [this, &ways_that_should_be_areas, &area_tags](const osmium::RelationMember& member, const osmium::Way& way) {
                         if (!std::strcmp(member.role(), "inner")) {
                             if (!way.nodes().empty() && way.is_closed() && way.tags().size() > 0) {
-                                const auto d = std::count_if(way.tags().cbegin(), way.tags().cend(), filter());
+                                const auto d = std::count_if(way.tags().cbegin(), way.tags().cend(), std::cref(filter()));
                                 if (d > 0) {
-                                    osmium::tags::KeyFilter::iterator way_fi_begin(filter(), way.tags().cbegin(), way.tags().cend());
-                                    osmium::tags::KeyFilter::iterator way_fi_end(filter(), way.tags().cend(), way.tags().cend());
-                                    osmium::tags::KeyFilter::iterator area_fi_begin(filter(), area_tags.cbegin(), area_tags.cend());
-                                    osmium::tags::KeyFilter::iterator area_fi_end(filter(), area_tags.cend(), area_tags.cend());
+                                    osmium::tags::KeyFilter::iterator way_fi_begin(std::cref(filter()), way.tags().cbegin(), way.tags().cend());
+                                    osmium::tags::KeyFilter::iterator way_fi_end(std::cref(filter()), way.tags().cend(), way.tags().cend());
+                                    osmium::tags::KeyFilter::iterator area_fi_begin(std::cref(filter()), area_tags.cbegin(), area_tags.cend());
+                                    osmium::tags::KeyFilter::iterator area_fi_end(std::cref(filter()), area_tags.cend(), area_tags.cend());
 
                                     if (!std::equal(way_fi_begin, way_fi_end, area_fi_begin) || d != std::distance(area_fi_begin, area_fi_end)) {
                                         ways_that_should_be_areas.push_back(&way);
                                     } else {
-                                        ++m_stats.inner_with_same_tags;
-                                        if (m_config.problem_reporter) {
-                                            m_config.problem_reporter->report_inner_with_same_tags(way);
+                                        ++stats().inner_with_same_tags;
+                                        if (config().problem_reporter) {
+                                            config().problem_reporter->report_inner_with_same_tags(way);
                                         }
                                     }
                                 }
@@ -1562,22 +399,18 @@ namespace osmium {
                 }
 
                 if (debug()) {
-                    std::cerr << "Done: " << m_stats << "\n";
+                    std::cerr << "Done: " << stats() << "\n";
                 }
 
                 // Now build areas for all ways found in the last step.
                 for (const osmium::Way* way : ways_that_should_be_areas) {
-                    Assembler assembler(m_config);
-                    assembler(*way, out_buffer);
+                    Assembler assembler{config()};
+                    if (!assembler(*way, out_buffer)) {
+                        okay = false;
+                    }
                 }
-            }
 
-            /**
-             * Get statistics from assembler. Call this after running the
-             * assembler to get statistics and data about errors.
-             */
-            const osmium::area::area_stats& stats() const noexcept {
-                return m_stats;
+                return okay;
             }
 
         }; // class Assembler
diff --git a/include/osmium/area/assembler_config.hpp b/include/osmium/area/assembler_config.hpp
new file mode 100644
index 0000000..2e49080
--- /dev/null
+++ b/include/osmium/area/assembler_config.hpp
@@ -0,0 +1,152 @@
+#ifndef OSMIUM_AREA_ASSEMBLER_CONFIG_HPP
+#define OSMIUM_AREA_ASSEMBLER_CONFIG_HPP
+
+/*
+
+This file is part of Osmium (http://osmcode.org/libosmium).
+
+Copyright 2013-2017 Jochen Topf <jochen at topf.org> and others (see README).
+
+Boost Software License - Version 1.0 - August 17th, 2003
+
+Permission is hereby granted, free of charge, to any person or organization
+obtaining a copy of the software and accompanying documentation covered by
+this license (the "Software") to use, reproduce, display, distribute,
+execute, and transmit the Software, and to prepare derivative works of the
+Software, and to permit third-parties to whom the Software is furnished to
+do so, all subject to the following:
+
+The copyright notices in the Software and this entire statement, including
+the above license grant, this restriction and the following disclaimer,
+must be included in all copies of the Software, in whole or in part, and
+all derivative works of the Software, unless such copies or derivative
+works are solely in the form of machine-executable object code generated by
+a source language processor.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
+SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
+FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+*/
+
+#include <osmium/util/compatibility.hpp>
+
+namespace osmium {
+
+    namespace area {
+
+        class ProblemReporter;
+
+        /**
+         * Configuration for osmium::area::Assembler objects. Create this
+         * once, set the options you want and then re-use it every time you
+         * create an Assembler object.
+         */
+        struct AssemblerConfig {
+
+            /**
+             * Optional pointer to problem reporter.
+             */
+            osmium::area::ProblemReporter* problem_reporter = nullptr;
+
+            /**
+             * Debug level. If this is greater than zero, debug messages will
+             * be printed to stderr. Available levels are 1 to 3. Note that
+             * level 2 and above will generate a lot of messages!
+             */
+            int debug_level = 0;
+
+            /**
+             * The roles of multipolygon members are ignored when assembling
+             * multipolygons, because they are often missing or wrong. If this
+             * is set, the roles are checked after the multipolygons are built
+             * against what the assembly process decided where the inner and
+             * outer rings are. This slows down the processing, so it only
+             * makes sense if you want to get the problem reports.
+             */
+            bool check_roles = false;
+
+            /**
+             * When the assembler can't create an area, usually because its
+             * geometry would be invalid, it will create an "empty" area object
+             * without rings. This allows you to detect where an area was
+             * invalid.
+             *
+             * If this is set to false, invalid areas will simply be discarded.
+             */
+            bool create_empty_areas = true;
+
+            /**
+             * Create areas for (multi)polygons where the tags are on the
+             * relation.
+             *
+             * If this is set to false, those areas will simply be discarded.
+             */
+            bool create_new_style_polygons = true;
+
+            /**
+             * Create areas for (multi)polygons where the tags are on the
+             * outer way(s).
+             *
+             * If this is set to false, those areas will simply be discarded.
+             */
+            bool create_old_style_polygons = true;
+
+            /**
+             * Create areas for polygons created from ways.
+             *
+             * If this is set to false, those areas will simply be discarded.
+             */
+            bool create_way_polygons = true;
+
+            /**
+             * Keep the type tag from multipolygon relations on the area
+             * object. By default this is false, and the type tag will be
+             * removed.
+             */
+            bool keep_type_tag = false;
+
+            /**
+             * If there is an invalid location in any of the ways needed for
+             * assembling the multipolygon, the assembler will normally fail.
+             * If this is set, the assembler will silently ignore the invalid
+             * locations pretending them to be not referenced from the ways.
+             * This will allow some areas to be built, others will now be
+             * incorrect. This can sometimes be useful to assemble areas
+             * crossing the boundary of an extract, but you will also get
+             * geometrically valid but wrong (multi)polygons.
+             */
+            bool ignore_invalid_locations = false;
+
+            AssemblerConfig() noexcept = default;
+
+            /**
+             * Constructor
+             * @deprecated Use default constructor and set values afterwards.
+             */
+            explicit AssemblerConfig(osmium::area::ProblemReporter* pr, bool d = false) :
+                problem_reporter(pr),
+                debug_level(d) {
+            }
+
+            /**
+             * Enable or disable debug output to stderr. This is for Osmium
+             * developers only.
+             *
+             * @deprecated Set debug_level directly.
+             */
+            OSMIUM_DEPRECATED void enable_debug_output(bool d = true) {
+                debug_level = d;
+            }
+
+        }; // struct AssemblerConfig
+
+    } // namespace area
+
+} // namespace osmium
+
+#endif // OSMIUM_AREA_ASSEMBLER_CONFIG_HPP
diff --git a/include/osmium/area/detail/basic_assembler.hpp b/include/osmium/area/detail/basic_assembler.hpp
new file mode 100644
index 0000000..13bd976
--- /dev/null
+++ b/include/osmium/area/detail/basic_assembler.hpp
@@ -0,0 +1,1204 @@
+#ifndef OSMIUM_AREA_DETAIL_BASIC_ASSEMBLER_HPP
+#define OSMIUM_AREA_DETAIL_BASIC_ASSEMBLER_HPP
+
+/*
+
+This file is part of Osmium (http://osmcode.org/libosmium).
+
+Copyright 2013-2017 Jochen Topf <jochen at topf.org> and others (see README).
+
+Boost Software License - Version 1.0 - August 17th, 2003
+
+Permission is hereby granted, free of charge, to any person or organization
+obtaining a copy of the software and accompanying documentation covered by
+this license (the "Software") to use, reproduce, display, distribute,
+execute, and transmit the Software, and to prepare derivative works of the
+Software, and to permit third-parties to whom the Software is furnished to
+do so, all subject to the following:
+
+The copyright notices in the Software and this entire statement, including
+the above license grant, this restriction and the following disclaimer,
+must be included in all copies of the Software, in whole or in part, and
+all derivative works of the Software, unless such copies or derivative
+works are solely in the form of machine-executable object code generated by
+a source language processor.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
+SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
+FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+*/
+
+#include <algorithm>
+#include <cassert>
+#include <cstdint>
+#include <cstdlib>
+#include <cstring>
+#include <iostream>
+#include <iterator>
+#include <list>
+#include <unordered_map>
+#include <unordered_set>
+#include <utility>
+#include <vector>
+
+#include <osmium/builder/osm_object_builder.hpp>
+#include <osmium/memory/buffer.hpp>
+#include <osmium/osm/area.hpp>
+#include <osmium/osm/item_type.hpp>
+#include <osmium/osm/location.hpp>
+#include <osmium/osm/node_ref.hpp>
+#include <osmium/osm/relation.hpp>
+#include <osmium/osm/types.hpp>
+#include <osmium/osm/way.hpp>
+#include <osmium/util/iterator.hpp>
+#include <osmium/util/timer.hpp>
+
+#include <osmium/area/assembler_config.hpp>
+#include <osmium/area/detail/node_ref_segment.hpp>
+#include <osmium/area/detail/proto_ring.hpp>
+#include <osmium/area/detail/segment_list.hpp>
+#include <osmium/area/problem_reporter.hpp>
+#include <osmium/area/stats.hpp>
+
+namespace osmium {
+
+    namespace area {
+
+        namespace detail {
+
+            using open_ring_its_type = std::list<std::list<detail::ProtoRing>::iterator>;
+
+            struct location_to_ring_map {
+                osmium::Location location;
+                open_ring_its_type::iterator ring_it;
+                bool start;
+
+                location_to_ring_map(const osmium::Location& l, const open_ring_its_type::iterator& r, bool s) noexcept :
+                    location(l),
+                    ring_it(r),
+                    start(s) {
+                }
+
+                explicit location_to_ring_map(const osmium::Location& l) noexcept :
+                    location(l),
+                    ring_it(),
+                    start(false) {
+                }
+
+                const detail::ProtoRing& ring() const noexcept {
+                    return **ring_it;
+                }
+
+            }; // struct location_to_ring_map
+
+            inline bool operator==(const location_to_ring_map& lhs, const location_to_ring_map& rhs) noexcept {
+                return lhs.location == rhs.location;
+            }
+
+            inline bool operator<(const location_to_ring_map& lhs, const location_to_ring_map& rhs) noexcept {
+                return lhs.location < rhs.location;
+            }
+
+            /**
+             * Class for assembling ways and relations into multipolygons
+             * (areas). Contains the basic functionality needed but is not
+             * used directly. Use the osmium::area::Assembler class instead.
+             */
+            class BasicAssembler {
+
+                struct slocation {
+
+                    static constexpr const uint32_t invalid_item = 1 << 30;
+
+                    uint32_t item : 31;
+                    uint32_t reverse : 1;
+
+                    slocation() noexcept :
+                        item(invalid_item),
+                        reverse(false) {
+                    }
+
+                    explicit slocation(uint32_t n, bool r = false) noexcept :
+                        item(n),
+                        reverse(r) {
+                    }
+
+                    osmium::Location location(const detail::SegmentList& segment_list) const noexcept {
+                        const auto& segment = segment_list[item];
+                        return reverse ? segment.second().location() : segment.first().location();
+                    }
+
+                    const osmium::NodeRef& node_ref(const detail::SegmentList& segment_list) const noexcept {
+                        const auto& segment = segment_list[item];
+                        return reverse ? segment.second() : segment.first();
+                    }
+
+                    osmium::Location location(const detail::SegmentList& segment_list, const osmium::Location& default_location) const noexcept {
+                        if (item == invalid_item) {
+                            return default_location;
+                        }
+                        return location(segment_list);
+                    }
+
+                }; // struct slocation
+
+                // Configuration settings for this Assembler
+                const AssemblerConfig& m_config;
+
+                // List of segments (connection between two nodes)
+                osmium::area::detail::SegmentList m_segment_list;
+
+                // The rings we are building from the segments
+                std::list<detail::ProtoRing> m_rings;
+
+                // All node locations
+                std::vector<slocation> m_locations;
+
+                // All locations where more than two segments start/end
+                std::vector<Location> m_split_locations;
+
+                // Statistics
+                area_stats m_stats;
+
+                // The number of members the multipolygon relation has
+                size_t m_num_members = 0;
+
+                template <typename TBuilder>
+                static void build_ring_from_proto_ring(osmium::builder::AreaBuilder& builder, const detail::ProtoRing& ring) {
+                    TBuilder ring_builder{builder};
+                    ring_builder.add_node_ref(ring.get_node_ref_start());
+                    for (const auto& segment : ring.segments()) {
+                        ring_builder.add_node_ref(segment->stop());
+                    }
+                }
+
+                void check_inner_outer_roles() {
+                    if (debug()) {
+                        std::cerr << "    Checking inner/outer roles\n";
+                    }
+
+                    std::unordered_map<const osmium::Way*, const detail::ProtoRing*> way_rings;
+                    std::unordered_set<const osmium::Way*> ways_in_multiple_rings;
+
+                    for (const detail::ProtoRing& ring : m_rings) {
+                        for (const auto& segment : ring.segments()) {
+                            assert(segment->way());
+
+                            if (!segment->role_empty() && (ring.is_outer() ? !segment->role_outer() : !segment->role_inner())) {
+                                ++m_stats.wrong_role;
+                                if (debug()) {
+                                    std::cerr << "      Segment " << *segment << " from way " << segment->way()->id() << " has role '" << segment->role_name()
+                                            << "', but should have role '" << (ring.is_outer() ? "outer" : "inner") << "'\n";
+                                }
+                                if (m_config.problem_reporter) {
+                                    if (ring.is_outer()) {
+                                        m_config.problem_reporter->report_role_should_be_outer(segment->way()->id(), segment->first().location(), segment->second().location());
+                                    } else {
+                                        m_config.problem_reporter->report_role_should_be_inner(segment->way()->id(), segment->first().location(), segment->second().location());
+                                    }
+                                }
+                            }
+
+                            auto& r = way_rings[segment->way()];
+                            if (!r) {
+                                r = ˚
+                            } else if (r != &ring) {
+                                ways_in_multiple_rings.insert(segment->way());
+                            }
+
+                        }
+                    }
+
+                    for (const osmium::Way* way : ways_in_multiple_rings) {
+                        ++m_stats.ways_in_multiple_rings;
+                        if (debug()) {
+                            std::cerr << "      Way " << way->id() << " is in multiple rings\n";
+                        }
+                        if (m_config.problem_reporter) {
+                            m_config.problem_reporter->report_way_in_multiple_rings(*way);
+                        }
+                    }
+
+                }
+
+                detail::NodeRefSegment* get_next_segment(const osmium::Location& location) {
+                    auto it = std::lower_bound(m_locations.begin(), m_locations.end(), slocation{}, [this, &location](const slocation& lhs, const slocation& rhs) {
+                        return lhs.location(m_segment_list, location) < rhs.location(m_segment_list, location);
+                    });
+
+                    assert(it != m_locations.end());
+                    if (m_segment_list[it->item].is_done()) {
+                        ++it;
+                    }
+                    assert(it != m_locations.end());
+
+                    assert(!m_segment_list[it->item].is_done());
+                    return &m_segment_list[it->item];
+                }
+
+                class rings_stack_element {
+
+                    int32_t m_y;
+                    detail::ProtoRing* m_ring_ptr;
+
+                public:
+
+                    rings_stack_element(int32_t y, detail::ProtoRing* ring_ptr) :
+                        m_y(y),
+                        m_ring_ptr(ring_ptr) {
+                    }
+
+                    int32_t y() const noexcept {
+                        return m_y;
+                    }
+
+                    const detail::ProtoRing& ring() const noexcept {
+                        return *m_ring_ptr;
+                    }
+
+                    detail::ProtoRing* ring_ptr() noexcept {
+                        return m_ring_ptr;
+                    }
+
+                    bool operator==(const rings_stack_element& rhs) const noexcept {
+                        return m_ring_ptr == rhs.m_ring_ptr;
+                    }
+
+                    bool operator<(const rings_stack_element& rhs) const noexcept {
+                        return m_y < rhs.m_y;
+                    }
+
+                }; // class ring_stack_element
+
+                using rings_stack = std::vector<rings_stack_element>;
+
+                void remove_duplicates(rings_stack& outer_rings) {
+                    while (true) {
+                        const auto it = std::adjacent_find(outer_rings.begin(), outer_rings.end());
+                        if (it == outer_rings.end()) {
+                            return;
+                        }
+                        outer_rings.erase(it, std::next(it, 2));
+                    }
+                }
+
+                detail::ProtoRing* find_enclosing_ring(detail::NodeRefSegment* segment) {
+                    if (debug()) {
+                        std::cerr << "    Looking for ring enclosing " << *segment << "\n";
+                    }
+
+                    const auto location = segment->first().location();
+                    const auto end_location = segment->second().location();
+
+                    while (segment->first().location() == location) {
+                        if (segment == &m_segment_list.back()) {
+                            break;
+                        }
+                        ++segment;
+                    }
+
+                    int nesting = 0;
+
+                    rings_stack outer_rings;
+                    while (segment >= &m_segment_list.front()) {
+                        if (!segment->is_direction_done()) {
+                            --segment;
+                            continue;
+                        }
+                        if (debug()) {
+                            std::cerr << "      Checking against " << *segment << "\n";
+                        }
+                        const osmium::Location& a = segment->first().location();
+                        const osmium::Location& b = segment->second().location();
+
+                        if (segment->first().location() == location) {
+                            const int64_t ax = a.x();
+                            const int64_t bx = b.x();
+                            const int64_t lx = end_location.x();
+                            const int64_t ay = a.y();
+                            const int64_t by = b.y();
+                            const int64_t ly = end_location.y();
+                            const auto z = (bx - ax)*(ly - ay) - (by - ay)*(lx - ax);
+                            if (debug()) {
+                                std::cerr << "      Segment XXXX z=" << z << "\n";
+                            }
+                            if (z > 0) {
+                                nesting += segment->is_reverse() ? -1 : 1;
+                                if (debug()) {
+                                    std::cerr << "        Segment is below (nesting=" << nesting << ")\n";
+                                }
+                                if (segment->ring()->is_outer()) {
+                                    if (debug()) {
+                                        std::cerr << "        Segment belongs to outer ring\n";
+                                    }
+                                    outer_rings.emplace_back(a.y(), segment->ring());
+                                }
+                            }
+                        } else if (a.x() <= location.x() && location.x() < b.x()) {
+                            if (debug()) {
+                                std::cerr << "        Is in x range\n";
+                            }
+
+                            const int64_t ax = a.x();
+                            const int64_t bx = b.x();
+                            const int64_t lx = location.x();
+                            const int64_t ay = a.y();
+                            const int64_t by = b.y();
+                            const int64_t ly = location.y();
+                            const auto z = (bx - ax)*(ly - ay) - (by - ay)*(lx - ax);
+
+                            if (z >= 0) {
+                                nesting += segment->is_reverse() ? -1 : 1;
+                                if (debug()) {
+                                    std::cerr << "        Segment is below (nesting=" << nesting << ")\n";
+                                }
+                                if (segment->ring()->is_outer()) {
+                                    if (debug()) {
+                                        std::cerr << "        Segment belongs to outer ring\n";
+                                    }
+                                    const int32_t y = int32_t(ay + (by - ay) * (lx - ax) / (bx - ax));
+                                    outer_rings.emplace_back(y, segment->ring());
+                                }
+                            }
+                        }
+                        --segment;
+                    }
+
+                    if (nesting % 2 == 0) {
+                        if (debug()) {
+                            std::cerr << "    Decided that this is an outer ring\n";
+                        }
+                        return nullptr;
+                    } else {
+                        if (debug()) {
+                            std::cerr << "    Decided that this is an inner ring\n";
+                        }
+                        assert(!outer_rings.empty());
+
+                        std::sort(outer_rings.rbegin(), outer_rings.rend());
+                        if (debug()) {
+                            for (const auto& o : outer_rings) {
+                                std::cerr << "        y=" << o.y() << " " << o.ring() << "\n";
+                            }
+                        }
+
+                        remove_duplicates(outer_rings);
+                        if (debug()) {
+                            std::cerr << "      after remove duplicates:\n";
+                            for (const auto& o : outer_rings) {
+                                std::cerr << "        y=" << o.y() << " " << o.ring() << "\n";
+                            }
+                        }
+
+                        assert(!outer_rings.empty());
+                        return outer_rings.front().ring_ptr();
+                    }
+                }
+
+                bool is_split_location(const osmium::Location& location) const noexcept {
+                    return std::find(m_split_locations.cbegin(), m_split_locations.cend(), location) != m_split_locations.cend();
+                }
+
+                uint32_t add_new_ring(slocation& node) {
+                    detail::NodeRefSegment* segment = &m_segment_list[node.item];
+                    assert(!segment->is_done());
+
+                    if (debug()) {
+                        std::cerr << "  Starting new ring at location " << node.location(m_segment_list) << " with segment " << *segment << "\n";
+                    }
+
+                    if (node.reverse) {
+                        segment->reverse();
+                    }
+
+                    detail::ProtoRing* outer_ring = nullptr;
+
+                    if (segment != &m_segment_list.front()) {
+                        outer_ring = find_enclosing_ring(segment);
+                    }
+                    segment->mark_direction_done();
+
+                    m_rings.emplace_back(segment);
+                    detail::ProtoRing* ring = &m_rings.back();
+                    if (outer_ring) {
+                        if (debug()) {
+                            std::cerr << "    This is an inner ring. Outer ring is " << *outer_ring << "\n";
+                        }
+                        outer_ring->add_inner_ring(ring);
+                        ring->set_outer_ring(outer_ring);
+                    } else if (debug()) {
+                        std::cerr << "    This is an outer ring\n";
+                    }
+
+                    const osmium::Location& first_location = node.location(m_segment_list);
+                    osmium::Location last_location = segment->stop().location();
+
+                    uint32_t nodes = 1;
+                    while (first_location != last_location) {
+                        ++nodes;
+                        detail::NodeRefSegment* next_segment = get_next_segment(last_location);
+                        next_segment->mark_direction_done();
+                        if (next_segment->start().location() != last_location) {
+                            next_segment->reverse();
+                        }
+                        ring->add_segment_back(next_segment);
+                        if (debug()) {
+                            std::cerr << "    Next segment is " << *next_segment << "\n";
+                        }
+                        last_location = next_segment->stop().location();
+                    }
+
+                    ring->fix_direction();
+
+                    if (debug()) {
+                        std::cerr << "    Completed ring: " << *ring << "\n";
+                    }
+
+                    return nodes;
+                }
+
+                uint32_t add_new_ring_complex(slocation& node) {
+                    detail::NodeRefSegment* segment = &m_segment_list[node.item];
+                    assert(!segment->is_done());
+
+                    if (debug()) {
+                        std::cerr << "  Starting new ring at location " << node.location(m_segment_list) << " with segment " << *segment << "\n";
+                    }
+
+                    if (node.reverse) {
+                        segment->reverse();
+                    }
+
+                    m_rings.emplace_back(segment);
+                    detail::ProtoRing* ring = &m_rings.back();
+
+                    const osmium::Location& first_location = node.location(m_segment_list);
+                    osmium::Location last_location = segment->stop().location();
+
+                    uint32_t nodes = 1;
+                    while (first_location != last_location && !is_split_location(last_location)) {
+                        ++nodes;
+                        detail::NodeRefSegment* next_segment = get_next_segment(last_location);
+                        if (next_segment->start().location() != last_location) {
+                            next_segment->reverse();
+                        }
+                        ring->add_segment_back(next_segment);
+                        if (debug()) {
+                            std::cerr << "    Next segment is " << *next_segment << "\n";
+                        }
+                        last_location = next_segment->stop().location();
+                    }
+
+                    if (debug()) {
+                        if (first_location == last_location) {
+                            std::cerr << "    Completed ring: " << *ring << "\n";
+                        } else {
+                            std::cerr << "    Completed partial ring: " << *ring << "\n";
+                        }
+                    }
+
+                    return nodes;
+                }
+
+                void create_locations_list() {
+                    m_locations.reserve(m_segment_list.size() * 2);
+
+                    for (uint32_t n = 0; n < m_segment_list.size(); ++n) {
+                        m_locations.emplace_back(n, false);
+                        m_locations.emplace_back(n, true);
+                    }
+
+                    std::stable_sort(m_locations.begin(), m_locations.end(), [this](const slocation& lhs, const slocation& rhs) {
+                        return lhs.location(m_segment_list) < rhs.location(m_segment_list);
+                    });
+                }
+
+                void find_inner_outer_complex(detail::ProtoRing* ring) {
+                    detail::ProtoRing* outer_ring = find_enclosing_ring(ring->min_segment());
+                    if (outer_ring) {
+                        outer_ring->add_inner_ring(ring);
+                        ring->set_outer_ring(outer_ring);
+                    }
+                    ring->fix_direction();
+                    ring->mark_direction_done();
+                }
+
+                void find_inner_outer_complex() {
+                    if (debug()) {
+                        std::cerr << "  Finding inner/outer rings\n";
+                    }
+                    std::vector<detail::ProtoRing*> rings;
+                    rings.reserve(m_rings.size());
+                    for (auto& ring : m_rings) {
+                        if (ring.closed()) {
+                            rings.push_back(&ring);
+                        }
+                    }
+
+                    if (rings.empty()) {
+                        return;
+                    }
+
+                    std::sort(rings.begin(), rings.end(), [](detail::ProtoRing* a, detail::ProtoRing* b) {
+                        return a->min_segment() < b->min_segment();
+                    });
+
+                    rings.front()->fix_direction();
+                    rings.front()->mark_direction_done();
+                    if (debug()) {
+                        std::cerr << "    First ring is outer: " << *rings.front() << "\n";
+                    }
+                    for (auto it = std::next(rings.begin()); it != rings.end(); ++it) {
+                        if (debug()) {
+                            std::cerr << "    Checking (at min segment " << *((*it)->min_segment()) << ") ring " << **it << "\n";
+                        }
+                        find_inner_outer_complex(*it);
+                        if (debug()) {
+                            std::cerr << "    Ring is " << ((*it)->is_outer() ? "OUTER: " : "INNER: ") << **it << "\n";
+                        }
+                    }
+                }
+
+                /**
+                 * Finds all locations where more than two segments meet. If there
+                 * are any open rings found along the way, they are reported
+                 * and the function returns false.
+                 */
+                bool find_split_locations() {
+                    osmium::Location previous_location;
+                    for (auto it = m_locations.cbegin(); it != m_locations.cend(); ++it) {
+                        const osmium::NodeRef& nr = it->node_ref(m_segment_list);
+                        const osmium::Location& loc = nr.location();
+                        if (std::next(it) == m_locations.cend() || loc != std::next(it)->location(m_segment_list)) {
+                            if (debug()) {
+                                std::cerr << "  Found open ring at " << nr << "\n";
+                            }
+                            if (m_config.problem_reporter) {
+                                const auto& segment = m_segment_list[it->item];
+                                m_config.problem_reporter->report_ring_not_closed(nr, segment.way());
+                            }
+                            ++m_stats.open_rings;
+                        } else {
+                            if (loc == previous_location && (m_split_locations.empty() || m_split_locations.back() != previous_location )) {
+                                m_split_locations.push_back(previous_location);
+                            }
+                            ++it;
+                            if (it == m_locations.end()) {
+                                break;
+                            }
+                        }
+                        previous_location = loc;
+                    }
+                    return m_stats.open_rings == 0;
+                }
+
+                void create_rings_simple_case() {
+                    auto count_remaining = m_segment_list.size();
+                    for (slocation& sl : m_locations) {
+                        const detail::NodeRefSegment& segment = m_segment_list[sl.item];
+                        if (!segment.is_done()) {
+                            count_remaining -= add_new_ring(sl);
+                            if (count_remaining == 0) {
+                                return;
+                            }
+                        }
+                    }
+                }
+
+                std::vector<location_to_ring_map> create_location_to_ring_map(open_ring_its_type& open_ring_its) {
+                    std::vector<location_to_ring_map> xrings;
+                    xrings.reserve(open_ring_its.size() * 2);
+
+                    for (auto it = open_ring_its.begin(); it != open_ring_its.end(); ++it) {
+                        if (debug()) {
+                            std::cerr << "      Ring: " << **it << "\n";
+                        }
+                        xrings.emplace_back((*it)->get_node_ref_start().location(), it, true);
+                        xrings.emplace_back((*it)->get_node_ref_stop().location(), it, false);
+                    }
+
+                    std::sort(xrings.begin(), xrings.end());
+
+                    return xrings;
+                }
+
+                void merge_two_rings(open_ring_its_type& open_ring_its, const location_to_ring_map& m1, const location_to_ring_map& m2) {
+                    auto& r1 = *m1.ring_it;
+                    auto& r2 = *m2.ring_it;
+
+                    if (r1->get_node_ref_stop().location() == r2->get_node_ref_start().location()) {
+                        r1->join_forward(*r2);
+                    } else if (r1->get_node_ref_stop().location() == r2->get_node_ref_stop().location()) {
+                        r1->join_backward(*r2);
+                    } else if (r1->get_node_ref_start().location() == r2->get_node_ref_start().location()) {
+                        r1->reverse();
+                        r1->join_forward(*r2);
+                    } else if (r1->get_node_ref_start().location() == r2->get_node_ref_stop().location()) {
+                        r1->reverse();
+                        r1->join_backward(*r2);
+                    } else {
+                        assert(false);
+                    }
+
+                    m_rings.erase(r2);
+                    open_ring_its.remove(r2);
+
+                    if (r1->closed()) {
+                        open_ring_its.remove(r1);
+                    }
+                }
+
+                bool try_to_merge(open_ring_its_type& open_ring_its) {
+                    if (open_ring_its.empty()) {
+                        return false;
+                    }
+
+                    if (debug()) {
+                        std::cerr << "    Trying to merge " << open_ring_its.size() << " open rings\n";
+                    }
+
+                    std::vector<location_to_ring_map> xrings = create_location_to_ring_map(open_ring_its);
+
+                    auto it = xrings.cbegin();
+                    while (it != xrings.cend()) {
+                        it = std::adjacent_find(it, xrings.cend());
+                        if (it == xrings.cend()) {
+                            return false;
+                        }
+                        auto after = std::next(it, 2);
+                        if (after == xrings.cend() || after->location != it->location) {
+                            if (debug()) {
+                                std::cerr << "      Merging two rings\n";
+                            }
+                            merge_two_rings(open_ring_its, *it, *std::next(it));
+                            return true;
+                        }
+                        while (it != xrings.cend() && it->location == after->location) {
+                            ++it;
+                        }
+                    }
+
+                    return false;
+                }
+
+                bool there_are_open_rings() const noexcept {
+                    return std::any_of(m_rings.cbegin(), m_rings.cend(), [](const detail::ProtoRing& ring){
+                        return !ring.closed();
+                    });
+                }
+
+                struct candidate {
+                    int64_t sum;
+                    std::vector<std::pair<location_to_ring_map, bool>> rings;
+                    osmium::Location start_location;
+                    osmium::Location stop_location;
+
+                    explicit candidate(location_to_ring_map& ring, bool reverse) :
+                        sum(ring.ring().sum()),
+                        rings(),
+                        start_location(ring.ring().get_node_ref_start().location()),
+                        stop_location(ring.ring().get_node_ref_stop().location()) {
+                        rings.emplace_back(ring, reverse);
+                    }
+
+                    bool closed() const noexcept {
+                        return start_location == stop_location;
+                    }
+
+                };
+
+                void find_candidates(std::vector<candidate>& candidates, std::unordered_set<osmium::Location>& loc_done, const std::vector<location_to_ring_map>& xrings, candidate& cand) {
+                    if (debug()) {
+                        std::cerr << "      find_candidates sum=" << cand.sum << " start=" << cand.start_location << " stop=" << cand.stop_location << "\n";
+                        for (const auto& ring : cand.rings) {
+                            std::cerr << "        " << ring.first.ring() << (ring.second ? " reverse" : "") << "\n";
+                        }
+                    }
+
+                    const auto connections = make_range(std::equal_range(xrings.cbegin(),
+                                                                        xrings.cend(),
+                                                                        location_to_ring_map{cand.stop_location}));
+
+                    assert(connections.begin() != connections.end());
+
+                    assert(!cand.rings.empty());
+                    const detail::ProtoRing* ring_leading_here = &cand.rings.back().first.ring();
+                    for (const location_to_ring_map& m : connections) {
+                        const detail::ProtoRing& ring = m.ring();
+
+                        if (&ring != ring_leading_here) {
+                            if (debug()) {
+                                std::cerr << "        next possible connection: " << ring << (m.start ? "" : " reverse") << "\n";
+                            }
+
+                            candidate c = cand;
+                            if (m.start) {
+                                c.rings.emplace_back(m, false);
+                                c.stop_location = ring.get_node_ref_stop().location();
+                                c.sum += ring.sum();
+                            } else {
+                                c.rings.emplace_back(m, true);
+                                c.stop_location = ring.get_node_ref_start().location();
+                                c.sum -= ring.sum();
+                            }
+                            if (c.closed()) {
+                                if (debug()) {
+                                    std::cerr << "          found candidate\n";
+                                }
+                                candidates.push_back(c);
+                            } else if (loc_done.count(c.stop_location) == 0) {
+                                if (debug()) {
+                                    std::cerr << "          recurse...\n";
+                                }
+                                loc_done.insert(c.stop_location);
+                                find_candidates(candidates, loc_done, xrings, c);
+                                if (debug()) {
+                                    std::cerr << "          ...back\n";
+                                }
+                            } else if (debug()) {
+                                std::cerr << "          loop found\n";
+                            }
+                        }
+                    }
+                }
+
+                /**
+                 * If there are multiple open rings and multiple ways to join them,
+                 * this function is called. It will take the first open ring and
+                 * try recursively all ways of closing it. Of all the candidates
+                 * the one with the smallest area is chosen and closed. If it
+                 * can't close this ring, an error is reported and the function
+                 * returns false.
+                 */
+                bool join_connected_rings(open_ring_its_type& open_ring_its) {
+                    assert(!open_ring_its.empty());
+
+                    if (debug()) {
+                        std::cerr << "    Trying to merge " << open_ring_its.size() << " open rings\n";
+                    }
+
+                    std::vector<location_to_ring_map> xrings = create_location_to_ring_map(open_ring_its);
+
+                    const auto ring_min = std::min_element(xrings.begin(), xrings.end(), [](const location_to_ring_map& lhs, const location_to_ring_map& rhs) {
+                        return lhs.ring().min_segment() < rhs.ring().min_segment();
+                    });
+
+                    find_inner_outer_complex();
+                    detail::ProtoRing* outer_ring = find_enclosing_ring(ring_min->ring().min_segment());
+                    bool ring_min_is_outer = !outer_ring;
+                    if (debug()) {
+                        std::cerr << "  Open ring is " << (ring_min_is_outer ? "outer" : "inner") << " ring\n";
+                    }
+                    for (auto& ring : m_rings) {
+                        ring.reset();
+                    }
+
+                    candidate cand{*ring_min, false};
+
+                    // Locations we have visited while finding candidates, used
+                    // to detect loops.
+                    std::unordered_set<osmium::Location> loc_done;
+
+                    loc_done.insert(cand.stop_location);
+
+                    std::vector<candidate> candidates;
+                    find_candidates(candidates, loc_done, xrings, cand);
+
+                    if (candidates.empty()) {
+                        if (debug()) {
+                            std::cerr << "    Found no candidates\n";
+                        }
+                        if (!open_ring_its.empty()) {
+                            ++m_stats.open_rings;
+                            if (m_config.problem_reporter) {
+                                for (auto& it : open_ring_its) {
+                                    m_config.problem_reporter->report_ring_not_closed(it->get_node_ref_start());
+                                    m_config.problem_reporter->report_ring_not_closed(it->get_node_ref_stop());
+                                }
+                            }
+                        }
+                        return false;
+                    }
+
+                    if (debug()) {
+                        std::cerr << "    Found candidates:\n";
+                        for (const auto& cand : candidates) {
+                            std::cerr << "      sum=" << cand.sum << "\n";
+                            for (const auto& ring : cand.rings) {
+                                std::cerr << "        " << ring.first.ring() << (ring.second ? " reverse" : "") << "\n";
+                            }
+                        }
+                    }
+
+                    // Find the candidate with the smallest/largest area
+                    const auto chosen_cand = ring_min_is_outer ?
+                        std::min_element(candidates.cbegin(), candidates.cend(), [](const candidate& lhs, const candidate& rhs) {
+                            return std::abs(lhs.sum) < std::abs(rhs.sum);
+                        }) :
+                        std::max_element(candidates.cbegin(), candidates.cend(), [](const candidate& lhs, const candidate& rhs) {
+                            return std::abs(lhs.sum) < std::abs(rhs.sum);
+                        });
+
+                    if (debug()) {
+                        std::cerr << "    Decided on: sum=" << chosen_cand->sum << "\n";
+                        for (const auto& ring : chosen_cand->rings) {
+                            std::cerr << "        " << ring.first.ring() << (ring.second ? " reverse" : "") << "\n";
+                        }
+                    }
+
+                    // Join all (open) rings in the candidate to get one closed ring.
+                    assert(chosen_cand->rings.size() > 1);
+                    const auto& first_ring = chosen_cand->rings.front().first;
+                    for (auto it = chosen_cand->rings.begin() + 1; it != chosen_cand->rings.end(); ++it) {
+                        merge_two_rings(open_ring_its, first_ring, it->first);
+                    }
+
+                    if (debug()) {
+                        std::cerr << "    Merged to " << first_ring.ring() << "\n";
+                    }
+
+                    return true;
+                }
+
+                bool create_rings_complex_case() {
+                    // First create all the (partial) rings starting at the split locations
+                    auto count_remaining = m_segment_list.size();
+                    for (const osmium::Location& location : m_split_locations) {
+                        const auto locs = make_range(std::equal_range(m_locations.begin(),
+                                                                    m_locations.end(),
+                                                                    slocation{},
+                                                                    [this, &location](const slocation& lhs, const slocation& rhs) {
+                            return lhs.location(m_segment_list, location) < rhs.location(m_segment_list, location);
+                        }));
+                        for (auto& loc : locs) {
+                            if (!m_segment_list[loc.item].is_done()) {
+                                count_remaining -= add_new_ring_complex(loc);
+                                if (count_remaining == 0) {
+                                    break;
+                                }
+                            }
+                        }
+                    }
+
+                    // Now find all the rest of the rings (ie not starting at split locations)
+                    if (count_remaining > 0) {
+                        for (slocation& sl : m_locations) {
+                            const detail::NodeRefSegment& segment = m_segment_list[sl.item];
+                            if (!segment.is_done()) {
+                                count_remaining -= add_new_ring_complex(sl);
+                                if (count_remaining == 0) {
+                                    break;
+                                }
+                            }
+                        }
+                    }
+
+                    // Now all segments are in exactly one (partial) ring.
+
+                    // If there are open rings, try to join them to create closed
+                    // rings.
+                    if (there_are_open_rings()) {
+                        ++m_stats.area_really_complex_case;
+
+                        open_ring_its_type open_ring_its;
+                        for (auto it = m_rings.begin(); it != m_rings.end(); ++it) {
+                            if (!it->closed()) {
+                                open_ring_its.push_back(it);
+                            }
+                        }
+
+                        while (!open_ring_its.empty()) {
+                            if (debug()) {
+                                std::cerr << "  There are " << open_ring_its.size() << " open rings\n";
+                            }
+                            while (try_to_merge(open_ring_its));
+
+                            if (!open_ring_its.empty()) {
+                                if (debug()) {
+                                    std::cerr << "  After joining obvious cases there are still " << open_ring_its.size() << " open rings\n";
+                                }
+                                if (!join_connected_rings(open_ring_its)) {
+                                    return false;
+                                }
+                            }
+                        }
+
+                        if (debug()) {
+                            std::cerr << "  Joined all open rings\n";
+                        }
+                    }
+
+                    // Now all rings are complete.
+
+                    find_inner_outer_complex();
+
+                    return true;
+                }
+
+                /**
+                 * Checks if any ways were completely removed in the
+                 * erase_duplicate_segments step.
+                 */
+                bool ways_were_lost() {
+                    std::unordered_set<const osmium::Way*> ways_in_segments;
+
+                    for (const auto& segment : m_segment_list) {
+                        ways_in_segments.insert(segment.way());
+                    }
+
+                    return ways_in_segments.size() < m_num_members;
+                }
+
+#ifdef OSMIUM_WITH_TIMER
+                static bool print_header() {
+                    std::cout << "nodes outer_rings inner_rings sort dupl intersection locations split simple_case complex_case roles_check\n";
+                    return true;
+                }
+
+                static bool init_header() {
+                    static bool printed_print_header = print_header();
+                    return printed_print_header;
+                }
+#endif
+
+            protected:
+
+                const std::list<detail::ProtoRing>& rings() const noexcept {
+                    return m_rings;
+                }
+
+                void set_num_members(size_t size) noexcept {
+                    m_num_members = size;
+                }
+
+                osmium::area::detail::SegmentList& segment_list() noexcept {
+                    return m_segment_list;
+                }
+
+                /**
+                 * Append each outer ring together with its inner rings to the
+                 * area in the buffer.
+                 */
+                void add_rings_to_area(osmium::builder::AreaBuilder& builder) const {
+                    for (const detail::ProtoRing& ring : m_rings) {
+                        if (ring.is_outer()) {
+                            build_ring_from_proto_ring<osmium::builder::OuterRingBuilder>(builder, ring);
+                            for (const detail::ProtoRing* inner : ring.inner_rings()) {
+                                build_ring_from_proto_ring<osmium::builder::InnerRingBuilder>(builder, *inner);
+                            }
+                        }
+                    }
+                }
+
+                /**
+                 * Create rings from segments.
+                 */
+                bool create_rings() {
+                    m_stats.nodes += m_segment_list.size();
+
+                    // Sort the list of segments (from left to right and bottom
+                    // to top).
+                    osmium::Timer timer_sort;
+                    m_segment_list.sort();
+                    timer_sort.stop();
+
+                    // Remove duplicate segments. Removal is in pairs, so if there
+                    // are two identical segments, they will both be removed. If
+                    // there are three, two will be removed and one remains.
+                    osmium::Timer timer_dupl;
+                    m_stats.duplicate_segments = m_segment_list.erase_duplicate_segments(m_config.problem_reporter);
+                    timer_dupl.stop();
+
+                    // If there are no segments left at this point, this isn't
+                    // a valid area.
+                    if (m_segment_list.empty()) {
+                        if (debug()) {
+                            std::cerr << "  No segments left\n";
+                        }
+                        return false;
+                    }
+
+                    // If one or more complete ways was removed because of
+                    // duplicate segments, this isn't a valid area.
+                    if (ways_were_lost()) {
+                        if (debug()) {
+                            std::cerr << "  Complete ways removed because of duplicate segments\n";
+                        }
+                        return false;
+                    }
+
+                    if (m_config.debug_level >= 3) {
+                        std::cerr << "Sorted de-duplicated segment list:\n";
+                        for (const auto& s : m_segment_list) {
+                            std::cerr << "  " << s << "\n";
+                        }
+                    }
+
+                    // Now we look for segments crossing each other. If there are
+                    // any, the multipolygon is invalid.
+                    // In the future this could be improved by trying to fix those
+                    // cases.
+                    osmium::Timer timer_intersection;
+                    m_stats.intersections = m_segment_list.find_intersections(m_config.problem_reporter);
+                    timer_intersection.stop();
+
+                    if (m_stats.intersections) {
+                        return false;
+                    }
+
+                    // This creates an ordered list of locations of both endpoints
+                    // of all segments with pointers back to the segments. We will
+                    // use this list later to quickly find which segment(s) fits
+                    // onto a known segment.
+                    osmium::Timer timer_locations_list;
+                    create_locations_list();
+                    timer_locations_list.stop();
+
+                    // Find all locations where more than two segments start or
+                    // end. We call those "split" locations. If there are any
+                    // "spike" segments found while doing this, we know the area
+                    // geometry isn't valid and return.
+                    osmium::Timer timer_split;
+                    if (!find_split_locations()) {
+                        return false;
+                    }
+                    timer_split.stop();
+
+                    // Now report all split locations to the problem reporter.
+                    m_stats.touching_rings += m_split_locations.size();
+                    if (!m_split_locations.empty()) {
+                        if (debug()) {
+                            std::cerr << "  Found split locations:\n";
+                        }
+                        for (const auto& location : m_split_locations) {
+                            if (m_config.problem_reporter) {
+                                auto it = std::lower_bound(m_locations.cbegin(), m_locations.cend(), slocation{}, [this, &location](const slocation& lhs, const slocation& rhs) {
+                                    return lhs.location(m_segment_list, location) < rhs.location(m_segment_list, location);
+                                });
+                                assert(it != m_locations.cend());
+                                const osmium::object_id_type id = it->node_ref(m_segment_list).ref();
+                                m_config.problem_reporter->report_touching_ring(id, location);
+                            }
+                            if (debug()) {
+                                std::cerr << "    " << location << "\n";
+                            }
+                        }
+                    }
+
+                    // From here on we use two different algorithms depending on
+                    // whether there were any split locations or not. If there
+                    // are no splits, we use the faster "simple algorithm", if
+                    // there are, we use the slower "complex algorithm".
+                    osmium::Timer timer_simple_case;
+                    osmium::Timer timer_complex_case;
+                    if (m_split_locations.empty()) {
+                        if (debug()) {
+                            std::cerr << "  No split locations -> using simple algorithm\n";
+                        }
+                        ++m_stats.area_simple_case;
+
+                        timer_simple_case.start();
+                        create_rings_simple_case();
+                        timer_simple_case.stop();
+                    } else {
+                        if (debug()) {
+                            std::cerr << "  Found split locations -> using complex algorithm\n";
+                        }
+                        ++m_stats.area_touching_rings_case;
+
+                        timer_complex_case.start();
+                        if (!create_rings_complex_case()) {
+                            return false;
+                        }
+                        timer_complex_case.stop();
+                    }
+
+                    // If the assembler was so configured, now check whether the
+                    // member roles are correctly tagged.
+                    if (m_config.check_roles && m_stats.from_relations) {
+                        osmium::Timer timer_roles;
+                        check_inner_outer_roles();
+                        timer_roles.stop();
+                    }
+
+                    m_stats.outer_rings = std::count_if(m_rings.cbegin(), m_rings.cend(), [](const detail::ProtoRing& ring){
+                        return ring.is_outer();
+                    });
+                    m_stats.inner_rings = m_rings.size() - m_stats.outer_rings;
+
+#ifdef OSMIUM_WITH_TIMER
+                    std::cout << m_stats.nodes << ' ' << m_stats.outer_rings << ' ' << m_stats.inner_rings <<
+                                                ' ' << timer_sort.elapsed_microseconds() <<
+                                                ' ' << timer_dupl.elapsed_microseconds() <<
+                                                ' ' << timer_intersection.elapsed_microseconds() <<
+                                                ' ' << timer_locations_list.elapsed_microseconds() <<
+                                                ' ' << timer_split.elapsed_microseconds();
+
+                    if (m_split_locations.empty()) {
+                        std::cout << ' ' << timer_simple_case.elapsed_microseconds() <<
+                                    " 0";
+                    } else {
+                        std::cout << " 0" <<
+                                    ' ' << timer_complex_case.elapsed_microseconds();
+                    }
+
+                    std::cout <<
+# ifdef OSMIUM_AREA_CHECK_INNER_OUTER_ROLES
+                                ' ' << timer_roles.elapsed_microseconds() <<
+# else
+                                " 0" <<
+# endif
+                                '\n';
+#endif
+
+                    return true;
+                }
+
+            public:
+
+                using config_type = osmium::area::AssemblerConfig;
+
+                explicit BasicAssembler(const config_type& config) :
+                    m_config(config),
+                    m_segment_list(config.debug_level > 1) {
+#ifdef OSMIUM_WITH_TIMER
+                    init_header();
+#endif
+                }
+
+                ~BasicAssembler() noexcept = default;
+
+                const AssemblerConfig& config() const noexcept {
+                    return m_config;
+                }
+
+                bool debug() const noexcept {
+                    return m_config.debug_level > 1;
+                }
+
+                /**
+                 * Get statistics from assembler. Call this after running the
+                 * assembler to get statistics and data about errors.
+                 */
+                const osmium::area::area_stats& stats() const noexcept {
+                    return m_stats;
+                }
+
+                osmium::area::area_stats& stats() noexcept {
+                    return m_stats;
+                }
+
+            }; // class BasicAssembler
+
+        } // namespace detail
+
+    } // namespace area
+
+} // namespace osmium
+
+#endif // OSMIUM_AREA_DETAIL_BASIC_ASSEMBLER_HPP
diff --git a/include/osmium/area/detail/segment_list.hpp b/include/osmium/area/detail/segment_list.hpp
index 64b2b4e..2dc58a3 100644
--- a/include/osmium/area/detail/segment_list.hpp
+++ b/include/osmium/area/detail/segment_list.hpp
@@ -110,11 +110,18 @@ namespace osmium {
                     });
                 }
 
-                uint32_t extract_segments_from_way_impl(osmium::area::ProblemReporter* problem_reporter, const osmium::Way& way, role_type role) {
-                    uint32_t duplicate_nodes = 0;
+                uint32_t extract_segments_from_way_impl(osmium::area::ProblemReporter* problem_reporter, uint64_t& duplicate_nodes, const osmium::Way& way, role_type role) {
+                    uint32_t invalid_locations = 0;
 
                     osmium::NodeRef previous_nr;
                     for (const osmium::NodeRef& nr : way.nodes()) {
+                        if (!nr.location().valid()) {
+                            ++invalid_locations;
+                            if (problem_reporter) {
+                                problem_reporter->report_invalid_location(way.id(), nr.ref());
+                            }
+                            continue;
+                        }
                         if (previous_nr.location()) {
                             if (previous_nr.location() != nr.location()) {
                                 m_segments.emplace_back(previous_nr, nr, role, &way);
@@ -128,7 +135,7 @@ namespace osmium {
                         previous_nr = nr;
                     }
 
-                    return duplicate_nodes;
+                    return invalid_locations;
                 }
 
             public:
@@ -213,19 +220,19 @@ namespace osmium {
                  * same node or different nodes with same location) are
                  * removed after reporting the duplicate node.
                  */
-                uint32_t extract_segments_from_way(osmium::area::ProblemReporter* problem_reporter, const osmium::Way& way) {
+                uint32_t extract_segments_from_way(osmium::area::ProblemReporter* problem_reporter, uint64_t& duplicate_nodes, const osmium::Way& way) {
                     if (way.nodes().empty()) {
                         return 0;
                     }
                     m_segments.reserve(way.nodes().size() - 1);
-                    return extract_segments_from_way_impl(problem_reporter, way, role_type::outer);
+                    return extract_segments_from_way_impl(problem_reporter, duplicate_nodes, way, role_type::outer);
                 }
 
                 /**
                  * Extract all segments from all ways that make up this
                  * multipolygon relation and add them to the list.
                  */
-                uint32_t extract_segments_from_ways(osmium::area::ProblemReporter* problem_reporter, const osmium::Relation& relation, const std::vector<const osmium::Way*>& members) {
+                uint32_t extract_segments_from_ways(osmium::area::ProblemReporter* problem_reporter, uint64_t& duplicate_nodes, const osmium::Relation& relation, const std::vector<const osmium::Way*>& members) {
                     assert(relation.members().size() >= members.size());
 
                     const size_t num_segments = get_num_segments(members);
@@ -234,12 +241,13 @@ namespace osmium {
                     }
                     m_segments.reserve(num_segments);
 
-                    uint32_t duplicate_nodes = 0;
-                    for_each_member(relation, members, [this, &problem_reporter, &duplicate_nodes](const osmium::RelationMember& member, const osmium::Way& way) {
-                        duplicate_nodes += extract_segments_from_way_impl(problem_reporter, way, parse_role(member.role()));
+                    uint32_t invalid_locations = 0;
+                    for_each_member(relation, members, [&](const osmium::RelationMember& member, const osmium::Way& way) {
+                        const auto role = parse_role(member.role());
+                        invalid_locations += extract_segments_from_way_impl(problem_reporter, duplicate_nodes, way, role);
                     });
 
-                    return duplicate_nodes;
+                    return invalid_locations;
                 }
 
                 /**
diff --git a/include/osmium/area/detail/vector.hpp b/include/osmium/area/detail/vector.hpp
index 14bf0cb..e8ff0a5 100644
--- a/include/osmium/area/detail/vector.hpp
+++ b/include/osmium/area/detail/vector.hpp
@@ -118,4 +118,4 @@ namespace osmium {
 
 } // namespace osmium
 
-#endif //  OSMIUM_AREA_DETAIL_VECTOR_HPP
+#endif // OSMIUM_AREA_DETAIL_VECTOR_HPP
diff --git a/include/osmium/area/geom_assembler.hpp b/include/osmium/area/geom_assembler.hpp
new file mode 100644
index 0000000..84870ae
--- /dev/null
+++ b/include/osmium/area/geom_assembler.hpp
@@ -0,0 +1,131 @@
+#ifndef OSMIUM_AREA_GEOM_ASSEMBLER_HPP
+#define OSMIUM_AREA_GEOM_ASSEMBLER_HPP
+
+/*
+
+This file is part of Osmium (http://osmcode.org/libosmium).
+
+Copyright 2013-2017 Jochen Topf <jochen at topf.org> and others (see README).
+
+Boost Software License - Version 1.0 - August 17th, 2003
+
+Permission is hereby granted, free of charge, to any person or organization
+obtaining a copy of the software and accompanying documentation covered by
+this license (the "Software") to use, reproduce, display, distribute,
+execute, and transmit the Software, and to prepare derivative works of the
+Software, and to permit third-parties to whom the Software is furnished to
+do so, all subject to the following:
+
+The copyright notices in the Software and this entire statement, including
+the above license grant, this restriction and the following disclaimer,
+must be included in all copies of the Software, in whole or in part, and
+all derivative works of the Software, unless such copies or derivative
+works are solely in the form of machine-executable object code generated by
+a source language processor.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
+SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
+FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+*/
+
+#include <osmium/area/detail/basic_assembler.hpp>
+#include <osmium/builder/osm_object_builder.hpp>
+#include <osmium/memory/buffer.hpp>
+#include <osmium/osm/item_type.hpp>
+#include <osmium/osm/relation.hpp>
+#include <osmium/osm/types.hpp>
+#include <osmium/osm/way.hpp>
+
+namespace osmium {
+
+    namespace area {
+
+        /**
+         * Assembles area objects from closed ways or multipolygon relations
+         * and their members. Unlike the Assembler, this one doesn't take
+         * tags into account at all. And it doesn't interpret all the config
+         * settings and doesn't do all the checks and error reporting the
+         * Assembler does.
+         *
+         * This class was developed specifically for the need of osm2pgsql.
+         * Unless you know what you are doing, use the Assembler class instead
+         * of this class. Contact the Libosmium developers if you want to use
+         * this class.
+         */
+        class GeomAssembler : public detail::BasicAssembler {
+
+        public:
+
+            using config_type = osmium::area::AssemblerConfig;
+
+            explicit GeomAssembler(const config_type& config) :
+                detail::BasicAssembler(config) {
+            }
+
+            ~GeomAssembler() noexcept = default;
+
+            /**
+             * Assemble an area from the given way.
+             *
+             * The resulting area is put into the out_buffer.
+             *
+             * @returns false if there was some kind of error building the
+             *          area, true otherwise.
+             */
+            bool operator()(const osmium::Way& way, osmium::memory::Buffer& out_buffer) {
+                segment_list().extract_segments_from_way(config().problem_reporter, stats().duplicate_nodes, way);
+
+                if (!create_rings()) {
+                    return false;
+                }
+
+                {
+                    osmium::builder::AreaBuilder builder{out_buffer};
+                    builder.initialize_from_object(way);
+                    add_rings_to_area(builder);
+                }
+                out_buffer.commit();
+
+                return true;
+            }
+
+            /**
+             * Assemble an area from the given relation and its member ways
+             * which are in the ways_buffer.
+             *
+             * The resulting area is put into the out_buffer.
+             *
+             * @returns false if there was some kind of error building the
+             *          area, true otherwise.
+             */
+            bool operator()(const osmium::Relation& relation, const osmium::memory::Buffer& ways_buffer, osmium::memory::Buffer& out_buffer) {
+                for (const auto& way : ways_buffer.select<osmium::Way>()) {
+                    segment_list().extract_segments_from_way(config().problem_reporter, stats().duplicate_nodes, way);
+                }
+
+                if (!create_rings()) {
+                    return false;
+                }
+
+                {
+                    osmium::builder::AreaBuilder builder{out_buffer};
+                    builder.initialize_from_object(relation);
+                    add_rings_to_area(builder);
+                }
+                out_buffer.commit();
+
+                return true;
+            }
+
+        }; // class GeomAssembler
+
+    } // namespace area
+
+} // namespace osmium
+
+#endif // OSMIUM_AREA_GEOM_ASSEMBLER_HPP
diff --git a/include/osmium/area/problem_reporter.hpp b/include/osmium/area/problem_reporter.hpp
index 8a72c1a..373403b 100644
--- a/include/osmium/area/problem_reporter.hpp
+++ b/include/osmium/area/problem_reporter.hpp
@@ -190,6 +190,15 @@ namespace osmium {
             }
 
             /**
+             * Report an invalid location in a way.
+             *
+             * @param way_id  ID of the way the node is in.
+             * @param node_id ID of the node with the invalid location.
+             */
+            virtual void report_invalid_location(osmium::object_id_type way_id, osmium::object_id_type node_id) {
+            }
+
+            /**
              * In addition to reporting specific problems, this is used to
              * report all ways belonging to areas having problems.
              *
diff --git a/include/osmium/area/problem_reporter_exception.hpp b/include/osmium/area/problem_reporter_exception.hpp
index 152be40..cc5eb98 100644
--- a/include/osmium/area/problem_reporter_exception.hpp
+++ b/include/osmium/area/problem_reporter_exception.hpp
@@ -60,58 +60,64 @@ namespace osmium {
             ~ProblemReporterException() override = default;
 
             void report_duplicate_node(osmium::object_id_type node_id1, osmium::object_id_type node_id2, osmium::Location location) override {
-                m_sstream.str();
+                m_sstream.str("");
                 ProblemReporterStream::report_duplicate_node(node_id1, node_id2, location);
-                throw std::runtime_error(m_sstream.str());
+                throw std::runtime_error{m_sstream.str()};
             }
 
             void report_touching_ring(osmium::object_id_type node_id, osmium::Location location) override {
-                m_sstream.str();
+                m_sstream.str("");
                 ProblemReporterStream::report_touching_ring(node_id, location);
-                throw std::runtime_error(m_sstream.str());
+                throw std::runtime_error{m_sstream.str()};
             }
 
             void report_intersection(osmium::object_id_type way1_id, osmium::Location way1_seg_start, osmium::Location way1_seg_end,
                                      osmium::object_id_type way2_id, osmium::Location way2_seg_start, osmium::Location way2_seg_end, osmium::Location intersection) override {
-                m_sstream.str();
+                m_sstream.str("");
                 ProblemReporterStream::report_intersection(way1_id, way1_seg_start, way1_seg_end, way2_id, way2_seg_start, way2_seg_end, intersection);
-                throw std::runtime_error(m_sstream.str());
+                throw std::runtime_error{m_sstream.str()};
             }
 
             void report_duplicate_segment(const osmium::NodeRef& nr1, const osmium::NodeRef& nr2) override {
-                m_sstream.str();
+                m_sstream.str("");
                 ProblemReporterStream::report_duplicate_segment(nr1, nr2);
-                throw std::runtime_error(m_sstream.str());
+                throw std::runtime_error{m_sstream.str()};
             }
 
             void report_ring_not_closed(const osmium::NodeRef& nr, const osmium::Way* way = nullptr) override {
-                m_sstream.str();
+                m_sstream.str("");
                 ProblemReporterStream::report_ring_not_closed(nr, way);
-                throw std::runtime_error(m_sstream.str());
+                throw std::runtime_error{m_sstream.str()};
             }
 
             void report_role_should_be_outer(osmium::object_id_type way_id, osmium::Location seg_start, osmium::Location seg_end) override {
-                m_sstream.str();
+                m_sstream.str("");
                 ProblemReporterStream::report_role_should_be_outer(way_id, seg_start, seg_end);
-                throw std::runtime_error(m_sstream.str());
+                throw std::runtime_error{m_sstream.str()};
             }
 
             void report_role_should_be_inner(osmium::object_id_type way_id, osmium::Location seg_start, osmium::Location seg_end) override {
-                m_sstream.str();
+                m_sstream.str("");
                 ProblemReporterStream::report_role_should_be_inner(way_id, seg_start, seg_end);
-                throw std::runtime_error(m_sstream.str());
+                throw std::runtime_error{m_sstream.str()};
             }
 
             void report_way_in_multiple_rings(const osmium::Way& way) override {
-                m_sstream.str();
+                m_sstream.str("");
                 ProblemReporterStream::report_way_in_multiple_rings(way);
-                throw std::runtime_error(m_sstream.str());
+                throw std::runtime_error{m_sstream.str()};
             }
 
             void report_inner_with_same_tags(const osmium::Way& way) override {
-                m_sstream.str();
+                m_sstream.str("");
                 ProblemReporterStream::report_inner_with_same_tags(way);
-                throw std::runtime_error(m_sstream.str());
+                throw std::runtime_error{m_sstream.str()};
+            }
+
+            void report_invalid_location(osmium::object_id_type way_id, osmium::object_id_type node_id) override {
+                m_sstream.str("");
+                ProblemReporterStream::report_invalid_location(way_id, node_id);
+                throw std::runtime_error{m_sstream.str()};
             }
 
         }; // class ProblemReporterException
diff --git a/include/osmium/area/problem_reporter_ogr.hpp b/include/osmium/area/problem_reporter_ogr.hpp
index 914c8ba..2d8026a 100644
--- a/include/osmium/area/problem_reporter_ogr.hpp
+++ b/include/osmium/area/problem_reporter_ogr.hpp
@@ -73,14 +73,14 @@ namespace osmium {
             gdalcpp::Layer m_layer_ways;
 
             void set_object(gdalcpp::Feature& feature) {
-                const char t[2] = { osmium::item_type_to_char(m_object_type), '\0' };
+                const char t[2] = {osmium::item_type_to_char(m_object_type), '\0'};
                 feature.set_field("obj_type", t);
                 feature.set_field("obj_id", int32_t(m_object_id));
                 feature.set_field("nodes", int32_t(m_nodes));
             }
 
             void write_point(const char* problem_type, osmium::object_id_type id1, osmium::object_id_type id2, osmium::Location location) {
-                gdalcpp::Feature feature(m_layer_perror, m_ogr_factory.create_point(location));
+                gdalcpp::Feature feature{m_layer_perror, m_ogr_factory.create_point(location)};
                 set_object(feature);
                 feature.set_field("id1", double(id1));
                 feature.set_field("id2", double(id2));
@@ -93,7 +93,7 @@ namespace osmium {
                 ogr_linestring->addPoint(loc1.lon(), loc1.lat());
                 ogr_linestring->addPoint(loc2.lon(), loc2.lat());
 
-                gdalcpp::Feature feature(m_layer_lerror, std::move(ogr_linestring));
+                gdalcpp::Feature feature{m_layer_lerror, std::move(ogr_linestring)};
                 set_object(feature);
                 feature.set_field("id1", static_cast<double>(id1));
                 feature.set_field("id2", static_cast<double>(id2));
@@ -175,7 +175,7 @@ namespace osmium {
                     return;
                 }
                 try {
-                    gdalcpp::Feature feature(m_layer_lerror, m_ogr_factory.create_linestring(way));
+                    gdalcpp::Feature feature{m_layer_lerror, m_ogr_factory.create_linestring(way)};
                     set_object(feature);
                     feature.set_field("id1", int32_t(way.id()));
                     feature.set_field("id2", 0);
@@ -191,7 +191,7 @@ namespace osmium {
                     return;
                 }
                 try {
-                    gdalcpp::Feature feature(m_layer_lerror, m_ogr_factory.create_linestring(way));
+                    gdalcpp::Feature feature{m_layer_lerror, m_ogr_factory.create_linestring(way)};
                     set_object(feature);
                     feature.set_field("id1", int32_t(way.id()));
                     feature.set_field("id2", 0);
@@ -212,7 +212,7 @@ namespace osmium {
                     return;
                 }
                 try {
-                    gdalcpp::Feature feature(m_layer_ways, m_ogr_factory.create_linestring(way));
+                    gdalcpp::Feature feature{m_layer_ways, m_ogr_factory.create_linestring(way)};
                     set_object(feature);
                     feature.set_field("way_id", int32_t(way.id()));
                     feature.add_to_layer();
diff --git a/include/osmium/area/problem_reporter_stream.hpp b/include/osmium/area/problem_reporter_stream.hpp
index 0c008f1..910eb4e 100644
--- a/include/osmium/area/problem_reporter_stream.hpp
+++ b/include/osmium/area/problem_reporter_stream.hpp
@@ -114,6 +114,11 @@ namespace osmium {
                 *m_out << "way_id=" << way.id() << '\n';
             }
 
+            void report_invalid_location(osmium::object_id_type way_id, osmium::object_id_type node_id) override {
+                header("invalid location");
+                *m_out << "way_id=" << way_id << " node_id=" << node_id << '\n';
+            }
+
         }; // class ProblemReporterStream
 
     } // namespace area
diff --git a/include/osmium/area/stats.hpp b/include/osmium/area/stats.hpp
index 07be783..48b4088 100644
--- a/include/osmium/area/stats.hpp
+++ b/include/osmium/area/stats.hpp
@@ -68,6 +68,7 @@ namespace osmium {
             uint64_t touching_rings = 0; ///< Rings touching in a node
             uint64_t ways_in_multiple_rings = 0; ///< Different segments of a way ended up in different rings
             uint64_t wrong_role = 0; ///< Member has wrong role (not "outer", "inner", or empty)
+            uint64_t invalid_locations = 0; ///< Invalid location found
 
             area_stats& operator+=(const area_stats& other) noexcept {
                 area_really_complex_case += other.area_really_complex_case;
@@ -91,6 +92,7 @@ namespace osmium {
                 touching_rings += other.touching_rings;
                 ways_in_multiple_rings += other.ways_in_multiple_rings;
                 wrong_role += other.wrong_role;
+                invalid_locations += invalid_locations;
                 return *this;
             }
 
@@ -118,7 +120,8 @@ namespace osmium {
                        << " single_way_in_mp_relation=" << s.single_way_in_mp_relation
                        << " touching_rings=" << s.touching_rings
                        << " ways_in_multiple_rings=" << s.ways_in_multiple_rings
-                       << " wrong_role=" << s.wrong_role;
+                       << " wrong_role=" << s.wrong_role
+                       << " invalid_locations=" << s.invalid_locations;
         }
 
     } // namespace area
diff --git a/include/osmium/builder/builder.hpp b/include/osmium/builder/builder.hpp
index 107f4a9..d435884 100644
--- a/include/osmium/builder/builder.hpp
+++ b/include/osmium/builder/builder.hpp
@@ -168,6 +168,20 @@ namespace osmium {
             }
 
             /**
+             * Append data to buffer and append an additional \0.
+             *
+             * @param data Pointer to data.
+             * @param length Length of data in bytes.
+             * @returns The number of bytes appended (length + 1).
+             */
+            osmium::memory::item_size_type append_with_zero(const char* data, const osmium::memory::item_size_type length) {
+                unsigned char* target = reserve_space(length + 1);
+                std::copy_n(reinterpret_cast<const unsigned char*>(data), length, target);
+                target[length] = '\0';
+                return length + 1;
+            }
+
+            /**
              * Append \0-terminated string to buffer.
              *
              * @param str \0-terminated string.
@@ -180,9 +194,11 @@ namespace osmium {
             /**
              * Append '\0' to the buffer.
              *
+             * @deprecated Use append_with_zero() instead.
+             *
              * @returns The number of bytes appended (always 1).
              */
-            osmium::memory::item_size_type append_zero() {
+            OSMIUM_DEPRECATED osmium::memory::item_size_type append_zero() {
                 *reserve_space(1) = '\0';
                 return 1;
             }
diff --git a/include/osmium/builder/builder_helper.hpp b/include/osmium/builder/builder_helper.hpp
index 8bfa21e..a273e50 100644
--- a/include/osmium/builder/builder_helper.hpp
+++ b/include/osmium/builder/builder_helper.hpp
@@ -71,7 +71,7 @@ namespace osmium {
          * @deprecated
          * Use osmium::builder::add_tag_list() instead.
          */
-        inline const osmium::TagList& build_tag_list(osmium::memory::Buffer& buffer, const std::initializer_list<std::pair<const char*, const char*>>& tags) {
+        OSMIUM_DEPRECATED inline const osmium::TagList& build_tag_list(osmium::memory::Buffer& buffer, const std::initializer_list<std::pair<const char*, const char*>>& tags) {
             const size_t pos = buffer.committed();
             {
                 osmium::builder::TagListBuilder tl_builder(buffer);
@@ -87,7 +87,7 @@ namespace osmium {
          * @deprecated
          * Use osmium::builder::add_tag_list() instead.
          */
-        inline const osmium::TagList& build_tag_list_from_map(osmium::memory::Buffer& buffer, const std::map<const char*, const char*>& tags) {
+        OSMIUM_DEPRECATED inline const osmium::TagList& build_tag_list_from_map(osmium::memory::Buffer& buffer, const std::map<const char*, const char*>& tags) {
             const size_t pos = buffer.committed();
             {
                 osmium::builder::TagListBuilder tl_builder(buffer);
@@ -103,7 +103,7 @@ namespace osmium {
          * @deprecated
          * Use osmium::builder::add_tag_list() instead.
          */
-        inline const osmium::TagList& build_tag_list_from_func(osmium::memory::Buffer& buffer, std::function<void(osmium::builder::TagListBuilder&)> func) {
+        OSMIUM_DEPRECATED inline const osmium::TagList& build_tag_list_from_func(osmium::memory::Buffer& buffer, std::function<void(osmium::builder::TagListBuilder&)> func) {
             const size_t pos = buffer.committed();
             {
                 osmium::builder::TagListBuilder tl_builder(buffer);
diff --git a/include/osmium/builder/osm_object_builder.hpp b/include/osmium/builder/osm_object_builder.hpp
index 1dd5f97..d4483b1 100644
--- a/include/osmium/builder/osm_object_builder.hpp
+++ b/include/osmium/builder/osm_object_builder.hpp
@@ -99,7 +99,8 @@ namespace osmium {
                 if (std::strlen(value) > osmium::max_osm_string_length) {
                     throw std::length_error("OSM tag value is too long");
                 }
-                add_size(append(key) + append(value));
+                add_size(append(key));
+                add_size(append(value));
             }
 
             /**
@@ -117,8 +118,8 @@ namespace osmium {
                 if (value_length > osmium::max_osm_string_length) {
                     throw std::length_error("OSM tag value is too long");
                 }
-                add_size(append(key,   osmium::memory::item_size_type(key_length))   + append_zero() +
-                         append(value, osmium::memory::item_size_type(value_length)) + append_zero());
+                add_size(append_with_zero(key,   osmium::memory::item_size_type(key_length)));
+                add_size(append_with_zero(value, osmium::memory::item_size_type(value_length)));
             }
 
             /**
@@ -134,8 +135,8 @@ namespace osmium {
                 if (value.size() > osmium::max_osm_string_length) {
                     throw std::length_error("OSM tag value is too long");
                 }
-                add_size(append(key.data(),   osmium::memory::item_size_type(key.size())   + 1) +
-                         append(value.data(), osmium::memory::item_size_type(value.size()) + 1));
+                add_size(append(key.data(),   osmium::memory::item_size_type(key.size())   + 1));
+                add_size(append(value.data(), osmium::memory::item_size_type(value.size()) + 1));
             }
 
             /**
@@ -144,7 +145,8 @@ namespace osmium {
              * @param tag Tag.
              */
             void add_tag(const osmium::Tag& tag) {
-                add_size(append(tag.key()) + append(tag.value()));
+                add_size(append(tag.key()));
+                add_size(append(tag.value()));
             }
 
             /**
@@ -226,7 +228,7 @@ namespace osmium {
                     throw std::length_error("OSM relation member role is too long");
                 }
                 member.set_role_size(osmium::string_size_type(length) + 1);
-                add_size(append(role, osmium::memory::item_size_type(length)) + append_zero());
+                add_size(append_with_zero(role, osmium::memory::item_size_type(length)));
                 add_padding(true);
             }
 
@@ -310,7 +312,7 @@ namespace osmium {
                     throw std::length_error("OSM user name is too long");
                 }
                 comment.set_user_size(osmium::string_size_type(length) + 1);
-                add_size(append(user, osmium::memory::item_size_type(length)) + append_zero());
+                add_size(append_with_zero(user, osmium::memory::item_size_type(length)));
             }
 
             void add_text(osmium::ChangesetComment& comment, const char* text, const size_t length) {
@@ -322,7 +324,7 @@ namespace osmium {
                     throw std::length_error("OSM changeset comment is too long");
                 }
                 comment.set_text_size(osmium::string_size_type(length) + 1);
-                add_size(append(text, osmium::memory::item_size_type(length)) + append_zero());
+                add_size(append_with_zero(text, osmium::memory::item_size_type(length)));
                 add_padding(true);
             }
 
diff --git a/include/osmium/geom/factory.hpp b/include/osmium/geom/factory.hpp
index 6f8d954..39d1eac 100644
--- a/include/osmium/geom/factory.hpp
+++ b/include/osmium/geom/factory.hpp
@@ -192,7 +192,7 @@ namespace osmium {
             using multipolygon_type = typename TGeomImpl::multipolygon_type;
             using ring_type         = typename TGeomImpl::ring_type;
 
-            int epsg() const {
+            int epsg() const noexcept {
                 return m_projection.epsg();
             }
 
diff --git a/include/osmium/geom/mercator_projection.hpp b/include/osmium/geom/mercator_projection.hpp
index 814bce6..a6b798a 100644
--- a/include/osmium/geom/mercator_projection.hpp
+++ b/include/osmium/geom/mercator_projection.hpp
@@ -118,7 +118,7 @@ namespace osmium {
          * @pre @code c.valid() @endcode
          */
         inline Coordinates lonlat_to_mercator(const Coordinates& c) {
-            return Coordinates(detail::lon_to_x(c.x), detail::lat_to_y(c.y));
+            return Coordinates{detail::lon_to_x(c.x), detail::lat_to_y(c.y)};
         }
 
         /**
@@ -127,7 +127,7 @@ namespace osmium {
          * @pre @code c.valid() @endcode
          */
         inline Coordinates mercator_to_lonlat(const Coordinates& c) {
-            return Coordinates(detail::x_to_lon(c.x), detail::y_to_lat(c.y));
+            return Coordinates{detail::x_to_lon(c.x), detail::y_to_lat(c.y)};
         }
 
         /**
@@ -139,7 +139,7 @@ namespace osmium {
         public:
 
             Coordinates operator()(osmium::Location location) const {
-                return Coordinates {detail::lon_to_x(location.lon()), detail::lat_to_y(location.lat())};
+                return Coordinates{detail::lon_to_x(location.lon()), detail::lat_to_y(location.lat())};
             }
 
             int epsg() const noexcept {
diff --git a/include/osmium/geom/projection.hpp b/include/osmium/geom/projection.hpp
index 60e0ecf..132b068 100644
--- a/include/osmium/geom/projection.hpp
+++ b/include/osmium/geom/projection.hpp
@@ -48,6 +48,7 @@ DEALINGS IN THE SOFTWARE.
 #include <proj_api.h>
 
 #include <osmium/geom/coordinates.hpp>
+#include <osmium/geom/mercator_projection.hpp>
 #include <osmium/geom/util.hpp>
 #include <osmium/osm/location.hpp>
 
@@ -70,15 +71,15 @@ namespace osmium {
 
         public:
 
-            explicit CRS(const std::string& crs) :
-                m_crs(pj_init_plus(crs.c_str()), ProjCRSDeleter()) {
+            explicit CRS(const char* crs) :
+                m_crs(pj_init_plus(crs), ProjCRSDeleter()) {
                 if (!m_crs) {
-                    throw osmium::projection_error(std::string{"creation of CRS failed: "} + pj_strerrno(*pj_get_errno_ref()));
+                    throw osmium::projection_error{std::string{"creation of CRS failed: "} + pj_strerrno(*pj_get_errno_ref())};
                 }
             }
 
-            explicit CRS(const char* crs) :
-                CRS(std::string{crs}) {
+            explicit CRS(const std::string& crs) :
+                CRS(crs.c_str()) {
             }
 
             explicit CRS(int epsg) :
@@ -88,15 +89,15 @@ namespace osmium {
             /**
              * Get underlying projPJ handle from proj library.
              */
-            projPJ get() const {
+            projPJ get() const noexcept {
                 return m_crs.get();
             }
 
-            bool is_latlong() const {
+            bool is_latlong() const noexcept {
                 return pj_is_latlong(m_crs.get()) != 0;
             }
 
-            bool is_geocent() const {
+            bool is_geocent() const noexcept {
                 return pj_is_geocent(m_crs.get()) != 0;
             }
 
@@ -108,12 +109,12 @@ namespace osmium {
          *
          * Coordinates have to be in radians and are produced in radians.
          *
-         * @throws osmmium::projection_error if the projection fails
+         * @throws osmium::projection_error if the projection fails
          */
         inline Coordinates transform(const CRS& src, const CRS& dest, Coordinates c) {
-            int result = pj_transform(src.get(), dest.get(), 1, 1, &c.x, &c.y, nullptr);
+            const int result = pj_transform(src.get(), dest.get(), 1, 1, &c.x, &c.y, nullptr);
             if (result != 0) {
-                throw osmium::projection_error(std::string("projection failed: ") + pj_strerrno(result));
+                throw osmium::projection_error{std::string("projection failed: ") + pj_strerrno(result)};
             }
             return c;
         }
@@ -121,12 +122,19 @@ namespace osmium {
         /**
          * Functor that does projection from WGS84 (EPSG:4326) to the given
          * CRS.
+         *
+         * If this Projection is initialized with the constructor taking
+         * an integer with the epsg code 4326, no projection is done. If it
+         * is initialized with epsg code 3857 the Osmium-internal
+         * implementation of the Mercator projection is used, otherwise this
+         * falls back to using the proj.4 library. Note that this "magic" does
+         * not work if you use any of the constructors taking a string.
          */
         class Projection {
 
             int m_epsg;
             std::string m_proj_string;
-            CRS m_crs_wgs84 {4326};
+            CRS m_crs_wgs84{4326};
             CRS m_crs_user;
 
         public:
@@ -145,19 +153,23 @@ namespace osmium {
 
             explicit Projection(int epsg) :
                 m_epsg(epsg),
-                m_proj_string(std::string("+init=epsg:") + std::to_string(epsg)),
+                m_proj_string(std::string{"+init=epsg:"} + std::to_string(epsg)),
                 m_crs_user(epsg) {
             }
 
             Coordinates operator()(osmium::Location location) const {
-                Coordinates c {location.lon(), location.lat()};
-
-                if (m_epsg != 4326) {
-                    c = transform(m_crs_wgs84, m_crs_user, Coordinates(deg_to_rad(location.lon()), deg_to_rad(location.lat())));
-                    if (m_crs_user.is_latlong()) {
-                        c.x = rad_to_deg(c.x);
-                        c.y = rad_to_deg(c.y);
-                    }
+                if (m_epsg == 4326) {
+                    return Coordinates{location.lon(), location.lat()};
+                } else if (m_epsg == 3857) {
+                    return Coordinates{detail::lon_to_x(location.lon()),
+                                       detail::lat_to_y(location.lat())};
+                }
+
+                Coordinates c{transform(m_crs_wgs84, m_crs_user, Coordinates{deg_to_rad(location.lon()),
+                                                                             deg_to_rad(location.lat())})};
+                if (m_crs_user.is_latlong()) {
+                    c.x = rad_to_deg(c.x);
+                    c.y = rad_to_deg(c.y);
                 }
 
                 return c;
diff --git a/include/osmium/handler/node_locations_for_ways.hpp b/include/osmium/handler/node_locations_for_ways.hpp
index 12c2b5f..84f77d1 100644
--- a/include/osmium/handler/node_locations_for_ways.hpp
+++ b/include/osmium/handler/node_locations_for_ways.hpp
@@ -136,9 +136,9 @@ namespace osmium {
              */
             osmium::Location get_node_location(const osmium::object_id_type id) const {
                 if (id >= 0) {
-                    return m_storage_pos.get(static_cast<osmium::unsigned_object_id_type>( id));
+                    return m_storage_pos.get_noexcept(static_cast<osmium::unsigned_object_id_type>( id));
                 } else {
-                    return m_storage_neg.get(static_cast<osmium::unsigned_object_id_type>(-id));
+                    return m_storage_neg.get_noexcept(static_cast<osmium::unsigned_object_id_type>(-id));
                 }
             }
 
@@ -155,16 +155,12 @@ namespace osmium {
                 }
                 bool error = false;
                 for (auto& node_ref : way.nodes()) {
-                    try {
-                        node_ref.set_location(get_node_location(node_ref.ref()));
-                        if (!node_ref.location()) {
-                            error = true;
-                        }
-                    } catch (const osmium::not_found&) {
+                    node_ref.set_location(get_node_location(node_ref.ref()));
+                    if (!node_ref.location()) {
                         error = true;
                     }
                 }
-                if (error && !m_ignore_errors) {
+                if (!m_ignore_errors && error) {
                     throw osmium::not_found{"location for one or more nodes not found in node location index"};
                 }
             }
diff --git a/include/osmium/index/id_set.hpp b/include/osmium/index/id_set.hpp
index 50426b0..9f36314 100644
--- a/include/osmium/index/id_set.hpp
+++ b/include/osmium/index/id_set.hpp
@@ -408,6 +408,7 @@ namespace osmium {
 
         }; // class IdSetSmall
 
+        /// @deprecated Use nrw_array helper class instead.
         template <template<typename> class IdSetType>
         class NWRIdSet {
 
diff --git a/include/osmium/index/map/sparse_mem_table.hpp b/include/osmium/index/map/sparse_mem_table.hpp
index f6a5fa3..e241462 100644
--- a/include/osmium/index/map/sparse_mem_table.hpp
+++ b/include/osmium/index/map/sparse_mem_table.hpp
@@ -152,4 +152,4 @@ namespace osmium {
 
 #endif // OSMIUM_WITH_SPARSEHASH
 
-#endif // OSMIUM_INDEX_BYID_SPARSE_MEM_TABLE_HPP
+#endif // OSMIUM_INDEX_MAP_SPARSE_MEM_TABLE_HPP
diff --git a/include/osmium/version.hpp b/include/osmium/index/nwr_array.hpp
similarity index 72%
copy from include/osmium/version.hpp
copy to include/osmium/index/nwr_array.hpp
index d32641a..2c52c7e 100644
--- a/include/osmium/version.hpp
+++ b/include/osmium/index/nwr_array.hpp
@@ -1,5 +1,5 @@
-#ifndef OSMIUM_VERSION_HPP
-#define OSMIUM_VERSION_HPP
+#ifndef OSMIUM_INDEX_NWR_ARRAY_HPP
+#define OSMIUM_INDEX_NWR_ARRAY_HPP
 
 /*
 
@@ -33,10 +33,27 @@ DEALINGS IN THE SOFTWARE.
 
 */
 
-#define LIBOSMIUM_VERSION_MAJOR 2
-#define LIBOSMIUM_VERSION_MINOR 11
-#define LIBOSMIUM_VERSION_PATCH 0
+#include <osmium/osm/item_type.hpp>
 
-#define LIBOSMIUM_VERSION_STRING "2.11.0"
+namespace osmium {
 
-#endif // OSMIUM_VERSION_HPP
+    template <typename T>
+    class nwr_array {
+
+        T m_sets[3];
+
+    public:
+
+        T& operator()(osmium::item_type type) noexcept {
+            return m_sets[osmium::item_type_to_nwr_index(type)];
+        }
+
+        const T& operator()(osmium::item_type type) const noexcept {
+            return m_sets[osmium::item_type_to_nwr_index(type)];
+        }
+
+    }; // class nwr_array
+
+} // namespace osmium
+
+#endif // OSMIUM_INDEX_NWR_ARRAY_HPP
diff --git a/include/osmium/index/relations_map.hpp b/include/osmium/index/relations_map.hpp
index 5f46e66..bb9f5a7 100644
--- a/include/osmium/index/relations_map.hpp
+++ b/include/osmium/index/relations_map.hpp
@@ -91,6 +91,24 @@ namespace osmium {
                     m_map.emplace_back(key, value);
                 }
 
+                typename std::enable_if<std::is_same<TKey, TValue>::value>::type flip_in_place() {
+                    for (auto& p : m_map) {
+                        using std::swap;
+                        swap(p.key, p.value);
+                    }
+                }
+
+                flat_map<TValue, TValueInternal, TKey, TKeyInternal> flip_copy() {
+                    flat_map<TValue, TValueInternal, TKey, TKeyInternal> map;
+                    map.reserve(m_map.size());
+
+                    for (const auto& p : m_map) {
+                        map.set(p.value, p.key);
+                    }
+
+                    return map;
+                }
+
                 void sort_unique() {
                     std::sort(m_map.begin(), m_map.end());
                     const auto last = std::unique(m_map.begin(), m_map.end());
@@ -111,39 +129,46 @@ namespace osmium {
                     return m_map.size();
                 }
 
+                void reserve(size_t size) {
+                    m_map.reserve(size);
+                }
+
             }; // class flat_map
 
         } // namespace detail
 
         /**
-        * Index for looking up parent relation IDs given a member relation ID.
-        * You can not instantiate such an index yourself, instead you need to
-        * instantiate a RelationsMapStash, fill it and then create an index from
-        * it:
-        *
-        * @code
-        * RelationsMapStash stash;
-        * ...
-        * for_each_relation(const osmium::Relation& relation) {
-        *    stash.add_members(relation);
-        * }
-        * ...
-        * const auto index = stash.build_index();
-        * ...
-        * osmium::unsigned_object_id_type member_id = ...;
-        * index.for_each_parent(member_id, [](osmium::unsigned_object_id_type id) {
-        *   ...
-        * });
-        * ...
-        * @endcode
-        *
-        */
+         * Index for looking up parent relation IDs given a member relation ID
+         * or the other way around.
+         *
+         * You can not instantiate such an index yourself, instead you need to
+         * instantiate a RelationsMapStash, fill it and then create an index
+         * from it:
+         *
+         * @code
+         * RelationsMapStash stash;
+         * ...
+         * for_each_relation(const osmium::Relation& relation) {
+         *    stash.add_members(relation);
+         * }
+         * ...
+         * const auto index = stash.build_member_to_parent_index();
+         * ...
+         * osmium::unsigned_object_id_type member_id = ...;
+         * index.for_each(member_id, [](osmium::unsigned_object_id_type parent_id) {
+         *   ...
+         * });
+         * ...
+         * @endcode
+         *
+         */
         class RelationsMapIndex {
 
             friend class RelationsMapStash;
+            friend class RelationsMapIndexes;
 
             using map_type = detail::flat_map<osmium::unsigned_object_id_type, uint32_t,
-                                            osmium::unsigned_object_id_type, uint32_t>;
+                                              osmium::unsigned_object_id_type, uint32_t>;
 
             map_type m_map;
 
@@ -162,56 +187,122 @@ namespace osmium {
             RelationsMapIndex& operator=(RelationsMapIndex&&) = default;
 
             /**
-            * Find the given relation id in the index and call the given function
-            * with all parent relation ids.
-            *
-            * @code
-            * osmium::unsigned_object_id_type member_id = 17;
-            * index.for_each_parent(member_id, [](osmium::unsigned_object_id_type id) {
-            *   ...
-            * });
-            * @endcode
-            *
-            * Complexity: Logarithmic in the number of elements in the index.
-            *             (Lookup uses binary search.)
-            */
-            template <typename Func>
-            void for_each_parent(osmium::unsigned_object_id_type member_id, Func&& func) const {
+             * Find the given relation id in the index and call the given
+             * function with all parent relation ids.
+             *
+             * @code
+             * osmium::unsigned_object_id_type member_id = 17;
+             * index.for_each_parent(member_id, [](osmium::unsigned_object_id_type id) {
+             *   ...
+             * });
+             * @endcode
+             *
+             * @deprecated Use for_each() instead.
+             *
+             * Complexity: Logarithmic in the number of elements in the index.
+             *             (Lookup uses binary search.)
+             */
+            template <typename TFunc>
+            void for_each_parent(osmium::unsigned_object_id_type member_id, TFunc&& func) const {
                 const auto parents = m_map.get(member_id);
                 for (auto it = parents.first; it != parents.second; ++it) {
-                    std::forward<Func>(func)(it->value);
+                    std::forward<TFunc>(func)(it->value);
+                }
+            }
+
+            /**
+             * Find the given relation id in the index and call the given
+             * function with all related relation ids.
+             *
+             * @code
+             * osmium::unsigned_object_id_type id = 17;
+             * index.for_each(id, [](osmium::unsigned_object_id_type rid) {
+             *   ...
+             * });
+             * @endcode
+             *
+             * Complexity: Logarithmic in the number of elements in the index.
+             *             (Lookup uses binary search.)
+             */
+            template <typename TFunc>
+            void for_each(osmium::unsigned_object_id_type id, TFunc&& func) const {
+                const auto parents = m_map.get(id);
+                for (auto it = parents.first; it != parents.second; ++it) {
+                    std::forward<TFunc>(func)(it->value);
                 }
             }
 
             /**
-            * Is this index empty?
-            *
-            * Complexity: Constant.
-            */
+             * Is this index empty?
+             *
+             * Complexity: Constant.
+             */
             bool empty() const noexcept {
                 return m_map.empty();
             }
 
             /**
-            * How many entries are in this index?
-            *
-            * Complexity: Constant.
-            */
+             * How many entries are in this index?
+             *
+             * Complexity: Constant.
+             */
             size_t size() const noexcept {
                 return m_map.size();
             }
 
-        }; // RelationsMapIndex
+        }; // class RelationsMapIndex
+
+        class RelationsMapIndexes {
+
+            friend class RelationsMapStash;
+
+            RelationsMapIndex m_member_to_parent;
+            RelationsMapIndex m_parent_to_member;
+
+            RelationsMapIndexes(RelationsMapIndex::map_type&& map1, RelationsMapIndex::map_type&& map2) :
+                m_member_to_parent(std::move(map1)),
+                m_parent_to_member(std::move(map2)) {
+            }
+
+        public:
+
+            const RelationsMapIndex& member_to_parent() const noexcept {
+                return m_member_to_parent;
+            }
+
+            const RelationsMapIndex& parent_to_member() const noexcept {
+                return m_parent_to_member;
+            }
+
+            /**
+             * Is this index empty?
+             *
+             * Complexity: Constant.
+             */
+            bool empty() const noexcept {
+                return m_member_to_parent.empty();
+            }
+
+            /**
+             * How many entries are in this index?
+             *
+             * Complexity: Constant.
+             */
+            size_t size() const noexcept {
+                return m_member_to_parent.size();
+            }
+
+        }; // class RelationsMapIndexes
 
         /**
-        * The RelationsMapStash is used to build up the data needed to create
-        * an index of member relation ID to parent relation ID. See the
-        * RelationsMapIndex class for more.
-        */
+         * The RelationsMapStash is used to build up the data needed to create
+         * an index of member relation ID to parent relation ID or the other
+         * way around. See the RelationsMapIndex class for more.
+         */
         class RelationsMapStash {
 
             using map_type = detail::flat_map<osmium::unsigned_object_id_type, uint32_t,
-                                            osmium::unsigned_object_id_type, uint32_t>;
+                                              osmium::unsigned_object_id_type, uint32_t>;
 
             map_type m_map;
 
@@ -230,16 +321,16 @@ namespace osmium {
             RelationsMapStash& operator=(RelationsMapStash&&) = default;
 
             /**
-            * Add mapping from member to parent relation in the stash.
-            */
+             * Add mapping from member to parent relation in the stash.
+             */
             void add(osmium::unsigned_object_id_type member_id, osmium::unsigned_object_id_type relation_id) {
                 assert(m_valid && "You can't use the RelationsMap any more after calling build_index()");
                 m_map.set(member_id, relation_id);
             }
 
             /**
-            * Add mapping from all members to given parent relation in the stash.
-            */
+             * Add mapping from all members to given parent relation in the stash.
+             */
             void add_members(const osmium::Relation& relation) {
                 assert(m_valid && "You can't use the RelationsMap any more after calling build_index()");
                 for (const auto& member : relation.members()) {
@@ -250,30 +341,33 @@ namespace osmium {
             }
 
             /**
-            * Is this stash empty?
-            *
-            * Complexity: Constant.
-            */
+             * Is this stash empty?
+             *
+             * Complexity: Constant.
+             */
             bool empty() const noexcept {
                 assert(m_valid && "You can't use the RelationsMap any more after calling build_index()");
                 return m_map.empty();
             }
 
             /**
-            * How many entries are in this stash?
-            *
-            * Complexity: Constant.
-            */
+             * How many entries are in this stash?
+             *
+             * Complexity: Constant.
+             */
             size_t size() const noexcept {
                 assert(m_valid && "You can't use the RelationsMap any more after calling build_index()");
                 return m_map.size();
             }
 
             /**
-            * Build an index with the contents of this stash and return it.
-            *
-            * After you get the index you can not use the stash any more!
-            */
+             * Build an index for member to parent lookups from the contents
+             * of this stash and return it.
+             *
+             * After you get the index you can not use the stash any more!
+             *
+             * @deprecated Use build_member_to_parent_index() instead.
+             */
             RelationsMapIndex build_index() {
                 assert(m_valid && "You can't use the RelationsMap any more after calling build_index()");
                 m_map.sort_unique();
@@ -283,6 +377,54 @@ namespace osmium {
                 return RelationsMapIndex{std::move(m_map)};
             }
 
+            /**
+             * Build an index for member to parent lookups from the contents
+             * of this stash and return it.
+             *
+             * After you get the index you can not use the stash any more!
+             */
+            RelationsMapIndex build_member_to_parent_index() {
+                assert(m_valid && "You can't use the RelationsMap any more after calling build_member_to_parent_index()");
+                m_map.sort_unique();
+#ifndef NDEBUG
+                m_valid = false;
+#endif
+                return RelationsMapIndex{std::move(m_map)};
+            }
+
+            /**
+             * Build an index for parent to member lookups from the contents
+             * of this stash and return it.
+             *
+             * After you get the index you can not use the stash any more!
+             */
+            RelationsMapIndex build_parent_to_member_index() {
+                assert(m_valid && "You can't use the RelationsMap any more after calling build_parent_to_member_index()");
+                m_map.flip_in_place();
+                m_map.sort_unique();
+#ifndef NDEBUG
+                m_valid = false;
+#endif
+                return RelationsMapIndex{std::move(m_map)};
+            }
+
+            /**
+             * Build indexes for member-to-parent and parent-to-member lookups
+             * from the contents of this stash and return them.
+             *
+             * After you get the index you can not use the stash any more!
+             */
+            RelationsMapIndexes build_indexes() {
+                assert(m_valid && "You can't use the RelationsMap any more after calling build_indexes()");
+                auto reverse_map = m_map.flip_copy();
+                reverse_map.sort_unique();
+                m_map.sort_unique();
+#ifndef NDEBUG
+                m_valid = false;
+#endif
+                return RelationsMapIndexes{std::move(m_map), std::move(reverse_map)};
+            }
+
         }; // class RelationsMapStash
 
     } // namespace index
diff --git a/include/osmium/io/detail/pbf_input_format.hpp b/include/osmium/io/detail/pbf_input_format.hpp
index be5f860..74fc4f8 100644
--- a/include/osmium/io/detail/pbf_input_format.hpp
+++ b/include/osmium/io/detail/pbf_input_format.hpp
@@ -33,7 +33,6 @@ DEALINGS IN THE SOFTWARE.
 
 */
 
-#include <algorithm>
 #include <cassert>
 #include <cstddef>
 #include <cstdint>
@@ -42,6 +41,7 @@ DEALINGS IN THE SOFTWARE.
 #include <memory>
 #include <string>
 #include <type_traits>
+#include <utility>
 
 #include <protozero/pbf_message.hpp>
 #include <protozero/types.hpp>
diff --git a/include/osmium/io/detail/pbf_output_format.hpp b/include/osmium/io/detail/pbf_output_format.hpp
index d431a67..00b364f 100644
--- a/include/osmium/io/detail/pbf_output_format.hpp
+++ b/include/osmium/io/detail/pbf_output_format.hpp
@@ -33,7 +33,6 @@ DEALINGS IN THE SOFTWARE.
 
 */
 
-#include <algorithm>
 #include <cassert>
 #include <cmath>
 #include <cstdint>
diff --git a/include/osmium/io/detail/protobuf_tags.hpp b/include/osmium/io/detail/protobuf_tags.hpp
index 8bb2e56..58fff56 100644
--- a/include/osmium/io/detail/protobuf_tags.hpp
+++ b/include/osmium/io/detail/protobuf_tags.hpp
@@ -169,4 +169,4 @@ namespace osmium {
 
 } // namespace osmium
 
-#endif //  OSMIUM_IO_DETAIL_PROTOBUF_TAGS_HPP
+#endif // OSMIUM_IO_DETAIL_PROTOBUF_TAGS_HPP
diff --git a/include/osmium/io/detail/string_util.hpp b/include/osmium/io/detail/string_util.hpp
index df6c3e2..6414785 100644
--- a/include/osmium/io/detail/string_util.hpp
+++ b/include/osmium/io/detail/string_util.hpp
@@ -181,7 +181,7 @@ namespace osmium {
 
             inline void append_xml_encoded_string(std::string& out, const char* data) {
                 for (; *data != '\0'; ++data) {
-                    switch(*data) {
+                    switch (*data) {
                         case '&':  out += "&";  break;
                         case '\"': out += """; break;
                         case '\'': out += "'"; break;
diff --git a/include/osmium/io/detail/write_thread.hpp b/include/osmium/io/detail/write_thread.hpp
index 1e22155..1b07451 100644
--- a/include/osmium/io/detail/write_thread.hpp
+++ b/include/osmium/io/detail/write_thread.hpp
@@ -33,11 +33,11 @@ DEALINGS IN THE SOFTWARE.
 
 */
 
-#include <algorithm>
 #include <exception>
 #include <future>
 #include <memory>
 #include <string>
+#include <utility>
 
 #include <osmium/io/compression.hpp>
 #include <osmium/io/detail/queue_util.hpp>
diff --git a/include/osmium/io/detail/xml_input_format.hpp b/include/osmium/io/detail/xml_input_format.hpp
index 96a348b..1b849ae 100644
--- a/include/osmium/io/detail/xml_input_format.hpp
+++ b/include/osmium/io/detail/xml_input_format.hpp
@@ -444,12 +444,14 @@ namespace osmium {
 
                                 item_type type = item_type::undefined;
                                 object_id_type ref = 0;
+                                bool ref_is_set = false;
                                 const char* role = "";
-                                check_attributes(attrs, [&type, &ref, &role](const XML_Char* name, const XML_Char* value) {
+                                check_attributes(attrs, [&](const XML_Char* name, const XML_Char* value) {
                                     if (!std::strcmp(name, "type")) {
                                         type = char_to_item_type(value[0]);
                                     } else if (!std::strcmp(name, "ref")) {
                                         ref = osmium::string_to_object_id(value);
+                                        ref_is_set = true;
                                     } else if (!std::strcmp(name, "role")) {
                                         role = static_cast<const char*>(value);
                                     }
@@ -457,7 +459,7 @@ namespace osmium {
                                 if (type != item_type::node && type != item_type::way && type != item_type::relation) {
                                     throw osmium::xml_error{"Unknown type on relation member"};
                                 }
-                                if (ref == 0) {
+                                if (!ref_is_set) {
                                     throw osmium::xml_error{"Missing ref on relation member"};
                                 }
                                 m_rml_builder->add_member(type, ref, role);
diff --git a/include/osmium/io/detail/xml_output_format.hpp b/include/osmium/io/detail/xml_output_format.hpp
index 44d6831..130a3c7 100644
--- a/include/osmium/io/detail/xml_output_format.hpp
+++ b/include/osmium/io/detail/xml_output_format.hpp
@@ -33,7 +33,6 @@ DEALINGS IN THE SOFTWARE.
 
 */
 
-#include <algorithm>
 #include <iterator>
 #include <memory>
 #include <string>
diff --git a/include/osmium/io/file_compression.hpp b/include/osmium/io/file_compression.hpp
index 9b36795..407558d 100644
--- a/include/osmium/io/file_compression.hpp
+++ b/include/osmium/io/file_compression.hpp
@@ -45,20 +45,17 @@ namespace osmium {
             bzip2 = 2
         };
 
-// avoid g++ false positive
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wreturn-type"
         inline const char* as_string(file_compression compression) {
             switch (compression) {
-                case file_compression::none:
-                    return "none";
                 case file_compression::gzip:
                     return "gzip";
                 case file_compression::bzip2:
                     return "bzip2";
+                default: // file_compression::none:
+                    break;
             }
+            return "none";
         }
-#pragma GCC diagnostic pop
 
         template <typename TChar, typename TTraits>
         inline std::basic_ostream<TChar, TTraits>& operator<<(std::basic_ostream<TChar, TTraits>& out, const file_compression compression) {
diff --git a/include/osmium/io/file_format.hpp b/include/osmium/io/file_format.hpp
index 01b560b..620082c 100644
--- a/include/osmium/io/file_format.hpp
+++ b/include/osmium/io/file_format.hpp
@@ -54,13 +54,8 @@ namespace osmium {
             yes = 1
         };
 
-// avoid g++ false positive
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wreturn-type"
         inline const char* as_string(file_format format) {
             switch (format) {
-                case file_format::unknown:
-                    return "unknown";
                 case file_format::xml:
                     return "XML";
                 case file_format::pbf:
@@ -73,9 +68,11 @@ namespace osmium {
                     return "O5M";
                 case file_format::debug:
                     return "DEBUG";
+                default: // file_format::unknown
+                    break;
             }
+            return "unknown";
         }
-#pragma GCC diagnostic pop
 
         template <typename TChar, typename TTraits>
         inline std::basic_ostream<TChar, TTraits>& operator<<(std::basic_ostream<TChar, TTraits>& out, const file_format format) {
diff --git a/include/osmium/io/reader.hpp b/include/osmium/io/reader.hpp
index c39eaaa..825cb41 100644
--- a/include/osmium/io/reader.hpp
+++ b/include/osmium/io/reader.hpp
@@ -92,6 +92,8 @@ namespace osmium {
 
             osmium::io::File m_file;
 
+            detail::ParserFactory::create_parser_type m_creator;
+
             enum class status {
                 okay   = 0, // normal reading
                 error  = 1, // some error occurred while reading
@@ -128,13 +130,12 @@ namespace osmium {
             }
 
             // This function will run in a separate thread.
-            static void parser_thread(const osmium::io::File& file,
+            static void parser_thread(const detail::ParserFactory::create_parser_type& creator,
                                       detail::future_string_queue_type& input_queue,
                                       detail::future_buffer_queue_type& osmdata_queue,
                                       std::promise<osmium::io::Header>&& header_promise,
                                       osmium::io::detail::reader_options options) {
                 std::promise<osmium::io::Header> promise = std::move(header_promise);
-                const auto creator = detail::ParserFactory::instance().get_creator_function(file);
                 const auto parser = creator(input_queue, osmdata_queue, promise, options);
                 parser->parse();
             }
@@ -236,6 +237,7 @@ namespace osmium {
             template <typename... TArgs>
             explicit Reader(const osmium::io::File& file, TArgs&&... args) :
                 m_file(file.check()),
+                m_creator(detail::ParserFactory::instance().get_creator_function(m_file)),
                 m_status(status::okay),
                 m_childpid(0),
                 m_input_queue(detail::get_input_queue_size(), "raw_input"),
@@ -256,7 +258,7 @@ namespace osmium {
 
                 std::promise<osmium::io::Header> header_promise;
                 m_header_future = header_promise.get_future();
-                m_thread = osmium::thread::thread_handler{parser_thread, std::ref(m_file), std::ref(m_input_queue), std::ref(m_osmdata_queue), std::move(header_promise), m_options};
+                m_thread = osmium::thread::thread_handler{parser_thread, std::ref(m_creator), std::ref(m_input_queue), std::ref(m_osmdata_queue), std::move(header_promise), m_options};
             }
 
             template <typename... TArgs>
diff --git a/include/osmium/object_pointer_collection.hpp b/include/osmium/object_pointer_collection.hpp
index 5accf42..7f79ebf 100644
--- a/include/osmium/object_pointer_collection.hpp
+++ b/include/osmium/object_pointer_collection.hpp
@@ -84,19 +84,37 @@ namespace osmium {
         }
 
         /**
-         * Sort objects according to the given order functor.
+         * Sort objects according to the specified order functor.
          */
         template <typename TCompare>
         void sort(TCompare&& compare) {
             std::sort(m_objects.begin(), m_objects.end(), std::forward<TCompare>(compare));
         }
 
-        /// Is the collection empty?
+        /**
+         * Make objects unique according to the specified equality functor.
+         *
+         * Complexity: Linear in the number of items.
+         */
+        template <typename TEqual>
+        void unique(TEqual&& equal) {
+            std::unique(m_objects.begin(), m_objects.end(), std::forward<TEqual>(equal));
+        }
+
+        /**
+         * Is the collection empty?
+         *
+         * Complexity: Constant.
+         */
         bool empty() const noexcept {
             return m_objects.empty();
         }
 
-        /// Return size of the collection.
+        /**
+         * Return size of the collection.
+         *
+         * Complexity: Constant.
+         */
         size_t size() const noexcept {
             return m_objects.size();
         }
diff --git a/include/osmium/osm/crc.hpp b/include/osmium/osm/crc.hpp
index 5de52ed..c191db9 100644
--- a/include/osmium/osm/crc.hpp
+++ b/include/osmium/osm/crc.hpp
@@ -246,4 +246,4 @@ namespace osmium {
 
 } // namespace osmium
 
-#endif // OSMIUM_OSM_CRC
+#endif // OSMIUM_OSM_CRC_HPP
diff --git a/include/osmium/osm/item_type.hpp b/include/osmium/osm/item_type.hpp
index 2b6dec2..74d4482 100644
--- a/include/osmium/osm/item_type.hpp
+++ b/include/osmium/osm/item_type.hpp
@@ -87,8 +87,6 @@ namespace osmium {
 
     inline item_type char_to_item_type(const char c) noexcept {
         switch (c) {
-            case 'X':
-                return item_type::undefined;
             case 'n':
                 return item_type::node;
             case 'w':
@@ -113,18 +111,14 @@ namespace osmium {
                 return item_type::inner_ring;
             case 'D':
                 return item_type::changeset_discussion;
-            default:
-                return item_type::undefined;
+            default: // 'X'
+                break;
         }
+        return item_type::undefined;
     }
 
-// avoid g++ false positive
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wreturn-type"
     inline char item_type_to_char(const item_type type) noexcept {
         switch (type) {
-            case item_type::undefined:
-                return 'X';
             case item_type::node:
                 return 'n';
             case item_type::way:
@@ -149,13 +143,14 @@ namespace osmium {
                 return 'I';
             case item_type::changeset_discussion:
                 return 'D';
+            default: // item_type::undefined
+                break;
         }
+        return 'X';
     }
 
     inline const char* item_type_to_name(const item_type type) noexcept {
         switch (type) {
-            case item_type::undefined:
-                return "undefined";
             case item_type::node:
                 return "node";
             case item_type::way:
@@ -180,9 +175,11 @@ namespace osmium {
                 return "inner_ring";
             case item_type::changeset_discussion:
                 return "changeset_discussion";
+            default: // item_type::undefined
+                break;
         }
+        return "undefined";
     }
-#pragma GCC diagnostic pop
 
     template <typename TChar, typename TTraits>
     inline std::basic_ostream<TChar, TTraits>& operator<<(std::basic_ostream<TChar, TTraits>& out, const item_type item_type) {
diff --git a/include/osmium/relations/collector.hpp b/include/osmium/relations/collector.hpp
index bede764..ee17d47 100644
--- a/include/osmium/relations/collector.hpp
+++ b/include/osmium/relations/collector.hpp
@@ -293,17 +293,6 @@ namespace osmium {
             void flush() {
             }
 
-            /**
-             * This removes all relations that have already been assembled
-             * from the m_relations vector.
-             */
-            void clean_assembled_relations() {
-                m_relations.erase(
-                    std::remove_if(m_relations.begin(), m_relations.end(), has_all_members()),
-                    m_relations.end()
-                );
-            }
-
             const osmium::Relation& get_relation(size_t offset) const {
                 assert(m_relations_buffer.committed() > offset);
                 return m_relations_buffer.get<osmium::Relation>(offset);
diff --git a/include/osmium/tags/filter.hpp b/include/osmium/tags/filter.hpp
index 22abb14..89c6f11 100644
--- a/include/osmium/tags/filter.hpp
+++ b/include/osmium/tags/filter.hpp
@@ -34,6 +34,7 @@ DEALINGS IN THE SOFTWARE.
 */
 
 #include <cstddef>
+#include <cstring>
 #include <string>
 #include <type_traits>
 #include <vector>
@@ -49,31 +50,46 @@ namespace osmium {
 
         template <typename TKey>
         struct match_key {
-            bool operator()(const TKey& rule_key, const char* tag_key) {
+            bool operator()(const TKey& rule_key, const char* tag_key) const {
                 return rule_key == tag_key;
             }
         }; // struct match_key
 
+        template <>
+        struct match_key<std::string> {
+            bool operator()(const std::string& rule_key, const char* tag_key) const {
+                return !std::strcmp(rule_key.c_str(), tag_key);
+            }
+        }; // struct match_key
+
         struct match_key_prefix {
-            bool operator()(const std::string& rule_key, const char* tag_key) {
+            bool operator()(const std::string& rule_key, const char* tag_key) const {
                 return rule_key.compare(0, std::string::npos, tag_key, 0, rule_key.size()) == 0;
             }
         }; // struct match_key_prefix
 
         template <typename TValue>
         struct match_value {
-            bool operator()(const TValue& rule_value, const char* tag_value) {
+            bool operator()(const TValue& rule_value, const char* tag_value) const {
                 return rule_value == tag_value;
             }
         }; // struct match_value
 
         template <>
+        struct match_value<std::string> {
+            bool operator()(const std::string& rule_value, const char* tag_value) const {
+                return !std::strcmp(rule_value.c_str(), tag_value);
+            }
+        }; // struct match_value
+
+        template <>
         struct match_value<void> {
-            bool operator()(const bool, const char*) {
+            bool operator()(const bool, const char*) const noexcept {
                 return true;
             }
         }; // struct match_value<void>
 
+        /// @deprecated Use osmium::TagsFilter instead.
         template <typename TKey, typename TValue=void, typename TKeyComp=match_key<TKey>, typename TValueComp=match_value<TValue>>
         class Filter {
 
@@ -138,22 +154,31 @@ namespace osmium {
 
             /**
              * Return the number of rules in this filter.
+             *
+             * Complexity: Constant.
              */
-            size_t count() const {
-                return m_rules.count();
+            size_t count() const noexcept {
+                return m_rules.size();
             }
 
             /**
              * Is this filter empty, ie are there no rules defined?
+             *
+             * Complexity: Constant.
              */
-            bool empty() const {
+            bool empty() const noexcept {
                 return m_rules.empty();
             }
 
         }; // class Filter
 
+        /// @deprecated Use osmium::TagsFilter instead.
         using KeyValueFilter  = Filter<std::string, std::string>;
+
+        /// @deprecated Use osmium::TagsFilter instead.
         using KeyFilter       = Filter<std::string>;
+
+        /// @deprecated Use osmium::TagsFilter instead.
         using KeyPrefixFilter = Filter<std::string, void, match_key_prefix>;
 
     } // namespace tags
diff --git a/include/osmium/tags/matcher.hpp b/include/osmium/tags/matcher.hpp
new file mode 100644
index 0000000..d424a5d
--- /dev/null
+++ b/include/osmium/tags/matcher.hpp
@@ -0,0 +1,123 @@
+#ifndef OSMIUM_TAGS_MATCHER_HPP
+#define OSMIUM_TAGS_MATCHER_HPP
+
+/*
+
+This file is part of Osmium (http://osmcode.org/libosmium).
+
+Copyright 2013-2017 Jochen Topf <jochen at topf.org> and others (see README).
+
+Boost Software License - Version 1.0 - August 17th, 2003
+
+Permission is hereby granted, free of charge, to any person or organization
+obtaining a copy of the software and accompanying documentation covered by
+this license (the "Software") to use, reproduce, display, distribute,
+execute, and transmit the Software, and to prepare derivative works of the
+Software, and to permit third-parties to whom the Software is furnished to
+do so, all subject to the following:
+
+The copyright notices in the Software and this entire statement, including
+the above license grant, this restriction and the following disclaimer,
+must be included in all copies of the Software, in whole or in part, and
+all derivative works of the Software, unless such copies or derivative
+works are solely in the form of machine-executable object code generated by
+a source language processor.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
+SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
+FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+*/
+
+#include <type_traits>
+#include <utility>
+
+#include <osmium/osm/tag.hpp>
+#include <osmium/util/string_matcher.hpp>
+
+namespace osmium {
+
+    /**
+     * Compares a tags key (and value) against the specified StringMatchers.
+     */
+    class TagMatcher {
+
+        osmium::StringMatcher m_key_matcher;
+        osmium::StringMatcher m_value_matcher;
+        bool m_result;
+
+    public:
+
+        /**
+         * Create a default TagMatcher that matches no tags.
+         */
+        TagMatcher() :
+            m_key_matcher(osmium::StringMatcher::always_false{}),
+            m_value_matcher(osmium::StringMatcher::always_false{}),
+            m_result(true) {
+        }
+
+        /**
+         * Create a TagMatcher matching the key against the specified
+         * StringMatcher.
+         *
+         * @param key_matcher StringMatcher for matching the key.
+         */
+        template <typename TKey, typename std::enable_if<
+            std::is_convertible<TKey, osmium::StringMatcher>::value, int>::type = 0>
+        TagMatcher(TKey&& key_matcher) :
+            m_key_matcher(std::forward<TKey>(key_matcher)),
+            m_value_matcher(osmium::StringMatcher::always_true{}),
+            m_result(true) {
+        }
+
+        /**
+         * Create a TagMatcher matching the key and value against the specified
+         * StringMatchers.
+         *
+         * @param key_matcher StringMatcher for matching the key.
+         * @param value_matcher StringMatcher for matching the value.
+         * @param invert If set to true, invert the result of the value_matcher.
+         */
+        template <typename TKey, typename TValue,
+            typename std::enable_if<std::is_convertible<TKey, osmium::StringMatcher>::value, int>::type = 0,
+            typename std::enable_if<std::is_convertible<TValue, osmium::StringMatcher>::value, int>::type = 0>
+        TagMatcher(TKey&& key_matcher, TValue&& value_matcher, bool invert = false) :
+            m_key_matcher(std::forward<TKey>(key_matcher)),
+            m_value_matcher(std::forward<TValue>(value_matcher)),
+            m_result(!invert) {
+        }
+
+        /**
+         * Match against the specified tag.
+         *
+         * @returns true if the tag matches.
+         */
+        bool operator()(const osmium::Tag& tag) const noexcept {
+            return m_key_matcher(tag.key()) &&
+                   (m_value_matcher(tag.value()) == m_result);
+        }
+
+        /**
+         * Match against the specified tags.
+         *
+         * @returns true if any of the tags in the TagList matches.
+         */
+        bool operator()(const osmium::TagList& tags) const noexcept {
+            for (const auto& tag : tags) {
+                if (operator()(tag)) {
+                    return true;
+                }
+            }
+            return false;
+        }
+
+    }; // class TagMatcher
+
+} // namespace osmium
+
+#endif // OSMIUM_TAGS_MATCHER_HPP
diff --git a/include/osmium/tags/regex_filter.hpp b/include/osmium/tags/regex_filter.hpp
index 72c3217..98ed94d 100644
--- a/include/osmium/tags/regex_filter.hpp
+++ b/include/osmium/tags/regex_filter.hpp
@@ -44,18 +44,19 @@ namespace osmium {
 
         template <>
         struct match_key<std::regex> {
-            bool operator()(const std::regex& rule_key, const char* tag_key) {
+            bool operator()(const std::regex& rule_key, const char* tag_key) const {
                 return std::regex_match(tag_key, rule_key);
             }
         }; // struct match_key<std::regex>
 
         template <>
         struct match_value<std::regex> {
-            bool operator()(const std::regex& rule_value, const char* tag_value) {
+            bool operator()(const std::regex& rule_value, const char* tag_value) const {
                 return std::regex_match(tag_value, rule_value);
             }
         }; // struct match_value<std::regex>
 
+        /// @deprecated Use osmium::TagsFilter instead.
         using RegexFilter = Filter<std::string, std::regex>;
 
     } // namespace tags
diff --git a/include/osmium/tags/taglist.hpp b/include/osmium/tags/taglist.hpp
index 30db9e9..3f640d6 100644
--- a/include/osmium/tags/taglist.hpp
+++ b/include/osmium/tags/taglist.hpp
@@ -34,6 +34,7 @@ DEALINGS IN THE SOFTWARE.
 */
 
 #include <algorithm>
+#include <functional>
 #include <utility> // IWYU pragma: keep
 
 #include <osmium/osm/tag.hpp>
@@ -46,18 +47,18 @@ namespace osmium {
     namespace tags {
 
         template <typename TFilter>
-        inline bool match_any_of(const osmium::TagList& tag_list, TFilter&& filter) {
-            return std::any_of(tag_list.cbegin(), tag_list.cend(), std::forward<TFilter>(filter));
+        inline bool match_any_of(const osmium::TagList& tag_list, const TFilter& filter) {
+            return std::any_of(tag_list.cbegin(), tag_list.cend(), std::cref(filter));
         }
 
         template <typename TFilter>
-        inline bool match_all_of(const osmium::TagList& tag_list, TFilter&& filter) {
-            return std::all_of(tag_list.cbegin(), tag_list.cend(), std::forward<TFilter>(filter));
+        inline bool match_all_of(const osmium::TagList& tag_list, const TFilter& filter) {
+            return std::all_of(tag_list.cbegin(), tag_list.cend(), std::cref(filter));
         }
 
         template <typename TFilter>
-        inline bool match_none_of(const osmium::TagList& tag_list, TFilter&& filter) {
-            return std::none_of(tag_list.cbegin(), tag_list.cend(), std::forward<TFilter>(filter));
+        inline bool match_none_of(const osmium::TagList& tag_list, const TFilter& filter) {
+            return std::none_of(tag_list.cbegin(), tag_list.cend(), std::cref(filter));
         }
 
     } // namespace tags
diff --git a/include/osmium/tags/tags_filter.hpp b/include/osmium/tags/tags_filter.hpp
new file mode 100644
index 0000000..f91c589
--- /dev/null
+++ b/include/osmium/tags/tags_filter.hpp
@@ -0,0 +1,146 @@
+#ifndef OSMIUM_TAGS_TAGS_FILTER_HPP
+#define OSMIUM_TAGS_TAGS_FILTER_HPP
+
+/*
+
+This file is part of Osmium (http://osmcode.org/libosmium).
+
+Copyright 2013-2017 Jochen Topf <jochen at topf.org> and others (see README).
+
+Boost Software License - Version 1.0 - August 17th, 2003
+
+Permission is hereby granted, free of charge, to any person or organization
+obtaining a copy of the software and accompanying documentation covered by
+this license (the "Software") to use, reproduce, display, distribute,
+execute, and transmit the Software, and to prepare derivative works of the
+Software, and to permit third-parties to whom the Software is furnished to
+do so, all subject to the following:
+
+The copyright notices in the Software and this entire statement, including
+the above license grant, this restriction and the following disclaimer,
+must be included in all copies of the Software, in whole or in part, and
+all derivative works of the Software, unless such copies or derivative
+works are solely in the form of machine-executable object code generated by
+a source language processor.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
+SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
+FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+*/
+
+#include <utility>
+#include <vector>
+
+#include <osmium/osm/tag.hpp>
+#include <osmium/tags/matcher.hpp>
+
+#include <boost/iterator/filter_iterator.hpp>
+
+namespace osmium {
+
+    /**
+     * A TagsFilter is a list of rules (defined using TagMatchers) to check
+     * tags against. The first rule that matches sets the result.
+     *
+     * Here is an example matching any "highway" tag except "highway=motorway":
+     * @code
+     * osmium::TagsFilter filter{false};
+     * filter.add_rule(false, osmium::TagMatcher{"highway", "motorway"});
+     * filter.add_rule(true, osmium::TagMatcher{"highway"});
+     *
+     * osmium::Tag& tag = ...;
+     * bool result = filter(tag);
+     * @endcode
+     *
+     * Use this instead of the old osmium::tags::Filter.
+     */
+    class TagsFilter {
+
+        std::vector<std::pair<bool, TagMatcher>> m_rules;
+        bool m_default_result;
+
+    public:
+
+        using iterator = boost::filter_iterator<TagsFilter, osmium::TagList::const_iterator>;
+
+        /**
+         * Constructor.
+         *
+         * @param default_result The result the matching function will return
+         *                       if none of the rules matched.
+         */
+        explicit TagsFilter(bool default_result = false) :
+            m_default_result(default_result) {
+        }
+
+        /**
+         * Add a rule to the filter.
+         *
+         * @param result The result returned when this rule matches.
+         * @param matcher The TagMatcher for checking tags.
+         * @returns A reference to this filter for chaining.
+         */
+        TagsFilter& add_rule(bool result, const TagMatcher& matcher) {
+            m_rules.emplace_back(result, matcher);
+            return *this;
+        }
+
+        /**
+         * Add a rule to the filter.
+         *
+         * @param result The result returned when this rule matches.
+         * @param args Arguments to construct a TagMatcher from that is used
+         *             for checking tags.
+         * @returns A reference to this filter for chaining.
+         */
+        template <typename... TArgs>
+        TagsFilter& add_rule(bool result, TArgs&&... args) {
+            m_rules.emplace_back(result, osmium::TagMatcher{std::forward<TArgs>(args)...});
+            return *this;
+        }
+
+        /**
+         * Matching function. Check the specified tag against the rules.
+         *
+         * @param tag A tag.
+         * @returns The result of the matching rule, or, if none of the rules
+         *          matched, the default result.
+         */
+        bool operator()(const osmium::Tag& tag) const noexcept {
+            for (const auto& rule : m_rules) {
+                if (rule.second(tag)) {
+                    return rule.first;
+                }
+            }
+            return m_default_result;
+        }
+
+        /**
+         * Return the number of rules in this filter.
+         *
+         * Complexity: Constant.
+         */
+        size_t count() const noexcept {
+            return m_rules.size();
+        }
+
+        /**
+         * Is this filter empty, ie are there no rules defined?
+         *
+         * Complexity: Constant.
+         */
+        bool empty() const noexcept {
+            return m_rules.empty();
+        }
+
+    }; // class TagsFilter
+
+} // namespace osmium
+
+
+#endif // OSMIUM_TAGS_TAGS_FILTER_HPP
diff --git a/include/osmium/thread/function_wrapper.hpp b/include/osmium/thread/function_wrapper.hpp
index 2ada084..eeb9425 100644
--- a/include/osmium/thread/function_wrapper.hpp
+++ b/include/osmium/thread/function_wrapper.hpp
@@ -33,8 +33,8 @@ DEALINGS IN THE SOFTWARE.
 
 */
 
-#include <algorithm>
 #include <memory>
+#include <utility>
 
 namespace osmium {
 
diff --git a/include/osmium/thread/pool.hpp b/include/osmium/thread/pool.hpp
index 06d96f5..a89b3e9 100644
--- a/include/osmium/thread/pool.hpp
+++ b/include/osmium/thread/pool.hpp
@@ -33,11 +33,11 @@ DEALINGS IN THE SOFTWARE.
 
 */
 
-#include <algorithm>
 #include <cstddef>
 #include <future>
 #include <thread>
 #include <type_traits>
+#include <utility>
 #include <vector>
 
 #include <osmium/thread/function_wrapper.hpp>
diff --git a/include/osmium/thread/util.hpp b/include/osmium/thread/util.hpp
index 4eb59c9..53d16a1 100644
--- a/include/osmium/thread/util.hpp
+++ b/include/osmium/thread/util.hpp
@@ -115,4 +115,4 @@ namespace osmium {
 
 } // namespace osmium
 
-#endif //  OSMIUM_THREAD_UTIL_HPP
+#endif // OSMIUM_THREAD_UTIL_HPP
diff --git a/include/osmium/util/file.hpp b/include/osmium/util/file.hpp
index a26d88f..b103057 100644
--- a/include/osmium/util/file.hpp
+++ b/include/osmium/util/file.hpp
@@ -42,6 +42,7 @@ DEALINGS IN THE SOFTWARE.
 #include <sys/types.h>
 
 #ifdef _WIN32
+# define WIN32_LEAN_AND_MEAN // Prevent winsock.h inclusion; avoid winsock2.h conflict
 # include <io.h>
 # include <windows.h>
 #endif
@@ -70,14 +71,14 @@ namespace osmium {
             // https://msdn.microsoft.com/en-us/library/dfbc2kec.aspx
             const auto size = ::_filelengthi64(fd);
             if (size == -1L) {
-                throw std::system_error(errno, std::system_category(), "_filelengthi64 failed");
+                throw std::system_error{errno, std::system_category(), "Could not get file size"};
             }
             return size_t(size);
 #else
             // Unix implementation
             struct stat s;
             if (::fstat(fd, &s) != 0) {
-                throw std::system_error(errno, std::system_category(), "fstat failed");
+                throw std::system_error{errno, std::system_category(), "Could not get file size"};
             }
             return size_t(s.st_size);
 #endif
@@ -97,13 +98,13 @@ namespace osmium {
             // https://msdn.microsoft.com/en-us/library/14h5k7ff.aspx
             struct _stat64 s;
             if (::_stati64(name, &s) != 0) {
-                throw std::system_error(errno, std::system_category(), "_stati64 failed");
+                throw std::system_error{errno, std::system_category(), std::string{"Could not get file size of file '"} + name + "'"};
             }
 #else
             // Unix implementation
             struct stat s;
             if (::stat(name, &s) != 0) {
-                throw std::system_error(errno, std::system_category(), "stat failed");
+                throw std::system_error{errno, std::system_category(), std::string{"Could not get file size of file '"} + name + "'"};
             }
 #endif
             return size_t(s.st_size);
@@ -136,7 +137,7 @@ namespace osmium {
 #else
             if (::ftruncate(fd, static_cast_with_assert<off_t>(new_size)) != 0) {
 #endif
-                throw std::system_error(errno, std::system_category(), "resizing file failed");
+                throw std::system_error{errno, std::system_category(), "Could not resize file"};
             }
         }
 
diff --git a/include/osmium/util/memory_mapping.hpp b/include/osmium/util/memory_mapping.hpp
index 9996c8a..7504c3f 100644
--- a/include/osmium/util/memory_mapping.hpp
+++ b/include/osmium/util/memory_mapping.hpp
@@ -644,9 +644,10 @@ inline DWORD osmium::util::MemoryMapping::get_protection() const noexcept {
             return PAGE_READONLY;
         case mapping_mode::write_private:
             return PAGE_WRITECOPY;
-        case mapping_mode::write_shared:
-            return PAGE_READWRITE;
+        default: // mapping_mode::write_shared
+            break;
     }
+    return PAGE_READWRITE;
 }
 
 inline DWORD osmium::util::MemoryMapping::get_flags() const noexcept {
@@ -655,9 +656,10 @@ inline DWORD osmium::util::MemoryMapping::get_flags() const noexcept {
             return FILE_MAP_READ;
         case mapping_mode::write_private:
             return FILE_MAP_COPY;
-        case mapping_mode::write_shared:
-            return FILE_MAP_WRITE;
+        default: // mapping_mode::write_shared
+            break;
     }
+    return FILE_MAP_WRITE;
 }
 
 inline HANDLE osmium::util::MemoryMapping::get_handle() const noexcept {
diff --git a/include/osmium/util/string_matcher.hpp b/include/osmium/util/string_matcher.hpp
new file mode 100644
index 0000000..9c79ecb
--- /dev/null
+++ b/include/osmium/util/string_matcher.hpp
@@ -0,0 +1,429 @@
+#ifndef OSMIUM_UTIL_STRING_MATCHER_HPP
+#define OSMIUM_UTIL_STRING_MATCHER_HPP
+
+/*
+
+This file is part of Osmium (http://osmcode.org/libosmium).
+
+Copyright 2013-2017 Jochen Topf <jochen at topf.org> and others (see README).
+
+Boost Software License - Version 1.0 - August 17th, 2003
+
+Permission is hereby granted, free of charge, to any person or organization
+obtaining a copy of the software and accompanying documentation covered by
+this license (the "Software") to use, reproduce, display, distribute,
+execute, and transmit the Software, and to prepare derivative works of the
+Software, and to permit third-parties to whom the Software is furnished to
+do so, all subject to the following:
+
+The copyright notices in the Software and this entire statement, including
+the above license grant, this restriction and the following disclaimer,
+must be included in all copies of the Software, in whole or in part, and
+all derivative works of the Software, unless such copies or derivative
+works are solely in the form of machine-executable object code generated by
+a source language processor.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
+SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
+FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+*/
+
+#include <cstring>
+#include <iosfwd>
+#include <string>
+#include <vector>
+
+#include <regex>
+
+// std::regex isn't implemented properly in glibc++ (before the version
+// delivered with GCC 4.9) and libc++ before the version 3.6, so the use is
+// disabled by these checks. Checks for GLIBC were based on
+// http://stackoverflow.com/questions/12530406/is-gcc-4-8-or-earlier-buggy-about-regular-expressions
+// Checks for libc++ are simply based on compiler defines. This is probably
+// not optimal but seems to work for now.
+#if defined(__GLIBCXX__)
+# if ((__cplusplus >= 201402L) || \
+        defined(_GLIBCXX_REGEX_DFS_QUANTIFIERS_LIMIT) || \
+        defined(_GLIBCXX_REGEX_STATE_LIMIT))
+#  define OSMIUM_WITH_REGEX
+# else
+#  pragma message("Disabling regex functionality. See source code for info.")
+# endif
+#elif defined(__clang__)
+# if ((__clang_major__ > 3) || \
+      (__clang_minor__ == 3 && __clang_minor__ > 5))
+#  define OSMIUM_WITH_REGEX
+# else
+#  pragma message("Disabling regex functionality")
+# endif
+#endif
+
+#include <boost/variant.hpp>
+
+namespace osmium {
+
+    /**
+     * Implements various string matching functions.
+     */
+    class StringMatcher {
+
+    public:
+
+        // Parent class for all matcher classes. Used for enable_if check.
+        class matcher {
+        };
+
+        /**
+         * Never matches.
+         */
+        class always_false : public matcher {
+
+        public:
+
+            bool match(const char* /*test_string*/) const noexcept {
+                return false;
+            }
+
+            template <typename TChar, typename TTraits>
+            void print(std::basic_ostream<TChar, TTraits>& out) const {
+                out << "always_false";
+            }
+
+        }; // class always_false
+
+        /**
+         * Always matches.
+         */
+        class always_true : public matcher {
+
+        public:
+
+            bool match(const char* /*test_string*/) const noexcept {
+                return true;
+            }
+
+            template <typename TChar, typename TTraits>
+            void print(std::basic_ostream<TChar, TTraits>& out) const {
+                out << "always_true";
+            }
+
+        }; // class always_true
+
+        /**
+         * Matches if the test string is equal to the stored string.
+         */
+        class equal : public matcher {
+
+            std::string m_str;
+
+        public:
+
+            explicit equal(const std::string& str) :
+                m_str(str) {
+            }
+
+            explicit equal(const char* str) :
+                m_str(str) {
+            }
+
+            bool match(const char* test_string) const noexcept {
+                return !std::strcmp(m_str.c_str(), test_string);
+            }
+
+            template <typename TChar, typename TTraits>
+            void print(std::basic_ostream<TChar, TTraits>& out) const {
+                out << "equal[" << m_str << ']';
+            }
+
+        }; // class equal
+
+        /**
+         * Matches if the test string starts with the stored string.
+         */
+        class prefix : public matcher {
+
+            std::string m_str;
+
+        public:
+
+            explicit prefix(const std::string& str) :
+                m_str(str) {
+            }
+
+            explicit prefix(const char* str) :
+                m_str(str) {
+            }
+
+            bool match(const char* test_string) const noexcept {
+                return m_str.compare(0, std::string::npos, test_string, 0, m_str.size()) == 0;
+            }
+
+            template <typename TChar, typename TTraits>
+            void print(std::basic_ostream<TChar, TTraits>& out) const {
+                out << "prefix[" << m_str << ']';
+            }
+
+        }; // class prefix
+
+        /**
+         * Matches if the test string is a substring of the stored string.
+         */
+        class substring : public matcher {
+
+            std::string m_str;
+
+        public:
+
+            explicit substring(const std::string& str) :
+                m_str(str) {
+            }
+
+            explicit substring(const char* str) :
+                m_str(str) {
+            }
+
+            bool match(const char* test_string) const noexcept {
+                return std::strstr(test_string, m_str.c_str());
+            }
+
+            template <typename TChar, typename TTraits>
+            void print(std::basic_ostream<TChar, TTraits>& out) const {
+                out << "substring[" << m_str << ']';
+            }
+
+        }; // class substring
+
+#ifdef OSMIUM_WITH_REGEX
+        /**
+         * Matches if the test string matches the regular expression.
+         */
+        class regex : public matcher {
+
+            std::regex m_regex;
+
+        public:
+
+            explicit regex(const std::regex& regex) :
+                m_regex(regex) {
+            }
+
+            bool match(const char* test_string) const noexcept {
+                return std::regex_search(test_string, m_regex);
+            }
+
+            template <typename TChar, typename TTraits>
+            void print(std::basic_ostream<TChar, TTraits>& out) const {
+                out << "regex";
+            }
+
+        }; // class regex
+#endif
+
+        /**
+         * Matches if the test string is equal to any of the stored strings.
+         */
+        class list : public matcher {
+
+            std::vector<std::string> m_strings;
+
+        public:
+
+            explicit list() :
+                m_strings() {
+            }
+
+            explicit list(const std::vector<std::string>& strings) :
+                m_strings(strings) {
+            }
+
+            list& add_string(const char* str) {
+                m_strings.push_back(str);
+                return *this;
+            }
+
+            list& add_string(const std::string& str) {
+                m_strings.push_back(str);
+                return *this;
+            }
+
+            bool match(const char* test_string) const noexcept {
+                for (const auto& s : m_strings) {
+                    if (!std::strcmp(s.c_str(), test_string)) {
+                        return true;
+                    }
+                }
+                return false;
+
+            }
+
+            template <typename TChar, typename TTraits>
+            void print(std::basic_ostream<TChar, TTraits>& out) const {
+                out << "list[";
+                for (const auto& s : m_strings) {
+                    out << '[' << s << ']';
+                }
+                out << ']';
+            }
+
+        }; // class list
+
+    private:
+
+        using matcher_type = boost::variant<always_false,
+                                            always_true,
+                                            equal,
+                                            prefix,
+                                            substring,
+#ifdef OSMIUM_WITH_REGEX
+                                            regex,
+#endif
+                                            list>;
+
+        matcher_type m_matcher;
+
+        class match_visitor : public boost::static_visitor<bool> {
+
+            const char* m_str;
+
+        public:
+
+            match_visitor(const char* str) noexcept :
+                m_str(str) {
+            }
+
+            template <typename TMatcher>
+            bool operator()(const TMatcher& t) const noexcept {
+                return t.match(m_str);
+            }
+
+        }; // class match_visitor
+
+        template <typename TChar, typename TTraits>
+        class print_visitor : public boost::static_visitor<void> {
+
+            std::basic_ostream<TChar, TTraits>* m_out;
+
+        public:
+
+            print_visitor(std::basic_ostream<TChar, TTraits>& out) :
+                m_out(&out) {
+            }
+
+            template <typename TMatcher>
+            void operator()(const TMatcher& t) const noexcept {
+                t.print(*m_out);
+            }
+
+        }; // class print_visitor
+
+    public:
+
+        /**
+         * Create a string matcher that will never match.
+         */
+        StringMatcher() :
+            m_matcher(always_false{}) {
+        }
+
+        /**
+         * Create a string matcher that will always or never match based on
+         * the argument.
+         * Shortcut for
+         * @code StringMatcher{StringMatcher::always_true}; @endcode
+         * or
+         * @code StringMatcher{StringMatcher::always_false}; @endcode
+         */
+        StringMatcher(bool result) :
+            m_matcher(always_false{}) {
+            if (result) {
+                m_matcher = always_true{};
+            }
+        }
+
+        /**
+         * Create a string matcher that will match the specified string.
+         * Shortcut for
+         * @code StringMatcher{StringMatcher::equal{str}}; @endcode
+         */
+        StringMatcher(const char* str) :
+            m_matcher(equal{str}) {
+        }
+
+        /**
+         * Create a string matcher that will match the specified string.
+         * Shortcut for
+         * @code StringMatcher{StringMatcher::equal{str}}; @endcode
+         */
+        StringMatcher(const std::string& str) :
+            m_matcher(equal{str}) {
+        }
+
+#ifdef OSMIUM_WITH_REGEX
+        /**
+         * Create a string matcher that will match the specified regex.
+         * Shortcut for
+         * @code StringMatcher{StringMatcher::regex{aregex}}; @endcode
+         */
+        StringMatcher(const std::regex& aregex) :
+            m_matcher(regex{aregex}) {
+        }
+#endif
+
+        /**
+         * Create a string matcher that will match if any of the strings
+         * match.
+         * Shortcut for
+         * @code StringMatcher{StringMatcher::list{strings}}; @endcode
+         */
+        StringMatcher(const std::vector<std::string>& strings) :
+            m_matcher(list{strings}) {
+        }
+
+        /**
+         * Create a string matcher.
+         *
+         * @tparam TMatcher Must be one of the matcher classes
+         *                  osmium::StringMatcher::always_false, always_true,
+         *                  equal, prefix, substring, regex or list.
+         */
+        template <typename TMatcher, typename std::enable_if<
+            std::is_base_of<matcher, TMatcher>::value, int>::type = 0>
+        StringMatcher(TMatcher&& matcher) :
+            m_matcher(std::forward<TMatcher>(matcher)) {
+        }
+
+        /**
+         * Match the specified string.
+         */
+        bool operator()(const char* str) const noexcept {
+            return boost::apply_visitor(match_visitor{str}, m_matcher);
+        }
+
+        /**
+         * Match the specified string.
+         */
+        bool operator()(const std::string& str) const noexcept {
+            return operator()(str.c_str());
+        }
+
+        template <typename TChar, typename TTraits>
+        void print(std::basic_ostream<TChar, TTraits>& out) const {
+            boost::apply_visitor(print_visitor<TChar, TTraits>{out}, m_matcher);
+        }
+
+    }; // class StringMatcher
+
+    template <typename TChar, typename TTraits>
+    inline std::basic_ostream<TChar, TTraits>& operator<<(std::basic_ostream<TChar, TTraits>& out, const StringMatcher& matcher) {
+        matcher.print(out);
+        return out;
+    }
+
+} // namespace osmium
+
+#endif // OSMIUM_UTIL_STRING_MATCHER_HPP
diff --git a/include/osmium/version.hpp b/include/osmium/version.hpp
index d32641a..c5e8204 100644
--- a/include/osmium/version.hpp
+++ b/include/osmium/version.hpp
@@ -34,9 +34,9 @@ DEALINGS IN THE SOFTWARE.
 */
 
 #define LIBOSMIUM_VERSION_MAJOR 2
-#define LIBOSMIUM_VERSION_MINOR 11
+#define LIBOSMIUM_VERSION_MINOR 12
 #define LIBOSMIUM_VERSION_PATCH 0
 
-#define LIBOSMIUM_VERSION_STRING "2.11.0"
+#define LIBOSMIUM_VERSION_STRING "2.12.0"
 
 #endif // OSMIUM_VERSION_HPP
diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt
index db0e934..bf1b02d 100644
--- a/test/CMakeLists.txt
+++ b/test/CMakeLists.txt
@@ -58,6 +58,9 @@ function(add_unit_test _tgroup _tname)
                 message("  Adding libs: ${_param_LIBS}")
             endif()
             target_link_libraries(${_testid} ${_param_LIBS})
+            if(_param_LIBS MATCHES "lpthread")
+                set_pthread_on_target(${_testid})
+            endif()
         endif()
 
         add_test(NAME ${_testid}
@@ -119,6 +122,7 @@ endif()
 #
 #-----------------------------------------------------------------------------
 add_unit_test(area test_area_id)
+add_unit_test(area test_assembler)
 add_unit_test(area test_node_ref_segment)
 
 add_unit_test(osm test_area)
@@ -167,6 +171,7 @@ add_unit_test(io test_compression_factory)
 add_unit_test(io test_bzip2 ENABLE_IF ${BZIP2_FOUND} LIBS ${BZIP2_LIBRARIES})
 add_unit_test(io test_file_formats)
 add_unit_test(io test_reader LIBS "${OSMIUM_XML_LIBRARIES};${OSMIUM_PBF_LIBRARIES}")
+add_unit_test(io test_reader_fileformat ENABLE_IF ${Threads_FOUND} LIBS ${CMAKE_THREAD_LIBS_INIT})
 add_unit_test(io test_reader_with_mock_decompression ENABLE_IF ${Threads_FOUND} LIBS ${OSMIUM_XML_LIBRARIES})
 add_unit_test(io test_reader_with_mock_parser ENABLE_IF ${Threads_FOUND} LIBS ${CMAKE_THREAD_LIBS_INIT})
 add_unit_test(io test_opl_parser)
@@ -180,6 +185,8 @@ add_unit_test(io test_writer_with_mock_encoder ENABLE_IF ${Threads_FOUND} LIBS $
 add_unit_test(tags test_filter)
 add_unit_test(tags test_operators)
 add_unit_test(tags test_tag_list)
+add_unit_test(tags test_tag_matcher)
+add_unit_test(tags test_tags_filter)
 
 add_unit_test(thread test_pool ENABLE_IF ${Threads_FOUND} LIBS ${CMAKE_THREAD_LIBS_INIT})
 
@@ -192,6 +199,7 @@ add_unit_test(util test_memory_mapping)
 add_unit_test(util test_minmax)
 add_unit_test(util test_options)
 add_unit_test(util test_string)
+add_unit_test(util test_string_matcher)
 
 
 #-----------------------------------------------------------------------------
diff --git a/test/data-tests/CMakeLists.txt b/test/data-tests/CMakeLists.txt
index a36c31c..8e05267 100644
--- a/test/data-tests/CMakeLists.txt
+++ b/test/data-tests/CMakeLists.txt
@@ -37,6 +37,7 @@ include_directories("../include")
 #-----------------------------------------------------------------------------
 file(GLOB TESTCASE_CPPS testcases/*.cpp)
 add_executable(testdata-testcases testdata-testcases.cpp ${TESTCASE_CPPS})
+set_pthread_on_target(testdata-testcases)
 target_link_libraries(testdata-testcases
                       ${OSMIUM_XML_LIBRARIES}
 )
@@ -54,6 +55,7 @@ set_tests_properties(testdata-testcases PROPERTIES
 #
 #-----------------------------------------------------------------------------
 add_executable(testdata-xml testdata-xml.cpp)
+set_pthread_on_target(testdata-xml)
 target_link_libraries(testdata-xml
                       ${OSMIUM_XML_LIBRARIES}
 )
@@ -71,6 +73,7 @@ set_tests_properties(testdata-xml PROPERTIES
 #
 #-----------------------------------------------------------------------------
 add_executable(testdata-overview testdata-overview.cpp)
+set_pthread_on_target(testdata-overview)
 target_link_libraries(testdata-overview
                       ${OSMIUM_XML_LIBRARIES}
                       ${GDAL_LIBRARIES}
@@ -94,6 +97,7 @@ find_program(SPATIALITE spatialite)
 
 if(RUBY AND GEM_json_FOUND AND SPATIALITE)
     add_executable(testdata-multipolygon testdata-multipolygon.cpp)
+    set_pthread_on_target(testdata-multipolygon)
     target_link_libraries(testdata-multipolygon
                         ${OSMIUM_XML_LIBRARIES}
                         ${GDAL_LIBRARIES}
diff --git a/test/data-tests/testdata-xml.cpp b/test/data-tests/testdata-xml.cpp
index eb984f8..5191f8a 100644
--- a/test/data-tests/testdata-xml.cpp
+++ b/test/data-tests/testdata-xml.cpp
@@ -15,11 +15,11 @@
 #include <osmium/io/gzip_compression.hpp>
 #include <osmium/visitor.hpp>
 
-std::string S_(const char* s) {
+static std::string S_(const char* s) {
     return std::string{s};
 }
 
-std::string filename(const char* test_id, const char* suffix = "osm") {
+static std::string filename(const char* test_id, const char* suffix = "osm") {
     const char* testdir = getenv("TESTDIR");
     if (!testdir) {
         std::cerr << "You have to set TESTDIR environment variable before running testdata-xml\n";
@@ -48,7 +48,7 @@ struct header_buffer_type {
 // operations, because they make certain assumptions, for instance that
 // file contents fit into small buffers.
 
-std::string read_file(const char* test_id) {
+static std::string read_file(const char* test_id) {
     const int fd = osmium::io::detail::open_for_reading(filename(test_id));
     assert(fd >= 0);
 
@@ -62,19 +62,19 @@ std::string read_file(const char* test_id) {
     return input;
 }
 
-std::string read_gz_file(const char* test_id, const char* suffix) {
+static std::string read_gz_file(const char* test_id, const char* suffix) {
     const int fd = osmium::io::detail::open_for_reading(filename(test_id, suffix));
     assert(fd >= 0);
 
     osmium::io::GzipDecompressor gzip_decompressor{fd};
-    std::string input = gzip_decompressor.read();
+    const std::string input = gzip_decompressor.read();
     gzip_decompressor.close();
 
     return input;
 }
 
 
-header_buffer_type parse_xml(std::string input) {
+static header_buffer_type parse_xml(std::string input) {
     osmium::io::detail::future_string_queue_type input_queue;
     osmium::io::detail::future_buffer_queue_type output_queue;
     std::promise<osmium::io::Header> header_promise;
@@ -101,463 +101,404 @@ header_buffer_type parse_xml(std::string input) {
     return result;
 }
 
-header_buffer_type read_xml(const char* test_id) {
-    std::string input = read_file(test_id);
+static header_buffer_type read_xml(const char* test_id) {
+    const std::string input = read_file(test_id);
     return parse_xml(input);
 }
 
 // =============================================
 
-TEST_CASE("Reading OSM XML 100") {
-
-    SECTION("Direct") {
-        header_buffer_type r = read_xml("100-correct_but_no_data");
-
-        REQUIRE(r.header.get("generator") == "testdata");
-        REQUIRE(0 == r.buffer.committed());
-        REQUIRE(! r.buffer);
-    }
-
-    SECTION("Using Reader") {
-        osmium::io::Reader reader{filename("100-correct_but_no_data")};
-
-        const osmium::io::Header header{reader.header()};
-        REQUIRE(header.get("generator") == "testdata");
-
-        osmium::memory::Buffer buffer = reader.read();
-        REQUIRE(0 == buffer.committed());
-        REQUIRE(! buffer);
-        reader.close();
-    }
-
-    SECTION("Using Reader asking for header only") {
-        osmium::io::Reader reader{filename("100-correct_but_no_data"), osmium::osm_entity_bits::nothing};
-
-        const osmium::io::Header header{reader.header()};
-        REQUIRE(header.get("generator") == "testdata");
-        reader.close();
-    }
+TEST_CASE("Reading OSM XML 100: Direct") {
+    header_buffer_type r = read_xml("100-correct_but_no_data");
 
+    REQUIRE(r.header.get("generator") == "testdata");
+    REQUIRE(0 == r.buffer.committed());
+    REQUIRE(! r.buffer);
 }
 
-// =============================================
+TEST_CASE("Reading OSM XML 100: Using Reader") {
+    osmium::io::Reader reader{filename("100-correct_but_no_data")};
 
-TEST_CASE("Reading OSM XML 101") {
+    const osmium::io::Header header{reader.header()};
+    REQUIRE(header.get("generator") == "testdata");
 
-    SECTION("Direct") {
-        REQUIRE_THROWS_AS(read_xml("101-missing_version"), osmium::format_version_error);
-        try {
-            read_xml("101-missing_version");
-        } catch (const osmium::format_version_error& e) {
-            REQUIRE(e.version.empty());
-        }
-    }
+    osmium::memory::Buffer buffer = reader.read();
+    REQUIRE(0 == buffer.committed());
+    REQUIRE(! buffer);
+    reader.close();
+}
 
-    SECTION("Using Reader") {
-        REQUIRE_THROWS_AS({
-            osmium::io::Reader reader{filename("101-missing_version")};
-            const osmium::io::Header header{reader.header()};
-            osmium::memory::Buffer buffer = reader.read();
-            reader.close();
-        }, osmium::format_version_error);
-    }
+TEST_CASE("Reading OSM XML 100: Using Reader asking for header only") {
+    osmium::io::Reader reader{filename("100-correct_but_no_data"), osmium::osm_entity_bits::nothing};
 
+    const osmium::io::Header header{reader.header()};
+    REQUIRE(header.get("generator") == "testdata");
+    reader.close();
 }
 
 // =============================================
 
-TEST_CASE("Reading OSM XML 102") {
-
-    SECTION("Direct") {
-        REQUIRE_THROWS_AS(read_xml("102-wrong_version"), osmium::format_version_error);
-        try {
-            read_xml("102-wrong_version");
-        } catch (const osmium::format_version_error& e) {
-            REQUIRE(e.version == "0.1");
-        }
-    }
-
-    SECTION("Using Reader") {
-        REQUIRE_THROWS_AS({
-            osmium::io::Reader reader{filename("102-wrong_version")};
-
-            const osmium::io::Header header{reader.header()};
-            osmium::memory::Buffer buffer = reader.read();
-            reader.close();
-        }, osmium::format_version_error);
+TEST_CASE("Reading OSM XML 101: Direct") {
+    REQUIRE_THROWS_AS(read_xml("101-missing_version"), osmium::format_version_error);
+    try {
+        read_xml("101-missing_version");
+    } catch (const osmium::format_version_error& e) {
+        REQUIRE(e.version.empty());
     }
+}
 
+TEST_CASE("Reading OSM XML 101: Using Reader") {
+    REQUIRE_THROWS_AS([](){
+        osmium::io::Reader reader{filename("101-missing_version")};
+        const osmium::io::Header header{reader.header()};
+        osmium::memory::Buffer buffer = reader.read();
+        reader.close();
+    }(), osmium::format_version_error);
 }
 
 // =============================================
 
-TEST_CASE("Reading OSM XML 103") {
-
-    SECTION("Direct") {
-        REQUIRE_THROWS_AS(read_xml("103-old_version"), osmium::format_version_error);
-        try {
-            read_xml("103-old_version");
-        } catch (const osmium::format_version_error& e) {
-            REQUIRE(e.version == "0.5");
-        }
+TEST_CASE("Reading OSM XML 102: Direct") {
+    REQUIRE_THROWS_AS(read_xml("102-wrong_version"), osmium::format_version_error);
+    try {
+        read_xml("102-wrong_version");
+    } catch (const osmium::format_version_error& e) {
+        REQUIRE(e.version == "0.1");
     }
+}
 
-    SECTION("Using Reader") {
-        REQUIRE_THROWS_AS({
-            osmium::io::Reader reader{filename("103-old_version")};
-            const osmium::io::Header header{reader.header()};
-            osmium::memory::Buffer buffer = reader.read();
-            reader.close();
-        }, osmium::format_version_error);
-    }
+TEST_CASE("Reading OSM XML 102: Using Reader") {
+    REQUIRE_THROWS_AS([](){
+        osmium::io::Reader reader{filename("102-wrong_version")};
 
+        const osmium::io::Header header{reader.header()};
+        osmium::memory::Buffer buffer = reader.read();
+        reader.close();
+    }(), osmium::format_version_error);
 }
 
 // =============================================
 
-TEST_CASE("Reading OSM XML 104") {
-
-    SECTION("Direct") {
-        REQUIRE_THROWS_AS(read_xml("104-empty_file"), osmium::xml_error);
-        try {
-            read_xml("104-empty_file");
-        } catch (const osmium::xml_error& e) {
-            REQUIRE(e.line == 1);
-            REQUIRE(e.column == 0);
-        }
+TEST_CASE("Reading OSM XML 103: Direct") {
+    REQUIRE_THROWS_AS(read_xml("103-old_version"), osmium::format_version_error);
+    try {
+        read_xml("103-old_version");
+    } catch (const osmium::format_version_error& e) {
+        REQUIRE(e.version == "0.5");
     }
+}
 
-    SECTION("Using Reader") {
-        REQUIRE_THROWS_AS({
-            osmium::io::Reader reader{filename("104-empty_file")};
-            const osmium::io::Header header{reader.header()};
-            osmium::memory::Buffer buffer = reader.read();
-            reader.close();
-        }, osmium::xml_error);
-    }
+TEST_CASE("Reading OSM XML 103: Using Reader") {
+    REQUIRE_THROWS_AS([](){
+        osmium::io::Reader reader{filename("103-old_version")};
+        const osmium::io::Header header{reader.header()};
+        osmium::memory::Buffer buffer = reader.read();
+        reader.close();
+    }(), osmium::format_version_error);
 }
 
 // =============================================
 
-TEST_CASE("Reading OSM XML 105") {
-
-    SECTION("Direct") {
-        REQUIRE_THROWS_AS(read_xml("105-incomplete_xml_file"), osmium::xml_error);
-    }
-
-    SECTION("Using Reader") {
-        REQUIRE_THROWS_AS({
-            osmium::io::Reader reader{filename("105-incomplete_xml_file")};
-            const osmium::io::Header header{reader.header()};
-            osmium::memory::Buffer buffer = reader.read();
-            reader.close();
-        }, osmium::xml_error);
+TEST_CASE("Reading OSM XML 104: Direct") {
+    REQUIRE_THROWS_AS(read_xml("104-empty_file"), osmium::xml_error);
+    try {
+        read_xml("104-empty_file");
+    } catch (const osmium::xml_error& e) {
+        REQUIRE(e.line == 1);
+        REQUIRE(e.column == 0);
     }
+}
 
+TEST_CASE("Reading OSM XML 104: Using Reader") {
+    REQUIRE_THROWS_AS([](){
+        osmium::io::Reader reader{filename("104-empty_file")};
+        const osmium::io::Header header{reader.header()};
+        osmium::memory::Buffer buffer = reader.read();
+        reader.close();
+    }(), osmium::xml_error);
 }
 
 // =============================================
 
-TEST_CASE("Reading OSM XML 120") {
-
-    SECTION("Direct") {
-        std::string data = read_gz_file("120-correct_gzip_file_without_data", "osm.gz");
-
-        REQUIRE(data.size() == 102);
-
-        header_buffer_type r = parse_xml(data);
-        REQUIRE(r.header.get("generator") == "testdata");
-        REQUIRE(0 == r.buffer.committed());
-        REQUIRE(! r.buffer);
-    }
-
-    SECTION("Using Reader") {
-        osmium::io::Reader reader{filename("120-correct_gzip_file_without_data", "osm.gz")};
+TEST_CASE("Reading OSM XML 105: Direct") {
+    REQUIRE_THROWS_AS(read_xml("105-incomplete_xml_file"), osmium::xml_error);
+}
 
+TEST_CASE("Reading OSM XML 105: Using Reader") {
+    REQUIRE_THROWS_AS([](){
+        osmium::io::Reader reader{filename("105-incomplete_xml_file")};
         const osmium::io::Header header{reader.header()};
-        REQUIRE(header.get("generator") == "testdata");
-
         osmium::memory::Buffer buffer = reader.read();
-        REQUIRE(0 == buffer.committed());
-        REQUIRE(! buffer);
         reader.close();
-    }
-
+    }(), osmium::xml_error);
 }
 
 // =============================================
 
-TEST_CASE("Reading OSM XML 121") {
+TEST_CASE("Reading OSM XML 120: Direct") {
+    std::string data = read_gz_file("120-correct_gzip_file_without_data", "osm.gz");
 
-    SECTION("Direct") {
-        REQUIRE_THROWS_AS( {
-            read_gz_file("121-truncated_gzip_file", "osm.gz");
-        }, osmium::gzip_error);
-    }
-
-    SECTION("Using Reader") {
-        // can throw osmium::gzip_error or osmium::xml_error
-        REQUIRE_THROWS({
-            osmium::io::Reader reader{filename("121-truncated_gzip_file", "osm.gz")};
-            const osmium::io::Header header{reader.header()};
-            osmium::memory::Buffer buffer = reader.read();
-            reader.close();
-        });
-    }
+    REQUIRE(data.size() == 102);
 
+    header_buffer_type r = parse_xml(data);
+    REQUIRE(r.header.get("generator") == "testdata");
+    REQUIRE(0 == r.buffer.committed());
+    REQUIRE(! r.buffer);
 }
 
-// =============================================
+TEST_CASE("Reading OSM XML 120: Using Reader") {
+    osmium::io::Reader reader{filename("120-correct_gzip_file_without_data", "osm.gz")};
 
-TEST_CASE("Reading OSM XML 122") {
+    const osmium::io::Header header{reader.header()};
+    REQUIRE(header.get("generator") == "testdata");
 
-    SECTION("Direct") {
-        REQUIRE_THROWS_AS( {
-            read_xml("122-no_osm_element");
-        }, osmium::xml_error);
-    }
+    osmium::memory::Buffer buffer = reader.read();
+    REQUIRE(0 == buffer.committed());
+    REQUIRE(! buffer);
+    reader.close();
+}
 
-    SECTION("Using Reader") {
-        REQUIRE_THROWS_AS({
-            osmium::io::Reader reader{filename("122-no_osm_element")};
-            const osmium::io::Header header{reader.header()};
-            osmium::memory::Buffer buffer = reader.read();
-            reader.close();
-        }, osmium::xml_error);
-    }
+// =============================================
 
+TEST_CASE("Reading OSM XML 121: Direct") {
+    REQUIRE_THROWS_AS(read_gz_file("121-truncated_gzip_file", "osm.gz"), osmium::gzip_error);
+}
+
+TEST_CASE("Reading OSM XML 121: Using Reader") {
+    // can throw osmium::gzip_error or osmium::xml_error
+    REQUIRE_THROWS([](){
+        osmium::io::Reader reader{filename("121-truncated_gzip_file", "osm.gz")};
+        const osmium::io::Header header{reader.header()};
+        osmium::memory::Buffer buffer = reader.read();
+        reader.close();
+    }());
 }
 
 // =============================================
 
-TEST_CASE("Reading OSM XML 140") {
+TEST_CASE("Reading OSM XML 122: Direct") {
+    REQUIRE_THROWS_AS(read_xml("122-no_osm_element"), osmium::xml_error);
+}
 
-    SECTION("Using Reader") {
-        osmium::io::Reader reader{filename("140-unicode")};
+TEST_CASE("Reading OSM XML 122: Using Reader") {
+    REQUIRE_THROWS_AS([](){
+        osmium::io::Reader reader{filename("122-no_osm_element")};
+        const osmium::io::Header header{reader.header()};
         osmium::memory::Buffer buffer = reader.read();
         reader.close();
+    }(), osmium::xml_error);
+}
+
+// =============================================
+
+TEST_CASE("Reading OSM XML 140: Using Reader") {
+    osmium::io::Reader reader{filename("140-unicode")};
+    osmium::memory::Buffer buffer = reader.read();
+    reader.close();
 
-        int count = 0;
-        for (const auto& node : buffer.select<osmium::Node>()) {
-            ++count;
-            REQUIRE(node.id() == count);
-            const osmium::TagList& t = node.tags();
+    int count = 0;
+    for (const auto& node : buffer.select<osmium::Node>()) {
+        ++count;
+        REQUIRE(node.id() == count);
+        const osmium::TagList& t = node.tags();
 
-            const char* uc = t["unicode_char"];
+        const char* uc = t["unicode_char"];
 
-            const auto len = atoi(t["unicode_utf8_length"]);
-            REQUIRE(len == strlen(uc));
+        const auto len = atoi(t["unicode_utf8_length"]);
+        REQUIRE(len == strlen(uc));
 
-            REQUIRE(S_(uc) == t["unicode_xml"]);
+        REQUIRE(S_(uc) == t["unicode_xml"]);
 
 // workaround for missing support for u8 string literals on Windows
 #if !defined(_MSC_VER)
-            switch (count) {
-                case 1:
-                    REQUIRE(S_(uc) ==  u8"a");
-                    break;
-                case 2:
-                    REQUIRE(S_(uc) == u8"\u00e4");
-                    break;
-                case 3:
-                    REQUIRE(S_(uc) == u8"\u30dc");
-                    break;
-                case 4:
-                    REQUIRE(S_(uc) == u8"\U0001d11e");
-                    break;
-                case 5:
-                    REQUIRE(S_(uc) == u8"\U0001f6eb");
-                    break;
-                default:
-                    REQUIRE(false); // should not be here
-            }
-#endif
+        switch (count) {
+            case 1:
+                REQUIRE(S_(uc) ==  u8"a");
+                break;
+            case 2:
+                REQUIRE(S_(uc) == u8"\u00e4");
+                break;
+            case 3:
+                REQUIRE(S_(uc) == u8"\u30dc");
+                break;
+            case 4:
+                REQUIRE(S_(uc) == u8"\U0001d11e");
+                break;
+            case 5:
+                REQUIRE(S_(uc) == u8"\U0001f6eb");
+                break;
+            default:
+                REQUIRE(false); // should not be here
         }
-        REQUIRE(count == 5);
+#endif
     }
-
+    REQUIRE(count == 5);
 }
 
-
 // =============================================
 
-TEST_CASE("Reading OSM XML 141") {
-
-    SECTION("Using Reader") {
-        osmium::io::Reader reader{filename("141-entities")};
-        osmium::memory::Buffer buffer = reader.read();
-        reader.close();
-        REQUIRE(buffer.committed() > 0);
-        REQUIRE(buffer.get<osmium::memory::Item>(0).type() == osmium::item_type::node);
-
-        const osmium::Node& node = buffer.get<osmium::Node>(0);
-        const osmium::TagList& tags = node.tags();
-
-        REQUIRE(S_(tags["less-than"])    == "<");
-        REQUIRE(S_(tags["greater-than"]) == ">");
-        REQUIRE(S_(tags["apostrophe"])   == "'");
-        REQUIRE(S_(tags["ampersand"])    == "&");
-        REQUIRE(S_(tags["quote"])        == "\"");
-    }
-
+TEST_CASE("Reading OSM XML 141: Using Reader") {
+    osmium::io::Reader reader{filename("141-entities")};
+    osmium::memory::Buffer buffer = reader.read();
+    reader.close();
+    REQUIRE(buffer.committed() > 0);
+    REQUIRE(buffer.get<osmium::memory::Item>(0).type() == osmium::item_type::node);
+
+    const osmium::Node& node = buffer.get<osmium::Node>(0);
+    const osmium::TagList& tags = node.tags();
+
+    REQUIRE(S_(tags["less-than"])    == "<");
+    REQUIRE(S_(tags["greater-than"]) == ">");
+    REQUIRE(S_(tags["apostrophe"])   == "'");
+    REQUIRE(S_(tags["ampersand"])    == "&");
+    REQUIRE(S_(tags["quote"])        == "\"");
 }
 
-
 // =============================================
 
-TEST_CASE("Reading OSM XML 142") {
-
-    SECTION("Using Reader to read nodes") {
-        osmium::io::Reader reader{filename("142-whitespace")};
-        osmium::memory::Buffer buffer = reader.read();
-        reader.close();
-
-        int count = 0;
-        for (const auto& node : buffer.select<osmium::Node>()) {
-            ++count;
-            REQUIRE(node.id() == count);
-            REQUIRE(node.tags().size() == 1);
-            const osmium::Tag& tag = *(node.tags().begin());
-
-            switch (count) {
-                case 1:
-                    REQUIRE(S_(node.user()) == "user name");
-                    REQUIRE(S_(tag.key()) == "key with space");
-                    REQUIRE(S_(tag.value()) == "value with space");
-                    break;
-                case 2:
-                    REQUIRE(S_(node.user()) == "line\nfeed");
-                    REQUIRE(S_(tag.key()) == "key with\nlinefeed");
-                    REQUIRE(S_(tag.value()) == "value with\nlinefeed");
-                    break;
-                case 3:
-                    REQUIRE(S_(node.user()) == "carriage\rreturn");
-                    REQUIRE(S_(tag.key()) == "key with\rcarriage\rreturn");
-                    REQUIRE(S_(tag.value()) == "value with\rcarriage\rreturn");
-                    break;
-                case 4:
-                    REQUIRE(S_(node.user()) == "tab\tulator");
-                    REQUIRE(S_(tag.key()) == "key with\ttab");
-                    REQUIRE(S_(tag.value()) == "value with\ttab");
-                    break;
-                case 5:
-                    REQUIRE(S_(node.user()) == "unencoded linefeed");
-                    REQUIRE(S_(tag.key()) == "key with unencoded linefeed");
-                    REQUIRE(S_(tag.value()) == "value with unencoded linefeed");
-                    break;
-                default:
-                    REQUIRE(false); // should not be here
-            }
+TEST_CASE("Reading OSM XML 142: Using Reader to read nodes") {
+    osmium::io::Reader reader{filename("142-whitespace")};
+    osmium::memory::Buffer buffer = reader.read();
+    reader.close();
+
+    int count = 0;
+    for (const auto& node : buffer.select<osmium::Node>()) {
+        ++count;
+        REQUIRE(node.id() == count);
+        REQUIRE(node.tags().size() == 1);
+        const osmium::Tag& tag = *(node.tags().begin());
+
+        switch (count) {
+            case 1:
+                REQUIRE(S_(node.user()) == "user name");
+                REQUIRE(S_(tag.key()) == "key with space");
+                REQUIRE(S_(tag.value()) == "value with space");
+                break;
+            case 2:
+                REQUIRE(S_(node.user()) == "line\nfeed");
+                REQUIRE(S_(tag.key()) == "key with\nlinefeed");
+                REQUIRE(S_(tag.value()) == "value with\nlinefeed");
+                break;
+            case 3:
+                REQUIRE(S_(node.user()) == "carriage\rreturn");
+                REQUIRE(S_(tag.key()) == "key with\rcarriage\rreturn");
+                REQUIRE(S_(tag.value()) == "value with\rcarriage\rreturn");
+                break;
+            case 4:
+                REQUIRE(S_(node.user()) == "tab\tulator");
+                REQUIRE(S_(tag.key()) == "key with\ttab");
+                REQUIRE(S_(tag.value()) == "value with\ttab");
+                break;
+            case 5:
+                REQUIRE(S_(node.user()) == "unencoded linefeed");
+                REQUIRE(S_(tag.key()) == "key with unencoded linefeed");
+                REQUIRE(S_(tag.value()) == "value with unencoded linefeed");
+                break;
+            default:
+                REQUIRE(false); // should not be here
         }
-        REQUIRE(count == 5);
     }
+    REQUIRE(count == 5);
+}
 
-    SECTION("Using Reader to read relation") {
-        osmium::io::Reader reader{filename("142-whitespace")};
-        osmium::memory::Buffer buffer = reader.read();
-        reader.close();
-
-        auto it = buffer.select<osmium::Relation>().begin();
-        REQUIRE(it != buffer.select<osmium::Relation>().end());
-        REQUIRE(it->id() == 21);
-        const auto& members = it->members();
-        REQUIRE(members.size() == 5);
-
-        int count = 0;
-        for (const auto& member : members) {
-            ++count;
-            switch (count) {
-                case 1:
-                    REQUIRE(S_(member.role()) == "role with whitespace");
-                    break;
-                case 2:
-                    REQUIRE(S_(member.role()) == "role with\nlinefeed");
-                    break;
-                case 3:
-                    REQUIRE(S_(member.role()) == "role with\rcarriage\rreturn");
-                    break;
-                case 4:
-                    REQUIRE(S_(member.role()) == "role with\ttab");
-                    break;
-                case 5:
-                    REQUIRE(S_(member.role()) == "role with unencoded linefeed");
-                    break;
-                default:
-                    REQUIRE(false); // should not be here
-            }
+TEST_CASE("Reading OSM XML 142: Using Reader to read relation") {
+    osmium::io::Reader reader{filename("142-whitespace")};
+    osmium::memory::Buffer buffer = reader.read();
+    reader.close();
+
+    auto it = buffer.select<osmium::Relation>().begin();
+    REQUIRE(it != buffer.select<osmium::Relation>().end());
+    REQUIRE(it->id() == 21);
+    const auto& members = it->members();
+    REQUIRE(members.size() == 5);
+
+    int count = 0;
+    for (const auto& member : members) {
+        ++count;
+        switch (count) {
+            case 1:
+                REQUIRE(S_(member.role()) == "role with whitespace");
+                break;
+            case 2:
+                REQUIRE(S_(member.role()) == "role with\nlinefeed");
+                break;
+            case 3:
+                REQUIRE(S_(member.role()) == "role with\rcarriage\rreturn");
+                break;
+            case 4:
+                REQUIRE(S_(member.role()) == "role with\ttab");
+                break;
+            case 5:
+                REQUIRE(S_(member.role()) == "role with unencoded linefeed");
+                break;
+            default:
+                REQUIRE(false); // should not be here
         }
-        REQUIRE(count == 5);
     }
-
+    REQUIRE(count == 5);
 }
 
 
 // =============================================
 
-TEST_CASE("Reading OSM XML 200") {
+TEST_CASE("Reading OSM XML 200: Direct") {
+    header_buffer_type r = read_xml("200-nodes");
 
-    SECTION("Direct") {
-        header_buffer_type r = read_xml("200-nodes");
-
-        REQUIRE(r.header.get("generator") == "testdata");
-        REQUIRE(r.buffer.committed() > 0);
-        REQUIRE(r.buffer.get<osmium::memory::Item>(0).type() == osmium::item_type::node);
-        REQUIRE(r.buffer.get<osmium::Node>(0).id() == 36966060);
-        REQUIRE(std::distance(r.buffer.begin(), r.buffer.end()) == 3);
-    }
+    REQUIRE(r.header.get("generator") == "testdata");
+    REQUIRE(r.buffer.committed() > 0);
+    REQUIRE(r.buffer.get<osmium::memory::Item>(0).type() == osmium::item_type::node);
+    REQUIRE(r.buffer.get<osmium::Node>(0).id() == 36966060);
+    REQUIRE(std::distance(r.buffer.begin(), r.buffer.end()) == 3);
+}
 
-    SECTION("Using Reader") {
-        osmium::io::Reader reader{filename("200-nodes")};
+TEST_CASE("Reading OSM XML 200: Using Reader") {
+    osmium::io::Reader reader{filename("200-nodes")};
 
-        const osmium::io::Header header{reader.header()};
-        REQUIRE(header.get("generator") == "testdata");
-
-        osmium::memory::Buffer buffer = reader.read();
-        REQUIRE(buffer.committed() > 0);
-        REQUIRE(buffer.get<osmium::memory::Item>(0).type() == osmium::item_type::node);
-        REQUIRE(buffer.get<osmium::Node>(0).id() == 36966060);
-        REQUIRE(std::distance(buffer.begin(), buffer.end()) == 3);
-        reader.close();
-    }
+    const osmium::io::Header header{reader.header()};
+    REQUIRE(header.get("generator") == "testdata");
 
-    SECTION("Using Reader asking for nodes") {
-        osmium::io::Reader reader{filename("200-nodes"), osmium::osm_entity_bits::node};
+    osmium::memory::Buffer buffer = reader.read();
+    REQUIRE(buffer.committed() > 0);
+    REQUIRE(buffer.get<osmium::memory::Item>(0).type() == osmium::item_type::node);
+    REQUIRE(buffer.get<osmium::Node>(0).id() == 36966060);
+    REQUIRE(std::distance(buffer.begin(), buffer.end()) == 3);
+    reader.close();
+}
 
-        const osmium::io::Header header{reader.header()};
-        REQUIRE(header.get("generator") == "testdata");
+TEST_CASE("Reading OSM XML 200: Using Reader asking for nodes") {
+    osmium::io::Reader reader{filename("200-nodes"), osmium::osm_entity_bits::node};
 
-        osmium::memory::Buffer buffer = reader.read();
-        REQUIRE(buffer.committed() > 0);
-        REQUIRE(buffer.get<osmium::memory::Item>(0).type() == osmium::item_type::node);
-        REQUIRE(buffer.get<osmium::Node>(0).id() == 36966060);
-        REQUIRE(std::distance(buffer.begin(), buffer.end()) == 3);
-        reader.close();
-    }
+    const osmium::io::Header header{reader.header()};
+    REQUIRE(header.get("generator") == "testdata");
 
-    SECTION("Using Reader asking for header only") {
-        osmium::io::Reader reader{filename("200-nodes"), osmium::osm_entity_bits::nothing};
+    osmium::memory::Buffer buffer = reader.read();
+    REQUIRE(buffer.committed() > 0);
+    REQUIRE(buffer.get<osmium::memory::Item>(0).type() == osmium::item_type::node);
+    REQUIRE(buffer.get<osmium::Node>(0).id() == 36966060);
+    REQUIRE(std::distance(buffer.begin(), buffer.end()) == 3);
+    reader.close();
+}
 
-        const osmium::io::Header header{reader.header()};
-        REQUIRE(header.get("generator") == "testdata");
+TEST_CASE("Reading OSM XML 200: Using Reader asking for header only") {
+    osmium::io::Reader reader{filename("200-nodes"), osmium::osm_entity_bits::nothing};
 
-        REQUIRE_THROWS({
-            reader.read();
-        });
+    const osmium::io::Header header{reader.header()};
+    REQUIRE(header.get("generator") == "testdata");
 
-        reader.close();
-    }
+    REQUIRE_THROWS(reader.read());
 
-    SECTION("Using Reader asking for ways") {
-        osmium::io::Reader reader{filename("200-nodes"), osmium::osm_entity_bits::way};
+    reader.close();
+}
 
-        const osmium::io::Header header{reader.header()};
-        REQUIRE(header.get("generator") == "testdata");
+TEST_CASE("Reading OSM XML 200: Using Reader asking for ways") {
+    osmium::io::Reader reader{filename("200-nodes"), osmium::osm_entity_bits::way};
 
-        osmium::memory::Buffer buffer = reader.read();
-        REQUIRE(0 == buffer.committed());
-        REQUIRE(! buffer);
-        reader.close();
-    }
+    const osmium::io::Header header{reader.header()};
+    REQUIRE(header.get("generator") == "testdata");
 
+    osmium::memory::Buffer buffer = reader.read();
+    REQUIRE(0 == buffer.committed());
+    REQUIRE(! buffer);
+    reader.close();
 }
 
diff --git a/test/include/catch.hpp b/test/include/catch.hpp
index 3d18ead..6f9334b 100644
--- a/test/include/catch.hpp
+++ b/test/include/catch.hpp
@@ -1,6 +1,6 @@
 /*
- *  Catch v1.5.9
- *  Generated: 2016-11-29 12:14:38.049276
+ *  Catch v1.8.1
+ *  Generated: 2017-03-01 16:04:19.016511
  *  ----------------------------------------------------------
  *  This file has been merged from multiple headers. Please don't edit it directly
  *  Copyright (c) 2012 Two Blue Cubes Ltd. All rights reserved.
@@ -40,6 +40,12 @@
 #elif defined __GNUC__
 #    pragma GCC diagnostic ignored "-Wvariadic-macros"
 #    pragma GCC diagnostic ignored "-Wunused-variable"
+
+     // For newer version we can use __Pragma to disable the warnings locally
+#    if __GNUC__ == 4 && __GNUC_MINOR__ >= 4 && __GNUC_MINOR__ <= 7
+#        pragma GCC diagnostic ignored "-Wparentheses"
+#    endif
+
 #    pragma GCC diagnostic push
 #    pragma GCC diagnostic ignored "-Wpadded"
 #endif
@@ -60,21 +66,6 @@
 // #included from: catch_common.h
 #define TWOBLUECUBES_CATCH_COMMON_H_INCLUDED
 
-#define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
-#define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
-#ifdef CATCH_CONFIG_COUNTER
-#  define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
-#else
-#  define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
-#endif
-
-#define INTERNAL_CATCH_STRINGIFY2( expr ) #expr
-#define INTERNAL_CATCH_STRINGIFY( expr ) INTERNAL_CATCH_STRINGIFY2( expr )
-
-#include <sstream>
-#include <stdexcept>
-#include <algorithm>
-
 // #included from: catch_compiler_capabilities.h
 #define TWOBLUECUBES_CATCH_COMPILER_CAPABILITIES_HPP_INCLUDED
 
@@ -89,11 +80,15 @@
 // CATCH_CONFIG_CPP11_LONG_LONG : is long long supported?
 // CATCH_CONFIG_CPP11_OVERRIDE : is override supported?
 // CATCH_CONFIG_CPP11_UNIQUE_PTR : is unique_ptr supported (otherwise use auto_ptr)
+// CATCH_CONFIG_CPP11_SHUFFLE : is std::shuffle supported?
+// CATCH_CONFIG_CPP11_TYPE_TRAITS : are type_traits and enable_if supported?
 
 // CATCH_CONFIG_CPP11_OR_GREATER : Is C++11 supported?
 
 // CATCH_CONFIG_VARIADIC_MACROS : are variadic macros supported?
 // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
+// CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
+// CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
 // ****************
 // Note to maintainers: if new toggles are added please document them
 // in configuration.md, too
@@ -129,12 +124,30 @@
 #  endif
 
 #   if defined(CATCH_CPP11_OR_GREATER)
-#       define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
+#       define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
+            _Pragma( "clang diagnostic push" ) \
+            _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
+#       define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
+            _Pragma( "clang diagnostic pop" )
 #   endif
 
 #endif // __clang__
 
 ////////////////////////////////////////////////////////////////////////////////
+// Cygwin
+#ifdef __CYGWIN__
+
+#   if !defined(CATCH_CONFIG_POSIX_SIGNALS)
+#       define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
+#   endif
+
+// Required for some versions of Cygwin to declare gettimeofday
+// see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
+#   define _BSD_SOURCE
+
+#endif // __CYGWIN__
+
+////////////////////////////////////////////////////////////////////////////////
 // Borland
 #ifdef __BORLANDC__
 
@@ -156,12 +169,20 @@
 // GCC
 #ifdef __GNUC__
 
+#   if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)
+#       define CATCH_GCC_HAS_NEW_PRAGMA
+#   endif
+
 #   if __GNUC__ == 4 && __GNUC_MINOR__ >= 6 && defined(__GXX_EXPERIMENTAL_CXX0X__)
 #       define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR
 #   endif
 
-#   if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS) && defined(CATCH_CPP11_OR_GREATER)
-#       define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS _Pragma( "GCC diagnostic ignored \"-Wparentheses\"" )
+#   if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS) && defined(CATCH_GCC_HAS_NEW_PRAGMA)
+#       define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
+            _Pragma( "GCC diagnostic push" ) \
+            _Pragma( "GCC diagnostic ignored \"-Wparentheses\"" )
+#       define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
+            _Pragma( "GCC diagnostic pop" )
 #   endif
 
 // - otherwise more recent versions define __cplusplus >= 201103L
@@ -173,6 +194,8 @@
 // Visual C++
 #ifdef _MSC_VER
 
+#define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
+
 #if (_MSC_VER >= 1600)
 #   define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR
 #   define CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR
@@ -181,6 +204,8 @@
 #if (_MSC_VER >= 1900 ) // (VC++ 13 (VS2015))
 #define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT
 #define CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS
+#define CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE
+#define CATCH_INTERNAL_CONFIG_CPP11_TYPE_TRAITS
 #endif
 
 #endif // _MSC_VER
@@ -246,6 +271,12 @@
 #  if !defined(CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR)
 #    define CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR
 #  endif
+# if !defined(CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE)
+#   define CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE
+#  endif
+# if !defined(CATCH_INTERNAL_CONFIG_CPP11_TYPE_TRAITS)
+#  define CATCH_INTERNAL_CONFIG_CPP11_TYPE_TRAITS
+# endif
 
 #endif // __cplusplus >= 201103L
 
@@ -268,21 +299,38 @@
 #if defined(CATCH_INTERNAL_CONFIG_VARIADIC_MACROS) && !defined(CATCH_CONFIG_NO_VARIADIC_MACROS) && !defined(CATCH_CONFIG_VARIADIC_MACROS)
 #   define CATCH_CONFIG_VARIADIC_MACROS
 #endif
-#if defined(CATCH_INTERNAL_CONFIG_CPP11_LONG_LONG) && !defined(CATCH_CONFIG_NO_LONG_LONG) && !defined(CATCH_CONFIG_CPP11_LONG_LONG) && !defined(CATCH_CONFIG_NO_CPP11)
+#if defined(CATCH_INTERNAL_CONFIG_CPP11_LONG_LONG) && !defined(CATCH_CONFIG_CPP11_NO_LONG_LONG) && !defined(CATCH_CONFIG_CPP11_LONG_LONG) && !defined(CATCH_CONFIG_NO_CPP11)
 #   define CATCH_CONFIG_CPP11_LONG_LONG
 #endif
-#if defined(CATCH_INTERNAL_CONFIG_CPP11_OVERRIDE) && !defined(CATCH_CONFIG_NO_OVERRIDE) && !defined(CATCH_CONFIG_CPP11_OVERRIDE) && !defined(CATCH_CONFIG_NO_CPP11)
+#if defined(CATCH_INTERNAL_CONFIG_CPP11_OVERRIDE) && !defined(CATCH_CONFIG_CPP11_NO_OVERRIDE) && !defined(CATCH_CONFIG_CPP11_OVERRIDE) && !defined(CATCH_CONFIG_NO_CPP11)
 #   define CATCH_CONFIG_CPP11_OVERRIDE
 #endif
-#if defined(CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) && !defined(CATCH_CONFIG_NO_UNIQUE_PTR) && !defined(CATCH_CONFIG_CPP11_UNIQUE_PTR) && !defined(CATCH_CONFIG_NO_CPP11)
+#if defined(CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) && !defined(CATCH_CONFIG_CPP11_NO_UNIQUE_PTR) && !defined(CATCH_CONFIG_CPP11_UNIQUE_PTR) && !defined(CATCH_CONFIG_NO_CPP11)
 #   define CATCH_CONFIG_CPP11_UNIQUE_PTR
 #endif
-#if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
+// Use of __COUNTER__ is suppressed if __JETBRAINS_IDE__ is #defined (meaning we're being parsed by a JetBrains IDE for
+// analytics) because, at time of writing, __COUNTER__ is not properly handled by it.
+// This does not affect compilation
+#if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER) && !defined(__JETBRAINS_IDE__)
 #   define CATCH_CONFIG_COUNTER
 #endif
+#if defined(CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE) && !defined(CATCH_CONFIG_CPP11_NO_SHUFFLE) && !defined(CATCH_CONFIG_CPP11_SHUFFLE) && !defined(CATCH_CONFIG_NO_CPP11)
+#   define CATCH_CONFIG_CPP11_SHUFFLE
+#endif
+# if defined(CATCH_INTERNAL_CONFIG_CPP11_TYPE_TRAITS) && !defined(CATCH_CONFIG_CPP11_NO_TYPE_TRAITS) && !defined(CATCH_CONFIG_CPP11_TYPE_TRAITS) && !defined(CATCH_CONFIG_NO_CPP11)
+#  define CATCH_CONFIG_CPP11_TYPE_TRAITS
+# endif
+#if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH)
+#   define CATCH_CONFIG_WINDOWS_SEH
+#endif
+// This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
+#if !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS)
+#   define CATCH_CONFIG_POSIX_SIGNALS
+#endif
 
 #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
 #   define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
+#   define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS
 #endif
 
 // noexcept support:
@@ -315,6 +363,20 @@
 #   define CATCH_AUTO_PTR( T ) std::auto_ptr<T>
 #endif
 
+#define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
+#define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
+#ifdef CATCH_CONFIG_COUNTER
+#  define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
+#else
+#  define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
+#endif
+
+#define INTERNAL_CATCH_STRINGIFY2( expr ) #expr
+#define INTERNAL_CATCH_STRINGIFY( expr ) INTERNAL_CATCH_STRINGIFY2( expr )
+
+#include <sstream>
+#include <algorithm>
+
 namespace Catch {
 
     struct IConfig;
@@ -367,7 +429,9 @@ namespace Catch {
     }
 
     bool startsWith( std::string const& s, std::string const& prefix );
+    bool startsWith( std::string const& s, char prefix );
     bool endsWith( std::string const& s, std::string const& suffix );
+    bool endsWith( std::string const& s, char suffix );
     bool contains( std::string const& s, std::string const& infix );
     void toLowerInPlace( std::string& s );
     std::string toLower( std::string const& s );
@@ -387,8 +451,8 @@ namespace Catch {
 
         SourceLineInfo();
         SourceLineInfo( char const* _file, std::size_t _line );
-        SourceLineInfo( SourceLineInfo const& other );
 #  ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
+        SourceLineInfo(SourceLineInfo const& other)          = default;
         SourceLineInfo( SourceLineInfo && )                  = default;
         SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
         SourceLineInfo& operator = ( SourceLineInfo && )     = default;
@@ -397,7 +461,7 @@ namespace Catch {
         bool operator == ( SourceLineInfo const& other ) const;
         bool operator < ( SourceLineInfo const& other ) const;
 
-        std::string file;
+        char const* file;
         std::size_t line;
     };
 
@@ -431,8 +495,6 @@ namespace Catch {
 #define CATCH_INTERNAL_LINEINFO ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
 #define CATCH_INTERNAL_ERROR( msg ) ::Catch::throwLogicError( msg, CATCH_INTERNAL_LINEINFO );
 
-#include <ostream>
-
 namespace Catch {
 
     class NotImplementedException : public std::exception
@@ -565,10 +627,6 @@ namespace Catch {
 #pragma clang diagnostic pop
 #endif
 
-#include <memory>
-#include <vector>
-#include <stdlib.h>
-
 namespace Catch {
 
     class TestCase;
@@ -832,6 +890,30 @@ namespace Catch {
 
 namespace Catch {
 
+    struct STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison;
+
+    struct DecomposedExpression
+    {
+        virtual ~DecomposedExpression() {}
+        virtual bool isBinaryExpression() const {
+            return false;
+        }
+        virtual void reconstructExpression( std::string& dest ) const = 0;
+
+        // Only simple binary comparisons can be decomposed.
+        // If more complex check is required then wrap sub-expressions in parentheses.
+        template<typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator + ( T const& );
+        template<typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator - ( T const& );
+        template<typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator * ( T const& );
+        template<typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator / ( T const& );
+        template<typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator % ( T const& );
+        template<typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator && ( T const& );
+        template<typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator || ( T const& );
+
+	private:
+		DecomposedExpression& operator = (DecomposedExpression const&);
+    };
+
     struct AssertionInfo
     {
         AssertionInfo() {}
@@ -848,11 +930,41 @@ namespace Catch {
 
     struct AssertionResultData
     {
-        AssertionResultData() : resultType( ResultWas::Unknown ) {}
+        AssertionResultData() : decomposedExpression( CATCH_NULL )
+                              , resultType( ResultWas::Unknown )
+                              , negated( false )
+                              , parenthesized( false ) {}
+
+        void negate( bool parenthesize ) {
+            negated = !negated;
+            parenthesized = parenthesize;
+            if( resultType == ResultWas::Ok )
+                resultType = ResultWas::ExpressionFailed;
+            else if( resultType == ResultWas::ExpressionFailed )
+                resultType = ResultWas::Ok;
+        }
+
+        std::string const& reconstructExpression() const {
+            if( decomposedExpression != CATCH_NULL ) {
+                decomposedExpression->reconstructExpression( reconstructedExpression );
+                if( parenthesized ) {
+                    reconstructedExpression.insert( 0, 1, '(' );
+                    reconstructedExpression.append( 1, ')' );
+                }
+                if( negated ) {
+                    reconstructedExpression.insert( 0, 1, '!' );
+                }
+                decomposedExpression = CATCH_NULL;
+            }
+            return reconstructedExpression;
+        }
 
-        std::string reconstructedExpression;
+        mutable DecomposedExpression const* decomposedExpression;
+        mutable std::string reconstructedExpression;
         std::string message;
         ResultWas::OfType resultType;
+        bool negated;
+        bool parenthesized;
     };
 
     class AssertionResult {
@@ -879,6 +991,8 @@ namespace Catch {
         std::string getMessage() const;
         SourceLineInfo getSourceInfo() const;
         std::string getTestMacroName() const;
+        void discardDecomposedExpression() const;
+        void expandDecomposedExpression() const;
 
     protected:
         AssertionInfo m_info;
@@ -894,313 +1008,153 @@ namespace Catch {
 namespace Matchers {
     namespace Impl {
 
-    namespace Generic {
-        template<typename ExpressionT> class AllOf;
-        template<typename ExpressionT> class AnyOf;
-        template<typename ExpressionT> class Not;
-    }
-
-    template<typename ExpressionT>
-    struct Matcher : SharedImpl<IShared>
-    {
-        typedef ExpressionT ExpressionType;
-
-        virtual ~Matcher() {}
-        virtual Ptr<Matcher> clone() const = 0;
-        virtual bool match( ExpressionT const& expr ) const = 0;
-        virtual std::string toString() const = 0;
+        template<typename ArgT> struct MatchAllOf;
+        template<typename ArgT> struct MatchAnyOf;
+        template<typename ArgT> struct MatchNotOf;
 
-        Generic::AllOf<ExpressionT> operator && ( Matcher<ExpressionT> const& other ) const;
-        Generic::AnyOf<ExpressionT> operator || ( Matcher<ExpressionT> const& other ) const;
-        Generic::Not<ExpressionT> operator ! () const;
-    };
-
-    template<typename DerivedT, typename ExpressionT>
-    struct MatcherImpl : Matcher<ExpressionT> {
-
-        virtual Ptr<Matcher<ExpressionT> > clone() const {
-            return Ptr<Matcher<ExpressionT> >( new DerivedT( static_cast<DerivedT const&>( *this ) ) );
-        }
-    };
-
-    namespace Generic {
-        template<typename ExpressionT>
-        class Not : public MatcherImpl<Not<ExpressionT>, ExpressionT> {
+        class MatcherUntypedBase {
         public:
-            explicit Not( Matcher<ExpressionT> const& matcher ) : m_matcher(matcher.clone()) {}
-            Not( Not const& other ) : m_matcher( other.m_matcher ) {}
-
-            virtual bool match( ExpressionT const& expr ) const CATCH_OVERRIDE {
-                return !m_matcher->match( expr );
+            std::string toString() const {
+                if( m_cachedToString.empty() )
+                    m_cachedToString = describe();
+                return m_cachedToString;
             }
 
-            virtual std::string toString() const CATCH_OVERRIDE {
-                return "not " + m_matcher->toString();
-            }
+        protected:
+            virtual std::string describe() const = 0;
+            mutable std::string m_cachedToString;
         private:
-            Ptr< Matcher<ExpressionT> > m_matcher;
+            MatcherUntypedBase& operator = ( MatcherUntypedBase const& );
         };
 
-        template<typename ExpressionT>
-        class AllOf : public MatcherImpl<AllOf<ExpressionT>, ExpressionT> {
-        public:
+        template<typename ObjectT, typename ComparatorT = ObjectT>
+        struct MatcherBase : MatcherUntypedBase {
 
-            AllOf() {}
-            AllOf( AllOf const& other ) : m_matchers( other.m_matchers ) {}
+            virtual bool match( ObjectT const& arg ) const = 0;
 
-            AllOf& add( Matcher<ExpressionT> const& matcher ) {
-                m_matchers.push_back( matcher.clone() );
-                return *this;
-            }
-            virtual bool match( ExpressionT const& expr ) const
-            {
-                for( std::size_t i = 0; i < m_matchers.size(); ++i )
-                    if( !m_matchers[i]->match( expr ) )
+            MatchAllOf<ComparatorT> operator && ( MatcherBase const& other ) const;
+            MatchAnyOf<ComparatorT> operator || ( MatcherBase const& other ) const;
+            MatchNotOf<ComparatorT> operator ! () const;
+        };
+
+        template<typename ArgT>
+        struct MatchAllOf : MatcherBase<ArgT> {
+            virtual bool match( ArgT const& arg ) const CATCH_OVERRIDE {
+                for( std::size_t i = 0; i < m_matchers.size(); ++i ) {
+                    if (!m_matchers[i]->match(arg))
                         return false;
+                }
                 return true;
             }
-            virtual std::string toString() const {
-                std::ostringstream oss;
-                oss << "( ";
+            virtual std::string describe() const CATCH_OVERRIDE {
+                std::string description;
+                description.reserve( 4 + m_matchers.size()*32 );
+                description += "( ";
                 for( std::size_t i = 0; i < m_matchers.size(); ++i ) {
                     if( i != 0 )
-                        oss << " and ";
-                    oss << m_matchers[i]->toString();
+                        description += " and ";
+                    description += m_matchers[i]->toString();
                 }
-                oss << " )";
-                return oss.str();
+                description += " )";
+                return description;
             }
 
-            AllOf operator && ( Matcher<ExpressionT> const& other ) const {
-                AllOf allOfExpr( *this );
-                allOfExpr.add( other );
-                return allOfExpr;
+            MatchAllOf<ArgT>& operator && ( MatcherBase<ArgT> const& other ) {
+                m_matchers.push_back( &other );
+                return *this;
             }
 
-        private:
-            std::vector<Ptr<Matcher<ExpressionT> > > m_matchers;
+            std::vector<MatcherBase<ArgT> const*> m_matchers;
         };
+        template<typename ArgT>
+        struct MatchAnyOf : MatcherBase<ArgT> {
 
-        template<typename ExpressionT>
-        class AnyOf : public MatcherImpl<AnyOf<ExpressionT>, ExpressionT> {
-        public:
-
-            AnyOf() {}
-            AnyOf( AnyOf const& other ) : m_matchers( other.m_matchers ) {}
-
-            AnyOf& add( Matcher<ExpressionT> const& matcher ) {
-                m_matchers.push_back( matcher.clone() );
-                return *this;
-            }
-            virtual bool match( ExpressionT const& expr ) const
-            {
-                for( std::size_t i = 0; i < m_matchers.size(); ++i )
-                    if( m_matchers[i]->match( expr ) )
+            virtual bool match( ArgT const& arg ) const CATCH_OVERRIDE {
+                for( std::size_t i = 0; i < m_matchers.size(); ++i ) {
+                    if (m_matchers[i]->match(arg))
                         return true;
+                }
                 return false;
             }
-            virtual std::string toString() const {
-                std::ostringstream oss;
-                oss << "( ";
+            virtual std::string describe() const CATCH_OVERRIDE {
+                std::string description;
+                description.reserve( 4 + m_matchers.size()*32 );
+                description += "( ";
                 for( std::size_t i = 0; i < m_matchers.size(); ++i ) {
                     if( i != 0 )
-                        oss << " or ";
-                    oss << m_matchers[i]->toString();
+                        description += " or ";
+                    description += m_matchers[i]->toString();
                 }
-                oss << " )";
-                return oss.str();
+                description += " )";
+                return description;
             }
 
-            AnyOf operator || ( Matcher<ExpressionT> const& other ) const {
-                AnyOf anyOfExpr( *this );
-                anyOfExpr.add( other );
-                return anyOfExpr;
-            }
-
-        private:
-            std::vector<Ptr<Matcher<ExpressionT> > > m_matchers;
-        };
-
-    } // namespace Generic
-
-    template<typename ExpressionT>
-    Generic::AllOf<ExpressionT> Matcher<ExpressionT>::operator && ( Matcher<ExpressionT> const& other ) const {
-        Generic::AllOf<ExpressionT> allOfExpr;
-        allOfExpr.add( *this );
-        allOfExpr.add( other );
-        return allOfExpr;
-    }
-
-    template<typename ExpressionT>
-    Generic::AnyOf<ExpressionT> Matcher<ExpressionT>::operator || ( Matcher<ExpressionT> const& other ) const {
-        Generic::AnyOf<ExpressionT> anyOfExpr;
-        anyOfExpr.add( *this );
-        anyOfExpr.add( other );
-        return anyOfExpr;
-    }
-
-    template<typename ExpressionT>
-    Generic::Not<ExpressionT> Matcher<ExpressionT>::operator ! () const {
-        return Generic::Not<ExpressionT>( *this );
-    }
-
-    namespace StdString {
-
-        inline std::string makeString( std::string const& str ) { return str; }
-        inline std::string makeString( const char* str ) { return str ? std::string( str ) : std::string(); }
-
-        struct CasedString
-        {
-            CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
-            :   m_caseSensitivity( caseSensitivity ),
-                m_str( adjustString( str ) )
-            {}
-            std::string adjustString( std::string const& str ) const {
-                return m_caseSensitivity == CaseSensitive::No
-                    ? toLower( str )
-                    : str;
-
-            }
-            std::string toStringSuffix() const
-            {
-                return m_caseSensitivity == CaseSensitive::No
-                    ? " (case insensitive)"
-                    : "";
-            }
-            CaseSensitive::Choice m_caseSensitivity;
-            std::string m_str;
-        };
-
-        struct Equals : MatcherImpl<Equals, std::string> {
-            Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes )
-            :   m_data( str, caseSensitivity )
-            {}
-            Equals( Equals const& other ) : m_data( other.m_data ){}
-
-            virtual ~Equals();
-
-            virtual bool match( std::string const& expr ) const {
-                return m_data.m_str == m_data.adjustString( expr );;
-            }
-            virtual std::string toString() const {
-                return "equals: \"" + m_data.m_str + "\"" + m_data.toStringSuffix();
+            MatchAnyOf<ArgT>& operator || ( MatcherBase<ArgT> const& other ) {
+                m_matchers.push_back( &other );
+                return *this;
             }
 
-            CasedString m_data;
+            std::vector<MatcherBase<ArgT> const*> m_matchers;
         };
 
-        struct Contains : MatcherImpl<Contains, std::string> {
-            Contains( std::string const& substr, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes )
-            : m_data( substr, caseSensitivity ){}
-            Contains( Contains const& other ) : m_data( other.m_data ){}
+        template<typename ArgT>
+        struct MatchNotOf : MatcherBase<ArgT> {
 
-            virtual ~Contains();
+            MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
 
-            virtual bool match( std::string const& expr ) const {
-                return m_data.adjustString( expr ).find( m_data.m_str ) != std::string::npos;
-            }
-            virtual std::string toString() const {
-                return "contains: \"" + m_data.m_str  + "\"" + m_data.toStringSuffix();
+            virtual bool match( ArgT const& arg ) const CATCH_OVERRIDE {
+                return !m_underlyingMatcher.match( arg );
             }
 
-            CasedString m_data;
-        };
-
-        struct StartsWith : MatcherImpl<StartsWith, std::string> {
-            StartsWith( std::string const& substr, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes )
-            : m_data( substr, caseSensitivity ){}
-
-            StartsWith( StartsWith const& other ) : m_data( other.m_data ){}
-
-            virtual ~StartsWith();
-
-            virtual bool match( std::string const& expr ) const {
-                return startsWith( m_data.adjustString( expr ), m_data.m_str );
-            }
-            virtual std::string toString() const {
-                return "starts with: \"" + m_data.m_str + "\"" + m_data.toStringSuffix();
+            virtual std::string describe() const CATCH_OVERRIDE {
+                return "not " + m_underlyingMatcher.toString();
             }
-
-            CasedString m_data;
+            MatcherBase<ArgT> const& m_underlyingMatcher;
         };
 
-        struct EndsWith : MatcherImpl<EndsWith, std::string> {
-            EndsWith( std::string const& substr, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes )
-            : m_data( substr, caseSensitivity ){}
-            EndsWith( EndsWith const& other ) : m_data( other.m_data ){}
-
-            virtual ~EndsWith();
-
-            virtual bool match( std::string const& expr ) const {
-                return endsWith( m_data.adjustString( expr ), m_data.m_str );
-            }
-            virtual std::string toString() const {
-                return "ends with: \"" + m_data.m_str + "\"" + m_data.toStringSuffix();
-            }
+        template<typename ObjectT, typename ComparatorT>
+        MatchAllOf<ComparatorT> MatcherBase<ObjectT, ComparatorT>::operator && ( MatcherBase const& other ) const {
+            return MatchAllOf<ComparatorT>() && *this && other;
+        }
+        template<typename ObjectT, typename ComparatorT>
+        MatchAnyOf<ComparatorT> MatcherBase<ObjectT, ComparatorT>::operator || ( MatcherBase const& other ) const {
+            return MatchAnyOf<ComparatorT>() || *this || other;
+        }
+        template<typename ObjectT, typename ComparatorT>
+        MatchNotOf<ComparatorT> MatcherBase<ObjectT, ComparatorT>::operator ! () const {
+            return MatchNotOf<ComparatorT>( *this );
+        }
 
-            CasedString m_data;
-        };
-    } // namespace StdString
     } // namespace Impl
 
     // The following functions create the actual matcher objects.
     // This allows the types to be inferred
-    template<typename ExpressionT>
-    inline Impl::Generic::Not<ExpressionT> Not( Impl::Matcher<ExpressionT> const& m ) {
-        return Impl::Generic::Not<ExpressionT>( m );
-    }
-
-    template<typename ExpressionT>
-    inline Impl::Generic::AllOf<ExpressionT> AllOf( Impl::Matcher<ExpressionT> const& m1,
-                                                    Impl::Matcher<ExpressionT> const& m2 ) {
-        return Impl::Generic::AllOf<ExpressionT>().add( m1 ).add( m2 );
-    }
-    template<typename ExpressionT>
-    inline Impl::Generic::AllOf<ExpressionT> AllOf( Impl::Matcher<ExpressionT> const& m1,
-                                                    Impl::Matcher<ExpressionT> const& m2,
-                                                    Impl::Matcher<ExpressionT> const& m3 ) {
-        return Impl::Generic::AllOf<ExpressionT>().add( m1 ).add( m2 ).add( m3 );
-    }
-    template<typename ExpressionT>
-    inline Impl::Generic::AnyOf<ExpressionT> AnyOf( Impl::Matcher<ExpressionT> const& m1,
-                                                    Impl::Matcher<ExpressionT> const& m2 ) {
-        return Impl::Generic::AnyOf<ExpressionT>().add( m1 ).add( m2 );
-    }
-    template<typename ExpressionT>
-    inline Impl::Generic::AnyOf<ExpressionT> AnyOf( Impl::Matcher<ExpressionT> const& m1,
-                                                    Impl::Matcher<ExpressionT> const& m2,
-                                                    Impl::Matcher<ExpressionT> const& m3 ) {
-        return Impl::Generic::AnyOf<ExpressionT>().add( m1 ).add( m2 ).add( m3 );
-    }
-
-    inline Impl::StdString::Equals      Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) {
-        return Impl::StdString::Equals( str, caseSensitivity );
-    }
-    inline Impl::StdString::Equals      Equals( const char* str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) {
-        return Impl::StdString::Equals( Impl::StdString::makeString( str ), caseSensitivity );
-    }
-    inline Impl::StdString::Contains    Contains( std::string const& substr, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) {
-        return Impl::StdString::Contains( substr, caseSensitivity );
-    }
-    inline Impl::StdString::Contains    Contains( const char* substr, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) {
-        return Impl::StdString::Contains( Impl::StdString::makeString( substr ), caseSensitivity );
+    // - deprecated: prefer ||, && and !
+    template<typename T>
+    inline Impl::MatchNotOf<T> Not( Impl::MatcherBase<T> const& underlyingMatcher ) {
+        return Impl::MatchNotOf<T>( underlyingMatcher );
     }
-    inline Impl::StdString::StartsWith  StartsWith( std::string const& substr ) {
-        return Impl::StdString::StartsWith( substr );
+    template<typename T>
+    inline Impl::MatchAllOf<T> AllOf( Impl::MatcherBase<T> const& m1, Impl::MatcherBase<T> const& m2 ) {
+        return Impl::MatchAllOf<T>() && m1 && m2;
     }
-    inline Impl::StdString::StartsWith  StartsWith( const char* substr ) {
-        return Impl::StdString::StartsWith( Impl::StdString::makeString( substr ) );
+    template<typename T>
+    inline Impl::MatchAllOf<T> AllOf( Impl::MatcherBase<T> const& m1, Impl::MatcherBase<T> const& m2, Impl::MatcherBase<T> const& m3 ) {
+        return Impl::MatchAllOf<T>() && m1 && m2 && m3;
     }
-    inline Impl::StdString::EndsWith    EndsWith( std::string const& substr ) {
-        return Impl::StdString::EndsWith( substr );
+    template<typename T>
+    inline Impl::MatchAnyOf<T> AnyOf( Impl::MatcherBase<T> const& m1, Impl::MatcherBase<T> const& m2 ) {
+        return Impl::MatchAnyOf<T>() || m1 || m2;
     }
-    inline Impl::StdString::EndsWith    EndsWith( const char* substr ) {
-        return Impl::StdString::EndsWith( Impl::StdString::makeString( substr ) );
+    template<typename T>
+    inline Impl::MatchAnyOf<T> AnyOf( Impl::MatcherBase<T> const& m1, Impl::MatcherBase<T> const& m2, Impl::MatcherBase<T> const& m3 ) {
+        return Impl::MatchAnyOf<T>() || m1 || m2 || m3;
     }
 
 } // namespace Matchers
 
 using namespace Matchers;
+using Matchers::Impl::MatcherBase;
 
 } // namespace Catch
 
@@ -1210,22 +1164,20 @@ namespace Catch {
 
     template<typename T> class ExpressionLhs;
 
-    struct STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison;
-
     struct CopyableStream {
         CopyableStream() {}
         CopyableStream( CopyableStream const& other ) {
             oss << other.oss.str();
         }
         CopyableStream& operator=( CopyableStream const& other ) {
-            oss.str("");
+            oss.str(std::string());
             oss << other.oss.str();
             return *this;
         }
         std::ostringstream oss;
     };
 
-    class ResultBuilder {
+    class ResultBuilder : public DecomposedExpression {
     public:
         ResultBuilder(  char const* macroName,
                         SourceLineInfo const& lineInfo,
@@ -1243,38 +1195,32 @@ namespace Catch {
             return *this;
         }
 
-        template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator && ( RhsT const& );
-        template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator || ( RhsT const& );
-
         ResultBuilder& setResultType( ResultWas::OfType result );
         ResultBuilder& setResultType( bool result );
-        ResultBuilder& setLhs( std::string const& lhs );
-        ResultBuilder& setRhs( std::string const& rhs );
-        ResultBuilder& setOp( std::string const& op );
 
-        void endExpression();
+        void endExpression( DecomposedExpression const& expr );
+
+        virtual void reconstructExpression( std::string& dest ) const CATCH_OVERRIDE;
 
-        std::string reconstructExpression() const;
         AssertionResult build() const;
+        AssertionResult build( DecomposedExpression const& expr ) const;
 
         void useActiveException( ResultDisposition::Flags resultDisposition = ResultDisposition::Normal );
         void captureResult( ResultWas::OfType resultType );
         void captureExpression();
         void captureExpectedException( std::string const& expectedMessage );
-        void captureExpectedException( Matchers::Impl::Matcher<std::string> const& matcher );
+        void captureExpectedException( Matchers::Impl::MatcherBase<std::string> const& matcher );
         void handleResult( AssertionResult const& result );
         void react();
         bool shouldDebugBreak() const;
         bool allowThrows() const;
 
+        template<typename ArgT, typename MatcherT>
+        void captureMatch( ArgT const& arg, MatcherT const& matcher, char const* matcherString );
+
     private:
         AssertionInfo m_assertionInfo;
         AssertionResultData m_data;
-        struct ExprComponents {
-            ExprComponents() : testFalse( false ) {}
-            bool testFalse;
-            std::string lhs, rhs, op;
-        } m_exprComponents;
         CopyableStream m_stream;
 
         bool m_shouldDebugBreak;
@@ -1293,6 +1239,7 @@ namespace Catch {
 #ifdef _MSC_VER
 #pragma warning(push)
 #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
+#pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
 #endif
 
 #include <cstddef>
@@ -1796,90 +1743,159 @@ std::string toString( T const& value ) {
 
 namespace Catch {
 
-// Wraps the LHS of an expression and captures the operator and RHS (if any) -
-// wrapping them all in a ResultBuilder object
-template<typename T>
-class ExpressionLhs {
-    ExpressionLhs& operator = ( ExpressionLhs const& );
-#  ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
-    ExpressionLhs& operator = ( ExpressionLhs && ) = delete;
-#  endif
+template<typename LhsT, Internal::Operator Op, typename RhsT>
+class BinaryExpression;
 
+template<typename ArgT, typename MatcherT>
+class MatchExpression;
+
+// Wraps the LHS of an expression and overloads comparison operators
+// for also capturing those and RHS (if any)
+template<typename T>
+class ExpressionLhs : public DecomposedExpression {
 public:
-    ExpressionLhs( ResultBuilder& rb, T lhs ) : m_rb( rb ), m_lhs( lhs ) {}
-#  ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
-    ExpressionLhs( ExpressionLhs const& ) = default;
-    ExpressionLhs( ExpressionLhs && )     = default;
-#  endif
+    ExpressionLhs( ResultBuilder& rb, T lhs ) : m_rb( rb ), m_lhs( lhs ), m_truthy(false) {}
+
+    ExpressionLhs& operator = ( const ExpressionLhs& );
 
     template<typename RhsT>
-    ResultBuilder& operator == ( RhsT const& rhs ) {
+    BinaryExpression<T, Internal::IsEqualTo, RhsT const&>
+    operator == ( RhsT const& rhs ) {
         return captureExpression<Internal::IsEqualTo>( rhs );
     }
 
     template<typename RhsT>
-    ResultBuilder& operator != ( RhsT const& rhs ) {
+    BinaryExpression<T, Internal::IsNotEqualTo, RhsT const&>
+    operator != ( RhsT const& rhs ) {
         return captureExpression<Internal::IsNotEqualTo>( rhs );
     }
 
     template<typename RhsT>
-    ResultBuilder& operator < ( RhsT const& rhs ) {
+    BinaryExpression<T, Internal::IsLessThan, RhsT const&>
+    operator < ( RhsT const& rhs ) {
         return captureExpression<Internal::IsLessThan>( rhs );
     }
 
     template<typename RhsT>
-    ResultBuilder& operator > ( RhsT const& rhs ) {
+    BinaryExpression<T, Internal::IsGreaterThan, RhsT const&>
+    operator > ( RhsT const& rhs ) {
         return captureExpression<Internal::IsGreaterThan>( rhs );
     }
 
     template<typename RhsT>
-    ResultBuilder& operator <= ( RhsT const& rhs ) {
+    BinaryExpression<T, Internal::IsLessThanOrEqualTo, RhsT const&>
+    operator <= ( RhsT const& rhs ) {
         return captureExpression<Internal::IsLessThanOrEqualTo>( rhs );
     }
 
     template<typename RhsT>
-    ResultBuilder& operator >= ( RhsT const& rhs ) {
+    BinaryExpression<T, Internal::IsGreaterThanOrEqualTo, RhsT const&>
+    operator >= ( RhsT const& rhs ) {
         return captureExpression<Internal::IsGreaterThanOrEqualTo>( rhs );
     }
 
-    ResultBuilder& operator == ( bool rhs ) {
+    BinaryExpression<T, Internal::IsEqualTo, bool> operator == ( bool rhs ) {
         return captureExpression<Internal::IsEqualTo>( rhs );
     }
 
-    ResultBuilder& operator != ( bool rhs ) {
+    BinaryExpression<T, Internal::IsNotEqualTo, bool> operator != ( bool rhs ) {
         return captureExpression<Internal::IsNotEqualTo>( rhs );
     }
 
     void endExpression() {
-        bool value = m_lhs ? true : false;
+        m_truthy = m_lhs ? true : false;
         m_rb
-            .setLhs( Catch::toString( value ) )
-            .setResultType( value )
-            .endExpression();
+            .setResultType( m_truthy )
+            .endExpression( *this );
     }
 
-    // Only simple binary expressions are allowed on the LHS.
-    // If more complex compositions are required then place the sub expression in parentheses
-    template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator + ( RhsT const& );
-    template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator - ( RhsT const& );
-    template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator / ( RhsT const& );
-    template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator * ( RhsT const& );
-    template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator && ( RhsT const& );
-    template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator || ( RhsT const& );
+    virtual void reconstructExpression( std::string& dest ) const CATCH_OVERRIDE {
+        dest = Catch::toString( m_truthy );
+    }
 
 private:
     template<Internal::Operator Op, typename RhsT>
-    ResultBuilder& captureExpression( RhsT const& rhs ) {
-        return m_rb
-            .setResultType( Internal::compare<Op>( m_lhs, rhs ) )
-            .setLhs( Catch::toString( m_lhs ) )
-            .setRhs( Catch::toString( rhs ) )
-            .setOp( Internal::OperatorTraits<Op>::getName() );
+    BinaryExpression<T, Op, RhsT&> captureExpression( RhsT& rhs ) const {
+        return BinaryExpression<T, Op, RhsT&>( m_rb, m_lhs, rhs );
+    }
+
+    template<Internal::Operator Op>
+    BinaryExpression<T, Op, bool> captureExpression( bool rhs ) const {
+        return BinaryExpression<T, Op, bool>( m_rb, m_lhs, rhs );
     }
 
 private:
     ResultBuilder& m_rb;
     T m_lhs;
+    bool m_truthy;
+};
+
+template<typename LhsT, Internal::Operator Op, typename RhsT>
+class BinaryExpression : public DecomposedExpression {
+public:
+    BinaryExpression( ResultBuilder& rb, LhsT lhs, RhsT rhs )
+        : m_rb( rb ), m_lhs( lhs ), m_rhs( rhs ) {}
+
+    BinaryExpression& operator = ( BinaryExpression& );
+
+    void endExpression() const {
+        m_rb
+            .setResultType( Internal::compare<Op>( m_lhs, m_rhs ) )
+            .endExpression( *this );
+    }
+
+    virtual bool isBinaryExpression() const CATCH_OVERRIDE {
+        return true;
+    }
+
+    virtual void reconstructExpression( std::string& dest ) const CATCH_OVERRIDE {
+        std::string lhs = Catch::toString( m_lhs );
+        std::string rhs = Catch::toString( m_rhs );
+        char delim = lhs.size() + rhs.size() < 40 &&
+                     lhs.find('\n') == std::string::npos &&
+                     rhs.find('\n') == std::string::npos ? ' ' : '\n';
+        dest.reserve( 7 + lhs.size() + rhs.size() );
+                   // 2 for spaces around operator
+                   // 2 for operator
+                   // 2 for parentheses (conditionally added later)
+                   // 1 for negation (conditionally added later)
+        dest = lhs;
+        dest += delim;
+        dest += Internal::OperatorTraits<Op>::getName();
+        dest += delim;
+        dest += rhs;
+    }
+
+private:
+    ResultBuilder& m_rb;
+    LhsT m_lhs;
+    RhsT m_rhs;
+};
+
+template<typename ArgT, typename MatcherT>
+class MatchExpression : public DecomposedExpression {
+public:
+    MatchExpression( ArgT arg, MatcherT matcher, char const* matcherString )
+        : m_arg( arg ), m_matcher( matcher ), m_matcherString( matcherString ) {}
+
+    virtual bool isBinaryExpression() const CATCH_OVERRIDE {
+        return true;
+    }
+
+    virtual void reconstructExpression( std::string& dest ) const CATCH_OVERRIDE {
+        std::string matcherAsString = m_matcher.toString();
+        dest = Catch::toString( m_arg );
+        dest += ' ';
+        if( matcherAsString == Detail::unprintableString )
+            dest += m_matcherString;
+        else
+            dest += matcherAsString;
+    }
+
+private:
+    ArgT m_arg;
+    MatcherT m_matcher;
+    char const* m_matcherString;
 };
 
 } // end namespace Catch
@@ -1896,6 +1912,14 @@ namespace Catch {
         return ExpressionLhs<bool>( *this, value );
     }
 
+    template<typename ArgT, typename MatcherT>
+    inline void ResultBuilder::captureMatch( ArgT const& arg, MatcherT const& matcher,
+                                             char const* matcherString ) {
+        MatchExpression<ArgT const&, MatcherT const&> expr( arg, matcher, matcherString );
+        setResultType( matcher.match( arg ) );
+        endExpression( expr );
+    }
+
 } // namespace Catch
 
 // #included from: catch_message.h
@@ -1998,11 +2022,19 @@ namespace Catch {
 #define TWOBLUECUBES_CATCH_PLATFORM_H_INCLUDED
 
 #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
-#define CATCH_PLATFORM_MAC
+#  define CATCH_PLATFORM_MAC
 #elif  defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
-#define CATCH_PLATFORM_IPHONE
+#  define CATCH_PLATFORM_IPHONE
+#elif defined(linux) || defined(__linux) || defined(__linux__)
+#  define CATCH_PLATFORM_LINUX
 #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER)
-#define CATCH_PLATFORM_WINDOWS
+#  define CATCH_PLATFORM_WINDOWS
+#  if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
+#    define CATCH_DEFINES_NOMINMAX
+#  endif
+#  if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
+#    define CATCH_DEFINES_WIN32_LEAN_AND_MEAN
+#  endif
 #endif
 
 #include <string>
@@ -2017,27 +2049,36 @@ namespace Catch{
 
     // The following code snippet based on:
     // http://cocoawithlove.com/2008/03/break-into-debugger.html
-    #ifdef DEBUG
-        #if defined(__ppc64__) || defined(__ppc__)
-            #define CATCH_BREAK_INTO_DEBUGGER() \
-                if( Catch::isDebuggerActive() ) { \
-                    __asm__("li r0, 20\nsc\nnop\nli r0, 37\nli r4, 2\nsc\nnop\n" \
-                    : : : "memory","r0","r3","r4" ); \
-                }
-        #else
-            #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) {__asm__("int $3\n" : : );}
-        #endif
+    #if defined(__ppc64__) || defined(__ppc__)
+        #define CATCH_TRAP() \
+                __asm__("li r0, 20\nsc\nnop\nli r0, 37\nli r4, 2\nsc\nnop\n" \
+                : : : "memory","r0","r3","r4" )
+    #else
+        #define CATCH_TRAP() __asm__("int $3\n" : : )
     #endif
 
+#elif defined(CATCH_PLATFORM_LINUX)
+    // If we can use inline assembler, do it because this allows us to break
+    // directly at the location of the failing check instead of breaking inside
+    // raise() called from it, i.e. one stack frame below.
+    #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
+        #define CATCH_TRAP() asm volatile ("int $3")
+    #else // Fall back to the generic way.
+        #include <signal.h>
+
+        #define CATCH_TRAP() raise(SIGTRAP)
+    #endif
 #elif defined(_MSC_VER)
-    #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { __debugbreak(); }
+    #define CATCH_TRAP() __debugbreak()
 #elif defined(__MINGW32__)
     extern "C" __declspec(dllimport) void __stdcall DebugBreak();
-    #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { DebugBreak(); }
+    #define CATCH_TRAP() DebugBreak()
 #endif
 
-#ifndef CATCH_BREAK_INTO_DEBUGGER
-#define CATCH_BREAK_INTO_DEBUGGER() Catch::alwaysTrue();
+#ifdef CATCH_TRAP
+    #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { CATCH_TRAP(); }
+#else
+    #define CATCH_BREAK_INTO_DEBUGGER() Catch::alwaysTrue();
 #endif
 
 // #included from: catch_interfaces_runner.h
@@ -2052,6 +2093,53 @@ namespace Catch {
     };
 }
 
+// #included from: catch_type_traits.hpp
+#define TWOBLUECUBES_CATCH_TYPE_TRAITS_HPP_INCLUDED
+
+#if defined(CATCH_CONFIG_CPP11_TYPE_TRAITS)
+#include <type_traits>
+#endif
+
+namespace Catch {
+
+#if defined(CATCH_CONFIG_CPP11_TYPE_TRAITS)
+
+     template <typename T>
+     using add_lvalue_reference = std::add_lvalue_reference<T>;
+
+     template <typename T>
+     using add_const = std::add_const<T>;
+
+#else
+
+    template <typename T>
+    struct add_const {
+        typedef const T type;
+    };
+
+    template <typename T>
+    struct add_lvalue_reference {
+        typedef T& type;
+    };
+    template <typename T>
+    struct add_lvalue_reference<T&> {
+        typedef T& type;
+    };
+    // No && overload, because that is C++11, in which case we have
+    // proper type_traits implementation from the standard library
+
+#endif
+
+}
+
+#if defined(CATCH_CONFIG_FAST_COMPILE)
+///////////////////////////////////////////////////////////////////////////////
+// We can speedup compilation significantly by breaking into debugger lower in
+// the callstack, because then we don't have to expand CATCH_BREAK_INTO_DEBUGGER
+// macro in each assertion
+#define INTERNAL_CATCH_REACT( resultBuilder ) \
+    resultBuilder.react();
+#else
 ///////////////////////////////////////////////////////////////////////////////
 // In the event of a failure works out if the debugger needs to be invoked
 // and/or an exception thrown and takes appropriate action.
@@ -2060,6 +2148,7 @@ namespace Catch {
 #define INTERNAL_CATCH_REACT( resultBuilder ) \
     if( resultBuilder.shouldDebugBreak() ) CATCH_BREAK_INTO_DEBUGGER(); \
     resultBuilder.react();
+#endif
 
 ///////////////////////////////////////////////////////////////////////////////
 #define INTERNAL_CATCH_TEST( expr, resultDisposition, macroName ) \
@@ -2068,12 +2157,14 @@ namespace Catch {
         try { \
             CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
             ( __catchResult <= expr ).endExpression(); \
+            CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
         } \
         catch( ... ) { \
-            __catchResult.useActiveException( Catch::ResultDisposition::Normal ); \
+            __catchResult.useActiveException( resultDisposition ); \
         } \
         INTERNAL_CATCH_REACT( __catchResult ) \
-    } while( Catch::isTrue( false && !!(expr) ) ) // expr here is never evaluated at runtime but it forces the compiler to give it a look
+    } while( Catch::isTrue( false && static_cast<bool>( !!(expr) ) ) ) // expr here is never evaluated at runtime but it forces the compiler to give it a look
+    // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
 
 ///////////////////////////////////////////////////////////////////////////////
 #define INTERNAL_CATCH_IF( expr, resultDisposition, macroName ) \
@@ -2090,7 +2181,7 @@ namespace Catch {
     do { \
         Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \
         try { \
-            expr; \
+            static_cast<void>(expr); \
             __catchResult.captureResult( Catch::ResultWas::Ok ); \
         } \
         catch( ... ) { \
@@ -2105,7 +2196,7 @@ namespace Catch {
         Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition, #matcher ); \
         if( __catchResult.allowThrows() ) \
             try { \
-                expr; \
+                static_cast<void>(expr); \
                 __catchResult.captureResult( Catch::ResultWas::DidntThrowException ); \
             } \
             catch( ... ) { \
@@ -2119,13 +2210,13 @@ namespace Catch {
 ///////////////////////////////////////////////////////////////////////////////
 #define INTERNAL_CATCH_THROWS_AS( expr, exceptionType, resultDisposition, macroName ) \
     do { \
-        Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \
+        Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr ", " #exceptionType, resultDisposition ); \
         if( __catchResult.allowThrows() ) \
             try { \
-                expr; \
+                static_cast<void>(expr); \
                 __catchResult.captureResult( Catch::ResultWas::DidntThrowException ); \
             } \
-            catch( exceptionType ) { \
+            catch( Catch::add_const<Catch::add_lvalue_reference<exceptionType>::type>::type ) { \
                 __catchResult.captureResult( Catch::ResultWas::Ok ); \
             } \
             catch( ... ) { \
@@ -2164,13 +2255,7 @@ namespace Catch {
     do { \
         Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #arg ", " #matcher, resultDisposition ); \
         try { \
-            std::string matcherAsString = (matcher).toString(); \
-            __catchResult \
-                .setLhs( Catch::toString( arg ) ) \
-                .setRhs( matcherAsString == Catch::Detail::unprintableString ? #matcher : matcherAsString ) \
-                .setOp( "matches" ) \
-                .setResultType( (matcher).match( arg ) ); \
-            __catchResult.captureExpression(); \
+            __catchResult.captureMatch( arg, matcher, #matcher ); \
         } catch( ... ) { \
             __catchResult.useActiveException( resultDisposition | Catch::ResultDisposition::ContinueOnFailure ); \
         } \
@@ -2253,6 +2338,8 @@ namespace Catch {
     };
 }
 
+#include <string>
+
 namespace Catch {
 
     struct SectionInfo {
@@ -2623,6 +2710,10 @@ namespace Catch {
 #include <cmath>
 #include <limits>
 
+#if defined(CATCH_CONFIG_CPP11_TYPE_TRAITS)
+#include <type_traits>
+#endif
+
 namespace Catch {
 namespace Detail {
 
@@ -2630,12 +2721,14 @@ namespace Detail {
     public:
         explicit Approx ( double value )
         :   m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
+            m_margin( 0.0 ),
             m_scale( 1.0 ),
             m_value( value )
         {}
 
         Approx( Approx const& other )
         :   m_epsilon( other.m_epsilon ),
+            m_margin( other.m_margin ),
             m_scale( other.m_scale ),
             m_value( other.m_value )
         {}
@@ -2647,13 +2740,69 @@ namespace Detail {
         Approx operator()( double value ) {
             Approx approx( value );
             approx.epsilon( m_epsilon );
+            approx.margin( m_margin );
             approx.scale( m_scale );
             return approx;
         }
 
+#if defined(CATCH_CONFIG_CPP11_TYPE_TRAITS)
+        template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
+        friend bool operator == ( const T& lhs, Approx const& rhs ) {
+            // Thanks to Richard Harris for his help refining this formula
+            auto lhs_v = double(lhs);
+            bool relativeOK = std::fabs(lhs_v - rhs.m_value) < rhs.m_epsilon * (rhs.m_scale + (std::max)(std::fabs(lhs_v), std::fabs(rhs.m_value)));
+            if (relativeOK) {
+                return true;
+            }
+            return std::fabs(lhs_v - rhs.m_value) < rhs.m_margin;
+        }
+
+        template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
+        friend bool operator == ( Approx const& lhs, const T& rhs ) {
+            return operator==( rhs, lhs );
+        }
+
+        template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
+        friend bool operator != ( T lhs, Approx const& rhs ) {
+            return !operator==( lhs, rhs );
+        }
+
+        template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
+        friend bool operator != ( Approx const& lhs, T rhs ) {
+            return !operator==( rhs, lhs );
+        }
+
+        template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
+        friend bool operator <= ( T lhs, Approx const& rhs )
+        {
+          return double(lhs) < rhs.m_value || lhs == rhs;
+        }
+
+        template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
+        friend bool operator <= ( Approx const& lhs, T rhs )
+        {
+          return lhs.m_value < double(rhs) || lhs == rhs;
+        }
+
+        template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
+        friend bool operator >= ( T lhs, Approx const& rhs )
+        {
+          return double(lhs) > rhs.m_value || lhs == rhs;
+        }
+
+        template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
+        friend bool operator >= ( Approx const& lhs, T rhs )
+        {
+          return lhs.m_value > double(rhs) || lhs == rhs;
+        }
+#else
         friend bool operator == ( double lhs, Approx const& rhs ) {
             // Thanks to Richard Harris for his help refining this formula
-            return fabs( lhs - rhs.m_value ) < rhs.m_epsilon * (rhs.m_scale + (std::max)( fabs(lhs), fabs(rhs.m_value) ) );
+            bool relativeOK = std::fabs( lhs - rhs.m_value ) < rhs.m_epsilon * (rhs.m_scale + (std::max)( std::fabs(lhs), std::fabs(rhs.m_value) ) );
+            if (relativeOK) {
+                return true;
+            }
+            return std::fabs(lhs - rhs.m_value) < rhs.m_margin;
         }
 
         friend bool operator == ( Approx const& lhs, double rhs ) {
@@ -2668,11 +2817,37 @@ namespace Detail {
             return !operator==( rhs, lhs );
         }
 
+        friend bool operator <= ( double lhs, Approx const& rhs )
+        {
+          return lhs < rhs.m_value || lhs == rhs;
+        }
+
+        friend bool operator <= ( Approx const& lhs, double rhs )
+        {
+          return lhs.m_value < rhs || lhs == rhs;
+        }
+
+        friend bool operator >= ( double lhs, Approx const& rhs )
+        {
+          return lhs > rhs.m_value || lhs == rhs;
+        }
+
+        friend bool operator >= ( Approx const& lhs, double rhs )
+        {
+          return lhs.m_value > rhs || lhs == rhs;
+        }
+#endif
+
         Approx& epsilon( double newEpsilon ) {
             m_epsilon = newEpsilon;
             return *this;
         }
 
+        Approx& margin( double newMargin ) {
+            m_margin = newMargin;
+            return *this;
+        }
+
         Approx& scale( double newScale ) {
             m_scale = newScale;
             return *this;
@@ -2686,6 +2861,7 @@ namespace Detail {
 
     private:
         double m_epsilon;
+        double m_margin;
         double m_scale;
         double m_value;
     };
@@ -2698,6 +2874,153 @@ inline std::string toString<Detail::Approx>( Detail::Approx const& value ) {
 
 } // end namespace Catch
 
+// #included from: internal/catch_matchers_string.h
+#define TWOBLUECUBES_CATCH_MATCHERS_STRING_H_INCLUDED
+
+namespace Catch {
+namespace Matchers {
+
+    namespace StdString {
+
+        struct CasedString
+        {
+            CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
+            std::string adjustString( std::string const& str ) const;
+            std::string caseSensitivitySuffix() const;
+
+            CaseSensitive::Choice m_caseSensitivity;
+            std::string m_str;
+        };
+
+        struct StringMatcherBase : MatcherBase<std::string> {
+            StringMatcherBase( std::string operation, CasedString const& comparator );
+            virtual std::string describe() const CATCH_OVERRIDE;
+
+            CasedString m_comparator;
+            std::string m_operation;
+        };
+
+        struct EqualsMatcher : StringMatcherBase {
+            EqualsMatcher( CasedString const& comparator );
+            virtual bool match( std::string const& source ) const CATCH_OVERRIDE;
+        };
+        struct ContainsMatcher : StringMatcherBase {
+            ContainsMatcher( CasedString const& comparator );
+            virtual bool match( std::string const& source ) const CATCH_OVERRIDE;
+        };
+        struct StartsWithMatcher : StringMatcherBase {
+            StartsWithMatcher( CasedString const& comparator );
+            virtual bool match( std::string const& source ) const CATCH_OVERRIDE;
+        };
+        struct EndsWithMatcher : StringMatcherBase {
+            EndsWithMatcher( CasedString const& comparator );
+            virtual bool match( std::string const& source ) const CATCH_OVERRIDE;
+        };
+
+    } // namespace StdString
+
+    // The following functions create the actual matcher objects.
+    // This allows the types to be inferred
+
+    StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
+    StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
+    StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
+    StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
+
+} // namespace Matchers
+} // namespace Catch
+
+// #included from: internal/catch_matchers_vector.h
+#define TWOBLUECUBES_CATCH_MATCHERS_VECTOR_H_INCLUDED
+
+namespace Catch {
+namespace Matchers {
+
+    namespace Vector {
+
+        template<typename T>
+        struct ContainsElementMatcher : MatcherBase<std::vector<T>, T> {
+
+            ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
+
+            bool match(std::vector<T> const &v) const CATCH_OVERRIDE {
+                return std::find(v.begin(), v.end(), m_comparator) != v.end();
+            }
+
+            virtual std::string describe() const CATCH_OVERRIDE {
+                return "Contains: " + Catch::toString( m_comparator );
+            }
+
+            T const& m_comparator;
+        };
+
+        template<typename T>
+        struct ContainsMatcher : MatcherBase<std::vector<T>, std::vector<T> > {
+
+            ContainsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
+
+            bool match(std::vector<T> const &v) const CATCH_OVERRIDE {
+                // !TBD: see note in EqualsMatcher
+                if (m_comparator.size() > v.size())
+                    return false;
+                for (size_t i = 0; i < m_comparator.size(); ++i)
+                    if (std::find(v.begin(), v.end(), m_comparator[i]) == v.end())
+                        return false;
+                return true;
+            }
+            virtual std::string describe() const CATCH_OVERRIDE {
+                return "Contains: " + Catch::toString( m_comparator );
+            }
+
+            std::vector<T> const& m_comparator;
+        };
+
+        template<typename T>
+        struct EqualsMatcher : MatcherBase<std::vector<T>, std::vector<T> > {
+
+            EqualsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
+
+            bool match(std::vector<T> const &v) const CATCH_OVERRIDE {
+                // !TBD: This currently works if all elements can be compared using !=
+                // - a more general approach would be via a compare template that defaults
+                // to using !=. but could be specialised for, e.g. std::vector<T> etc
+                // - then just call that directly
+                if (m_comparator.size() != v.size())
+                    return false;
+                for (size_t i = 0; i < v.size(); ++i)
+                    if (m_comparator[i] != v[i])
+                        return false;
+                return true;
+            }
+            virtual std::string describe() const CATCH_OVERRIDE {
+                return "Equals: " + Catch::toString( m_comparator );
+            }
+            std::vector<T> const& m_comparator;
+        };
+
+    } // namespace Vector
+
+    // The following functions create the actual matcher objects.
+    // This allows the types to be inferred
+
+    template<typename T>
+    Vector::ContainsMatcher<T> Contains( std::vector<T> const& comparator ) {
+        return Vector::ContainsMatcher<T>( comparator );
+    }
+
+    template<typename T>
+    Vector::ContainsElementMatcher<T> VectorContains( T const& comparator ) {
+        return Vector::ContainsElementMatcher<T>( comparator );
+    }
+
+    template<typename T>
+    Vector::EqualsMatcher<T> Equals( std::vector<T> const& comparator ) {
+        return Vector::EqualsMatcher<T>( comparator );
+    }
+
+} // namespace Matchers
+} // namespace Catch
+
 // #included from: internal/catch_interfaces_tag_alias_registry.h
 #define TWOBLUECUBES_CATCH_INTERFACES_TAG_ALIAS_REGISTRY_H_INCLUDED
 
@@ -2822,7 +3145,8 @@ namespace Catch {
             IsHidden = 1 << 1,
             ShouldFail = 1 << 2,
             MayFail = 1 << 3,
-            Throws = 1 << 4
+            Throws = 1 << 4,
+            NonPortable = 1 << 5
         };
 
         TestCaseInfo(   std::string const& _name,
@@ -3078,6 +3402,29 @@ return @ desc; \
 #endif
 
 #ifdef CATCH_IMPL
+
+// !TBD: Move the leak detector code into a separate header
+#ifdef CATCH_CONFIG_WINDOWS_CRTDBG
+#include <crtdbg.h>
+class LeakDetector {
+public:
+	LeakDetector() {
+		int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
+		flag |= _CRTDBG_LEAK_CHECK_DF;
+		flag |= _CRTDBG_ALLOC_MEM_DF;
+		_CrtSetDbgFlag(flag);
+		_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
+		_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
+		// Change this to leaking allocation's number to break there
+		_CrtSetBreakAlloc(-1);
+	}
+};
+#else
+class LeakDetector {};
+#endif
+
+LeakDetector leakDetector;
+
 // #included from: internal/catch_impl.hpp
 #define TWOBLUECUBES_CATCH_IMPL_HPP_INCLUDED
 
@@ -3117,6 +3464,8 @@ return @ desc; \
 // #included from: catch_wildcard_pattern.hpp
 #define TWOBLUECUBES_CATCH_WILDCARD_PATTERN_HPP_INCLUDED
 
+#include <stdexcept>
+
 namespace Catch
 {
     class WildcardPattern {
@@ -3134,11 +3483,11 @@ namespace Catch
             m_wildcard( NoWildcard ),
             m_pattern( adjustCase( pattern ) )
         {
-            if( startsWith( m_pattern, "*" ) ) {
+            if( startsWith( m_pattern, '*' ) ) {
                 m_pattern = m_pattern.substr( 1 );
                 m_wildcard = WildcardAtStart;
             }
-            if( endsWith( m_pattern, "*" ) ) {
+            if( endsWith( m_pattern, '*' ) ) {
                 m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
                 m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
             }
@@ -3257,11 +3606,12 @@ namespace Catch {
 namespace Catch {
 
     class TestSpecParser {
-        enum Mode{ None, Name, QuotedName, Tag };
+        enum Mode{ None, Name, QuotedName, Tag, EscapedName };
         Mode m_mode;
         bool m_exclusion;
         std::size_t m_start, m_pos;
         std::string m_arg;
+        std::vector<std::size_t> m_escapeChars;
         TestSpec::Filter m_currentFilter;
         TestSpec m_testSpec;
         ITagAliasRegistry const* m_tagAliases;
@@ -3274,6 +3624,7 @@ namespace Catch {
             m_exclusion = false;
             m_start = std::string::npos;
             m_arg = m_tagAliases->expandAliases( arg );
+            m_escapeChars.clear();
             for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
                 visitChar( m_arg[m_pos] );
             if( m_mode == Name )
@@ -3292,6 +3643,7 @@ namespace Catch {
                 case '~': m_exclusion = true; return;
                 case '[': return startNewMode( Tag, ++m_pos );
                 case '"': return startNewMode( QuotedName, ++m_pos );
+                case '\\': return escape();
                 default: startNewMode( Name, m_pos ); break;
                 }
             }
@@ -3307,7 +3659,11 @@ namespace Catch {
                         addPattern<TestSpec::NamePattern>();
                     startNewMode( Tag, ++m_pos );
                 }
+                else if( c == '\\' )
+                    escape();
             }
+            else if( m_mode == EscapedName )
+                m_mode = Name;
             else if( m_mode == QuotedName && c == '"' )
                 addPattern<TestSpec::NamePattern>();
             else if( m_mode == Tag && c == ']' )
@@ -3317,10 +3673,19 @@ namespace Catch {
             m_mode = mode;
             m_start = start;
         }
+        void escape() {
+            if( m_mode == None )
+                m_start = m_pos;
+            m_mode = EscapedName;
+            m_escapeChars.push_back( m_pos );
+        }
         std::string subString() const { return m_arg.substr( m_start, m_pos - m_start ); }
         template<typename T>
         void addPattern() {
             std::string token = subString();
+            for( size_t i = 0; i < m_escapeChars.size(); ++i )
+                token = token.substr( 0, m_escapeChars[i]-m_start-i ) + token.substr( m_escapeChars[i]-m_start-i+1 );
+            m_escapeChars.clear();
             if( startsWith( token, "exclude:" ) ) {
                 m_exclusion = true;
                 token = token.substr( 8 );
@@ -3354,7 +3719,7 @@ namespace Catch {
 // #included from: catch_interfaces_config.h
 #define TWOBLUECUBES_CATCH_INTERFACES_CONFIG_H_INCLUDED
 
-#include <iostream>
+#include <iosfwd>
 #include <string>
 #include <vector>
 
@@ -3406,6 +3771,8 @@ namespace Catch {
         virtual RunTests::InWhatOrder runOrder() const = 0;
         virtual unsigned int rngSeed() const = 0;
         virtual UseColour::YesOrNo useColour() const = 0;
+        virtual std::vector<std::string> const& getSectionsToRun() const = 0;
+
     };
 }
 
@@ -3474,8 +3841,7 @@ namespace Catch {
 #include <memory>
 #include <vector>
 #include <string>
-#include <iostream>
-#include <ctime>
+#include <stdexcept>
 
 #ifndef CATCH_CONFIG_CONSOLE_WIDTH
 #define CATCH_CONFIG_CONSOLE_WIDTH 80
@@ -3532,6 +3898,7 @@ namespace Catch {
 
         std::vector<std::string> reporterNames;
         std::vector<std::string> testsOrTags;
+        std::vector<std::string> sectionsToRun;
     };
 
     class Config : public SharedImpl<IConfig> {
@@ -3556,8 +3923,7 @@ namespace Catch {
             }
         }
 
-        virtual ~Config() {
-        }
+        virtual ~Config() {}
 
         std::string const& getFilename() const {
             return m_data.outputFilename ;
@@ -3570,27 +3936,26 @@ namespace Catch {
 
         std::string getProcessName() const { return m_data.processName; }
 
-        bool shouldDebugBreak() const { return m_data.shouldDebugBreak; }
+        std::vector<std::string> const& getReporterNames() const { return m_data.reporterNames; }
+        std::vector<std::string> const& getSectionsToRun() const CATCH_OVERRIDE { return m_data.sectionsToRun; }
 
-        std::vector<std::string> getReporterNames() const { return m_data.reporterNames; }
-
-        int abortAfter() const { return m_data.abortAfter; }
-
-        TestSpec const& testSpec() const { return m_testSpec; }
+        virtual TestSpec const& testSpec() const CATCH_OVERRIDE { return m_testSpec; }
 
         bool showHelp() const { return m_data.showHelp; }
-        bool showInvisibles() const { return m_data.showInvisibles; }
 
         // IConfig interface
-        virtual bool allowThrows() const        { return !m_data.noThrow; }
-        virtual std::ostream& stream() const    { return m_stream->stream(); }
-        virtual std::string name() const        { return m_data.name.empty() ? m_data.processName : m_data.name; }
-        virtual bool includeSuccessfulResults() const   { return m_data.showSuccessfulTests; }
-        virtual bool warnAboutMissingAssertions() const { return m_data.warnings & WarnAbout::NoAssertions; }
-        virtual ShowDurations::OrNot showDurations() const { return m_data.showDurations; }
-        virtual RunTests::InWhatOrder runOrder() const  { return m_data.runOrder; }
-        virtual unsigned int rngSeed() const    { return m_data.rngSeed; }
-        virtual UseColour::YesOrNo useColour() const { return m_data.useColour; }
+        virtual bool allowThrows() const CATCH_OVERRIDE                 { return !m_data.noThrow; }
+        virtual std::ostream& stream() const CATCH_OVERRIDE             { return m_stream->stream(); }
+        virtual std::string name() const CATCH_OVERRIDE                 { return m_data.name.empty() ? m_data.processName : m_data.name; }
+        virtual bool includeSuccessfulResults() const CATCH_OVERRIDE    { return m_data.showSuccessfulTests; }
+        virtual bool warnAboutMissingAssertions() const CATCH_OVERRIDE  { return m_data.warnings & WarnAbout::NoAssertions; }
+        virtual ShowDurations::OrNot showDurations() const CATCH_OVERRIDE { return m_data.showDurations; }
+        virtual RunTests::InWhatOrder runOrder() const CATCH_OVERRIDE   { return m_data.runOrder; }
+        virtual unsigned int rngSeed() const CATCH_OVERRIDE             { return m_data.rngSeed; }
+        virtual UseColour::YesOrNo useColour() const CATCH_OVERRIDE     { return m_data.useColour; }
+        virtual bool shouldDebugBreak() const CATCH_OVERRIDE { return m_data.shouldDebugBreak; }
+        virtual int abortAfter() const CATCH_OVERRIDE { return m_data.abortAfter; }
+        virtual bool showInvisibles() const CATCH_OVERRIDE { return m_data.showInvisibles; }
 
     private:
 
@@ -4652,6 +5017,7 @@ STITCH_CLARA_CLOSE_NAMESPACE
 #endif
 
 #include <fstream>
+#include <ctime>
 
 namespace Catch {
 
@@ -4662,13 +5028,14 @@ namespace Catch {
         config.abortAfter = x;
     }
     inline void addTestOrTags( ConfigData& config, std::string const& _testSpec ) { config.testsOrTags.push_back( _testSpec ); }
+    inline void addSectionToRun( ConfigData& config, std::string const& sectionName ) { config.sectionsToRun.push_back( sectionName ); }
     inline void addReporterName( ConfigData& config, std::string const& _reporterName ) { config.reporterNames.push_back( _reporterName ); }
 
     inline void addWarning( ConfigData& config, std::string const& _warning ) {
         if( _warning == "NoAssertions" )
             config.warnings = static_cast<WarnAbout::What>( config.warnings | WarnAbout::NoAssertions );
         else
-            throw std::runtime_error( "Unrecognised warning: '" + _warning + "'" );
+            throw std::runtime_error( "Unrecognised warning: '" + _warning + '\'' );
     }
     inline void setOrder( ConfigData& config, std::string const& order ) {
         if( startsWith( "declared", order ) )
@@ -4678,7 +5045,7 @@ namespace Catch {
         else if( startsWith( "random", order ) )
             config.runOrder = RunTests::InRandomOrder;
         else
-            throw std::runtime_error( "Unrecognised ordering: '" + order + "'" );
+            throw std::runtime_error( "Unrecognised ordering: '" + order + '\'' );
     }
     inline void setRngSeed( ConfigData& config, std::string const& seed ) {
         if( seed == "time" ) {
@@ -4689,7 +5056,7 @@ namespace Catch {
             ss << seed;
             ss >> config.rngSeed;
             if( ss.fail() )
-                throw std::runtime_error( "Argment to --rng-seed should be the word 'time' or a number" );
+                throw std::runtime_error( "Argument to --rng-seed should be the word 'time' or a number" );
         }
     }
     inline void setVerbosity( ConfigData& config, int level ) {
@@ -4724,10 +5091,10 @@ namespace Catch {
         std::string line;
         while( std::getline( f, line ) ) {
             line = trim(line);
-            if( !line.empty() && !startsWith( line, "#" ) ) {
-                if( !startsWith( line, "\"" ) )
-                    line = "\"" + line + "\"";
-                addTestOrTags( config, line + "," );
+            if( !line.empty() && !startsWith( line, '#' ) ) {
+                if( !startsWith( line, '"' ) )
+                    line = '"' + line + '"';
+                addTestOrTags( config, line + ',' );
             }
         }
     }
@@ -4815,6 +5182,10 @@ namespace Catch {
             .describe( "adds a tag for the filename" )
             .bind( &ConfigData::filenamesAsTags );
 
+        cli["-c"]["--section"]
+                .describe( "specify section to run" )
+                .bind( &addSectionToRun, "section name" );
+
         // Less common commands which don't have a short form
         cli["--list-test-names-only"]
             .describe( "list all/matching test cases names only" )
@@ -4887,19 +5258,16 @@ namespace Tbc {
         TextAttributes()
         :   initialIndent( std::string::npos ),
             indent( 0 ),
-            width( consoleWidth-1 ),
-            tabChar( '\t' )
+            width( consoleWidth-1 )
         {}
 
         TextAttributes& setInitialIndent( std::size_t _value )  { initialIndent = _value; return *this; }
         TextAttributes& setIndent( std::size_t _value )         { indent = _value; return *this; }
         TextAttributes& setWidth( std::size_t _value )          { width = _value; return *this; }
-        TextAttributes& setTabChar( char _value )               { tabChar = _value; return *this; }
 
         std::size_t initialIndent;  // indent of first line, or npos
         std::size_t indent;         // indent of subsequent lines, or all if initialIndent is npos
         std::size_t width;          // maximum width of text, including indent. Longer text will wrap
-        char tabChar;               // If this char is seen the indent is changed to current pos
     };
 
     class Text {
@@ -4907,62 +5275,76 @@ namespace Tbc {
         Text( std::string const& _str, TextAttributes const& _attr = TextAttributes() )
         : attr( _attr )
         {
-            std::string wrappableChars = " [({.,/|\\-";
-            std::size_t indent = _attr.initialIndent != std::string::npos
-                ? _attr.initialIndent
-                : _attr.indent;
-            std::string remainder = _str;
+            const std::string wrappableBeforeChars = "[({<\t";
+            const std::string wrappableAfterChars = "])}>-,./|\\";
+            const std::string wrappableInsteadOfChars = " \n\r";
+            std::string indent = _attr.initialIndent != std::string::npos
+                ? std::string( _attr.initialIndent, ' ' )
+                : std::string( _attr.indent, ' ' );
+
+            typedef std::string::const_iterator iterator;
+            iterator it = _str.begin();
+            const iterator strEnd = _str.end();
+
+            while( it != strEnd ) {
 
-            while( !remainder.empty() ) {
                 if( lines.size() >= 1000 ) {
                     lines.push_back( "... message truncated due to excessive size" );
                     return;
                 }
-                std::size_t tabPos = std::string::npos;
-                std::size_t width = (std::min)( remainder.size(), _attr.width - indent );
-                std::size_t pos = remainder.find_first_of( '\n' );
-                if( pos <= width ) {
-                    width = pos;
-                }
-                pos = remainder.find_last_of( _attr.tabChar, width );
-                if( pos != std::string::npos ) {
-                    tabPos = pos;
-                    if( remainder[width] == '\n' )
-                        width--;
-                    remainder = remainder.substr( 0, tabPos ) + remainder.substr( tabPos+1 );
-                }
 
-                if( width == remainder.size() ) {
-                    spliceLine( indent, remainder, width );
-                }
-                else if( remainder[width] == '\n' ) {
-                    spliceLine( indent, remainder, width );
-                    if( width <= 1 || remainder.size() != 1 )
-                        remainder = remainder.substr( 1 );
-                    indent = _attr.indent;
-                }
-                else {
-                    pos = remainder.find_last_of( wrappableChars, width );
-                    if( pos != std::string::npos && pos > 0 ) {
-                        spliceLine( indent, remainder, pos );
-                        if( remainder[0] == ' ' )
-                            remainder = remainder.substr( 1 );
+                std::string suffix;
+                std::size_t width = (std::min)( static_cast<size_t>( strEnd-it ), _attr.width-static_cast<size_t>( indent.size() ) );
+                iterator itEnd = it+width;
+                iterator itNext = _str.end();
+
+                iterator itNewLine = std::find( it, itEnd, '\n' );
+                if( itNewLine != itEnd )
+                    itEnd = itNewLine;
+
+                if( itEnd != strEnd  ) {
+                    bool foundWrapPoint = false;
+                    iterator findIt = itEnd;
+                    do {
+                        if( wrappableAfterChars.find( *findIt ) != std::string::npos && findIt != itEnd ) {
+                            itEnd = findIt+1;
+                            itNext = findIt+1;
+                            foundWrapPoint = true;
+                        }
+                        else if( findIt > it && wrappableBeforeChars.find( *findIt ) != std::string::npos ) {
+                            itEnd = findIt;
+                            itNext = findIt;
+                            foundWrapPoint = true;
+                        }
+                        else if( wrappableInsteadOfChars.find( *findIt ) != std::string::npos ) {
+                            itNext = findIt+1;
+                            itEnd = findIt;
+                            foundWrapPoint = true;
+                        }
+                        if( findIt == it )
+                            break;
+                        else
+                            --findIt;
                     }
-                    else {
-                        spliceLine( indent, remainder, width-1 );
-                        lines.back() += "-";
+                    while( !foundWrapPoint );
+
+                    if( !foundWrapPoint ) {
+                        // No good wrap char, so we'll break mid word and add a hyphen
+                        --itEnd;
+                        itNext = itEnd;
+                        suffix = "-";
+                    }
+                    else {
+                        while( itEnd > it && wrappableInsteadOfChars.find( *(itEnd-1) ) != std::string::npos )
+                            --itEnd;
                     }
-                    if( lines.size() == 1 )
-                        indent = _attr.indent;
-                    if( tabPos != std::string::npos )
-                        indent += tabPos;
                 }
-            }
-        }
+                lines.push_back( indent + std::string( it, itEnd ) + suffix );
 
-        void spliceLine( std::size_t _indent, std::string& _remainder, std::size_t _pos ) {
-            lines.push_back( std::string( _indent, ' ' ) + _remainder.substr( 0, _pos ) );
-            _remainder = _remainder.substr( _pos );
+                if( indent.size() != _attr.indent )
+                    indent = std::string( _attr.indent, ' ' );
+                it = itNext;
+            }
         }
 
         typedef std::vector<std::string>::const_iterator const_iterator;
@@ -5071,7 +5453,6 @@ namespace Catch {
 #include <string>
 #include <ostream>
 #include <map>
-#include <assert.h>
 
 namespace Catch
 {
@@ -5359,9 +5740,9 @@ namespace Catch {
         }
 
         if( !config.testSpec().hasFilters() )
-            Catch::cout() << pluralise( matchedTests, "test case" ) << "\n" << std::endl;
+            Catch::cout() << pluralise( matchedTests, "test case" ) << '\n' << std::endl;
         else
-            Catch::cout() << pluralise( matchedTests, "matching test case" ) << "\n" << std::endl;
+            Catch::cout() << pluralise( matchedTests, "matching test case" ) << '\n' << std::endl;
         return matchedTests;
     }
 
@@ -5376,8 +5757,8 @@ namespace Catch {
                 ++it ) {
             matchedTests++;
             TestCaseInfo const& testCaseInfo = it->getTestCaseInfo();
-            if( startsWith( testCaseInfo.name, "#" ) )
-               Catch::cout() << "\"" << testCaseInfo.name << "\"" << std::endl;
+            if( startsWith( testCaseInfo.name, '#' ) )
+               Catch::cout() << '"' << testCaseInfo.name << '"' << std::endl;
             else
                Catch::cout() << testCaseInfo.name << std::endl;
         }
@@ -5440,9 +5821,9 @@ namespace Catch {
                                                     .setInitialIndent( 0 )
                                                     .setIndent( oss.str().size() )
                                                     .setWidth( CATCH_CONFIG_CONSOLE_WIDTH-10 ) );
-            Catch::cout() << oss.str() << wrapper << "\n";
+            Catch::cout() << oss.str() << wrapper << '\n';
         }
-        Catch::cout() << pluralise( tagCounts.size(), "tag" ) << "\n" << std::endl;
+        Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
         return tagCounts.size();
     }
 
@@ -5461,9 +5842,9 @@ namespace Catch {
                                                         .setWidth( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 ) );
             Catch::cout() << "  "
                     << it->first
-                    << ":"
+                    << ':'
                     << std::string( maxNameLen - it->first.size() + 2, ' ' )
-                    << wrapper << "\n";
+                    << wrapper << '\n';
         }
         Catch::cout() << std::endl;
         return factories.size();
@@ -5494,15 +5875,27 @@ namespace Catch {
 #include <string>
 #include <assert.h>
 #include <vector>
+#include <iterator>
+#include <stdexcept>
 
 namespace Catch {
 namespace TestCaseTracking {
 
+    struct NameAndLocation {
+        std::string name;
+        SourceLineInfo location;
+
+        NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
+        :   name( _name ),
+            location( _location )
+        {}
+    };
+
     struct ITracker : SharedImpl<> {
         virtual ~ITracker();
 
         // static queries
-        virtual std::string name() const = 0;
+        virtual NameAndLocation const& nameAndLocation() const = 0;
 
         // dynamic queries
         virtual bool isComplete() const = 0; // Successfully completed or failed
@@ -5518,7 +5911,7 @@ namespace TestCaseTracking {
         virtual void markAsNeedingAnotherRun() = 0;
 
         virtual void addChild( Ptr<ITracker> const& child ) = 0;
-        virtual ITracker* findChild( std::string const& name ) = 0;
+        virtual ITracker* findChild( NameAndLocation const& nameAndLocation ) = 0;
         virtual void openChild() = 0;
 
         // Debug/ checking
@@ -5526,7 +5919,7 @@ namespace TestCaseTracking {
         virtual bool isIndexTracker() const = 0;
     };
 
-    class TrackerContext {
+    class  TrackerContext {
 
         enum RunState {
             NotStarted,
@@ -5588,30 +5981,32 @@ namespace TestCaseTracking {
             Failed
         };
         class TrackerHasName {
-            std::string m_name;
+            NameAndLocation m_nameAndLocation;
         public:
-            TrackerHasName( std::string const& name ) : m_name( name ) {}
+            TrackerHasName( NameAndLocation const& nameAndLocation ) : m_nameAndLocation( nameAndLocation ) {}
             bool operator ()( Ptr<ITracker> const& tracker ) {
-                return tracker->name() == m_name;
+                return
+                    tracker->nameAndLocation().name == m_nameAndLocation.name &&
+                    tracker->nameAndLocation().location == m_nameAndLocation.location;
             }
         };
         typedef std::vector<Ptr<ITracker> > Children;
-        std::string m_name;
+        NameAndLocation m_nameAndLocation;
         TrackerContext& m_ctx;
         ITracker* m_parent;
         Children m_children;
         CycleState m_runState;
     public:
-        TrackerBase( std::string const& name, TrackerContext& ctx, ITracker* parent )
-        :   m_name( name ),
+        TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
+        :   m_nameAndLocation( nameAndLocation ),
             m_ctx( ctx ),
             m_parent( parent ),
             m_runState( NotStarted )
         {}
         virtual ~TrackerBase();
 
-        virtual std::string name() const CATCH_OVERRIDE {
-            return m_name;
+        virtual NameAndLocation const& nameAndLocation() const CATCH_OVERRIDE {
+            return m_nameAndLocation;
         }
         virtual bool isComplete() const CATCH_OVERRIDE {
             return m_runState == CompletedSuccessfully || m_runState == Failed;
@@ -5630,8 +6025,8 @@ namespace TestCaseTracking {
             m_children.push_back( child );
         }
 
-        virtual ITracker* findChild( std::string const& name ) CATCH_OVERRIDE {
-            Children::const_iterator it = std::find_if( m_children.begin(), m_children.end(), TrackerHasName( name ) );
+        virtual ITracker* findChild( NameAndLocation const& nameAndLocation ) CATCH_OVERRIDE {
+            Children::const_iterator it = std::find_if( m_children.begin(), m_children.end(), TrackerHasName( nameAndLocation ) );
             return( it != m_children.end() )
                 ? it->get()
                 : CATCH_NULL;
@@ -5709,32 +6104,56 @@ namespace TestCaseTracking {
     };
 
     class SectionTracker : public TrackerBase {
+        std::vector<std::string> m_filters;
     public:
-        SectionTracker( std::string const& name, TrackerContext& ctx, ITracker* parent )
-        :   TrackerBase( name, ctx, parent )
-        {}
+        SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
+        :   TrackerBase( nameAndLocation, ctx, parent )
+        {
+            if( parent ) {
+                while( !parent->isSectionTracker() )
+                    parent = &parent->parent();
+
+                SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
+                addNextFilters( parentSection.m_filters );
+            }
+        }
         virtual ~SectionTracker();
 
         virtual bool isSectionTracker() const CATCH_OVERRIDE { return true; }
 
-        static SectionTracker& acquire( TrackerContext& ctx, std::string const& name ) {
+        static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
             SectionTracker* section = CATCH_NULL;
 
             ITracker& currentTracker = ctx.currentTracker();
-            if( ITracker* childTracker = currentTracker.findChild( name ) ) {
+            if( ITracker* childTracker = currentTracker.findChild( nameAndLocation ) ) {
                 assert( childTracker );
                 assert( childTracker->isSectionTracker() );
                 section = static_cast<SectionTracker*>( childTracker );
             }
             else {
-                section = new SectionTracker( name, ctx, &currentTracker );
+                section = new SectionTracker( nameAndLocation, ctx, &currentTracker );
                 currentTracker.addChild( section );
             }
-            if( !ctx.completedCycle() && !section->isComplete() ) {
+            if( !ctx.completedCycle() )
+                section->tryOpen();
+            return *section;
+        }
+
+        void tryOpen() {
+            if( !isComplete() && (m_filters.empty() || m_filters[0].empty() ||  m_filters[0] == m_nameAndLocation.name ) )
+                open();
+        }
 
-                section->open();
+        void addInitialFilters( std::vector<std::string> const& filters ) {
+            if( !filters.empty() ) {
+                m_filters.push_back(""); // Root - should never be consulted
+                m_filters.push_back(""); // Test Case - not a section filter
+                std::copy( filters.begin(), filters.end(), std::back_inserter( m_filters ) );
             }
-            return *section;
+        }
+        void addNextFilters( std::vector<std::string> const& filters ) {
+            if( filters.size() > 1 )
+                std::copy( filters.begin()+1, filters.end(), std::back_inserter( m_filters ) );
         }
     };
 
@@ -5742,8 +6161,8 @@ namespace TestCaseTracking {
         int m_size;
         int m_index;
     public:
-        IndexTracker( std::string const& name, TrackerContext& ctx, ITracker* parent, int size )
-        :   TrackerBase( name, ctx, parent ),
+        IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size )
+        :   TrackerBase( nameAndLocation, ctx, parent ),
             m_size( size ),
             m_index( -1 )
         {}
@@ -5751,17 +6170,17 @@ namespace TestCaseTracking {
 
         virtual bool isIndexTracker() const CATCH_OVERRIDE { return true; }
 
-        static IndexTracker& acquire( TrackerContext& ctx, std::string const& name, int size ) {
+        static IndexTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size ) {
             IndexTracker* tracker = CATCH_NULL;
 
             ITracker& currentTracker = ctx.currentTracker();
-            if( ITracker* childTracker = currentTracker.findChild( name ) ) {
+            if( ITracker* childTracker = currentTracker.findChild( nameAndLocation ) ) {
                 assert( childTracker );
                 assert( childTracker->isIndexTracker() );
                 tracker = static_cast<IndexTracker*>( childTracker );
             }
             else {
-                tracker = new IndexTracker( name, ctx, &currentTracker, size );
+                tracker = new IndexTracker( nameAndLocation, ctx, &currentTracker, size );
                 currentTracker.addChild( tracker );
             }
 
@@ -5789,7 +6208,7 @@ namespace TestCaseTracking {
     };
 
     inline ITracker& TrackerContext::startRun() {
-        m_rootTracker = new SectionTracker( "{root}", *this, CATCH_NULL );
+        m_rootTracker = new SectionTracker( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, CATCH_NULL );
         m_currentTracker = CATCH_NULL;
         m_runState = Executing;
         return *m_rootTracker;
@@ -5809,35 +6228,138 @@ using TestCaseTracking::IndexTracker;
 
 namespace Catch {
 
-    // Report the error condition then exit the process
-    inline void fatal( std::string const& message, int exitCode ) {
+    // Report the error condition
+    inline void reportFatal( std::string const& message ) {
         IContext& context = Catch::getCurrentContext();
         IResultCapture* resultCapture = context.getResultCapture();
         resultCapture->handleFatalErrorCondition( message );
-
-		if( Catch::alwaysTrue() ) // avoids "no return" warnings
-            exit( exitCode );
     }
 
 } // namespace Catch
 
 #if defined ( CATCH_PLATFORM_WINDOWS ) /////////////////////////////////////////
+// #included from: catch_windows_h_proxy.h
+
+#define TWOBLUECUBES_CATCH_WINDOWS_H_PROXY_H_INCLUDED
+
+#ifdef CATCH_DEFINES_NOMINMAX
+#  define NOMINMAX
+#endif
+#ifdef CATCH_DEFINES_WIN32_LEAN_AND_MEAN
+#  define WIN32_LEAN_AND_MEAN
+#endif
+
+#ifdef __AFXDLL
+#include <AfxWin.h>
+#else
+#include <windows.h>
+#endif
+
+#ifdef CATCH_DEFINES_NOMINMAX
+#  undef NOMINMAX
+#endif
+#ifdef CATCH_DEFINES_WIN32_LEAN_AND_MEAN
+#  undef WIN32_LEAN_AND_MEAN
+#endif
+
+
+#  if !defined ( CATCH_CONFIG_WINDOWS_SEH )
+
+namespace Catch {
+    struct FatalConditionHandler {
+        void reset() {}
+    };
+}
+
+#  else // CATCH_CONFIG_WINDOWS_SEH is defined
 
 namespace Catch {
 
+    struct SignalDefs { DWORD id; const char* name; };
+    extern SignalDefs signalDefs[];
+    // There is no 1-1 mapping between signals and windows exceptions.
+    // Windows can easily distinguish between SO and SigSegV,
+    // but SigInt, SigTerm, etc are handled differently.
+    SignalDefs signalDefs[] = {
+        { EXCEPTION_ILLEGAL_INSTRUCTION,  "SIGILL - Illegal instruction signal" },
+        { EXCEPTION_STACK_OVERFLOW, "SIGSEGV - Stack overflow" },
+        { EXCEPTION_ACCESS_VIOLATION, "SIGSEGV - Segmentation violation signal" },
+        { EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero error" },
+    };
+
     struct FatalConditionHandler {
-		void reset() {}
-	};
+
+        static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
+            for (int i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) {
+                if (ExceptionInfo->ExceptionRecord->ExceptionCode == signalDefs[i].id) {
+                    reset();
+                    reportFatal(signalDefs[i].name);
+                }
+            }
+            // If its not an exception we care about, pass it along.
+            // This stops us from eating debugger breaks etc.
+            return EXCEPTION_CONTINUE_SEARCH;
+        }
+
+        FatalConditionHandler() {
+            isSet = true;
+            // 32k seems enough for Catch to handle stack overflow,
+            // but the value was found experimentally, so there is no strong guarantee
+            guaranteeSize = 32 * 1024;
+            exceptionHandlerHandle = CATCH_NULL;
+            // Register as first handler in current chain
+            exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
+            // Pass in guarantee size to be filled
+            SetThreadStackGuarantee(&guaranteeSize);
+        }
+
+        static void reset() {
+            if (isSet) {
+                // Unregister handler and restore the old guarantee
+                RemoveVectoredExceptionHandler(exceptionHandlerHandle);
+                SetThreadStackGuarantee(&guaranteeSize);
+                exceptionHandlerHandle = CATCH_NULL;
+                isSet = false;
+            }
+        }
+
+        ~FatalConditionHandler() {
+            reset();
+        }
+    private:
+        static bool isSet;
+        static ULONG guaranteeSize;
+        static PVOID exceptionHandlerHandle;
+    };
+
+    bool FatalConditionHandler::isSet = false;
+    ULONG FatalConditionHandler::guaranteeSize = 0;
+    PVOID FatalConditionHandler::exceptionHandlerHandle = CATCH_NULL;
 
 } // namespace Catch
 
+#  endif // CATCH_CONFIG_WINDOWS_SEH
+
 #else // Not Windows - assumed to be POSIX compatible //////////////////////////
 
+#  if !defined(CATCH_CONFIG_POSIX_SIGNALS)
+
+namespace Catch {
+    struct FatalConditionHandler {
+        void reset() {}
+    };
+}
+
+#  else // CATCH_CONFIG_POSIX_SIGNALS is defined
+
 #include <signal.h>
 
 namespace Catch {
 
-    struct SignalDefs { int id; const char* name; };
+    struct SignalDefs {
+        int id;
+        const char* name;
+    };
     extern SignalDefs signalDefs[];
     SignalDefs signalDefs[] = {
             { SIGINT,  "SIGINT - Terminal interrupt signal" },
@@ -5846,37 +6368,70 @@ namespace Catch {
             { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
             { SIGTERM, "SIGTERM - Termination request signal" },
             { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
-        };
+    };
 
     struct FatalConditionHandler {
 
+        static bool isSet;
+        static struct sigaction oldSigActions [sizeof(signalDefs)/sizeof(SignalDefs)];
+        static stack_t oldSigStack;
+        static char altStackMem[SIGSTKSZ];
+
         static void handleSignal( int sig ) {
-            for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i )
-                if( sig == signalDefs[i].id )
-                    fatal( signalDefs[i].name, -sig );
-            fatal( "<unknown signal>", -sig );
+            std::string name = "<unknown signal>";
+            for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) {
+                SignalDefs &def = signalDefs[i];
+                if (sig == def.id) {
+                    name = def.name;
+                    break;
+                }
+            }
+            reset();
+            reportFatal(name);
+            raise( sig );
         }
 
-        FatalConditionHandler() : m_isSet( true ) {
-            for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i )
-                signal( signalDefs[i].id, handleSignal );
+        FatalConditionHandler() {
+            isSet = true;
+            stack_t sigStack;
+            sigStack.ss_sp = altStackMem;
+            sigStack.ss_size = SIGSTKSZ;
+            sigStack.ss_flags = 0;
+            sigaltstack(&sigStack, &oldSigStack);
+            struct sigaction sa = { 0 };
+
+            sa.sa_handler = handleSignal;
+            sa.sa_flags = SA_ONSTACK;
+            for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
+                sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
+            }
         }
+
         ~FatalConditionHandler() {
             reset();
         }
-        void reset() {
-            if( m_isSet ) {
-                for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i )
-                    signal( signalDefs[i].id, SIG_DFL );
-                m_isSet = false;
+        static void reset() {
+            if( isSet ) {
+                // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
+                for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
+                    sigaction(signalDefs[i].id, &oldSigActions[i], CATCH_NULL);
+                }
+                // Return the old stack
+                sigaltstack(&oldSigStack, CATCH_NULL);
+                isSet = false;
             }
         }
-
-        bool m_isSet;
     };
 
+    bool FatalConditionHandler::isSet = false;
+    struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
+    stack_t FatalConditionHandler::oldSigStack = {};
+    char FatalConditionHandler::altStackMem[SIGSTKSZ] = {};
+
 } // namespace Catch
 
+#  endif // CATCH_CONFIG_POSIX_SIGNALS
+
 #endif // not Windows
 
 #include <set>
@@ -5953,10 +6508,12 @@ namespace Catch {
             m_activeTestCase = &testCase;
 
             do {
-                m_trackerContext.startRun();
+                ITracker& rootTracker = m_trackerContext.startRun();
+                assert( rootTracker.isSectionTracker() );
+                static_cast<SectionTracker&>( rootTracker ).addInitialFilters( m_config->getSectionsToRun() );
                 do {
                     m_trackerContext.startCycle();
-                    m_testCaseTracker = &SectionTracker::acquire( m_trackerContext, testInfo.name );
+                    m_testCaseTracker = &SectionTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( testInfo.name, testInfo.lineInfo ) );
                     runCurrentTest( redirectedCout, redirectedCerr );
                 }
                 while( !m_testCaseTracker->isSuccessfullyCompleted() && !aborting() );
@@ -6001,7 +6558,7 @@ namespace Catch {
                 m_messages.clear();
 
             // Reset working state
-            m_lastAssertionInfo = AssertionInfo( "", m_lastAssertionInfo.lineInfo, "{Unknown expression after the reported line}" , m_lastAssertionInfo.resultDisposition );
+            m_lastAssertionInfo = AssertionInfo( std::string(), m_lastAssertionInfo.lineInfo, "{Unknown expression after the reported line}" , m_lastAssertionInfo.resultDisposition );
             m_lastResult = result;
         }
 
@@ -6010,10 +6567,7 @@ namespace Catch {
             Counts& assertions
         )
         {
-            std::ostringstream oss;
-            oss << sectionInfo.name << "@" << sectionInfo.lineInfo;
-
-            ITracker& sectionTracker = SectionTracker::acquire( m_trackerContext, oss.str() );
+            ITracker& sectionTracker = SectionTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( sectionInfo.name, sectionInfo.lineInfo ) );
             if( !sectionTracker.isOpen() )
                 return false;
             m_activeSections.push_back( &sectionTracker );
@@ -6072,7 +6626,7 @@ namespace Catch {
         virtual std::string getCurrentTestName() const {
             return m_activeTestCase
                 ? m_activeTestCase->getTestCaseInfo().name
-                : "";
+                : std::string();
         }
 
         virtual const AssertionResult* getLastResult() const {
@@ -6102,11 +6656,11 @@ namespace Catch {
             deltaTotals.testCases.failed = 1;
             m_reporter->testCaseEnded( TestCaseStats(   testInfo,
                                                         deltaTotals,
-                                                        "",
-                                                        "",
+                                                        std::string(),
+                                                        std::string(),
                                                         false ) );
             m_totals.testCases.failed++;
-            testGroupEnded( "", m_totals, 1, 1 );
+            testGroupEnded( std::string(), m_totals, 1, 1 );
             m_reporter->testRunEnded( TestRunStats( m_runInfo, m_totals, false ) );
         }
 
@@ -6125,7 +6679,7 @@ namespace Catch {
             Counts prevAssertions = m_totals.assertions;
             double duration = 0;
             try {
-                m_lastAssertionInfo = AssertionInfo( "TEST_CASE", testCaseInfo.lineInfo, "", ResultDisposition::Normal );
+                m_lastAssertionInfo = AssertionInfo( "TEST_CASE", testCaseInfo.lineInfo, std::string(), ResultDisposition::Normal );
 
                 seedRng( *m_config );
 
@@ -6455,13 +7009,8 @@ namespace Catch {
 #include <vector>
 #include <set>
 #include <sstream>
-#include <iostream>
 #include <algorithm>
 
-#ifdef CATCH_CPP14_OR_GREATER
-#include <random>
-#endif
-
 namespace Catch {
 
     struct RandomNumberGenerator {
@@ -6469,7 +7018,7 @@ namespace Catch {
 
         result_type operator()( result_type n ) const { return std::rand() % n; }
 
-#ifdef CATCH_CPP14_OR_GREATER
+#ifdef CATCH_CONFIG_CPP11_SHUFFLE
         static constexpr result_type min() { return 0; }
         static constexpr result_type max() { return 1000000; }
         result_type operator()() const { return std::rand() % max(); }
@@ -6477,7 +7026,7 @@ namespace Catch {
         template<typename V>
         static void shuffle( V& vector ) {
             RandomNumberGenerator rng;
-#ifdef CATCH_CPP14_OR_GREATER
+#ifdef CATCH_CONFIG_CPP11_SHUFFLE
             std::shuffle( vector.begin(), vector.end(), rng );
 #else
             std::random_shuffle( vector.begin(), vector.end(), rng );
@@ -6520,7 +7069,7 @@ namespace Catch {
 
                 ss  << Colour( Colour::Red )
                     << "error: TEST_CASE( \"" << it->name << "\" ) already defined.\n"
-                    << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
+                    << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << '\n'
                     << "\tRedefined at " << it->getTestCaseInfo().lineInfo << std::endl;
 
                 throw std::runtime_error(ss.str());
@@ -6552,7 +7101,7 @@ namespace Catch {
 
         virtual void registerTest( TestCase const& testCase ) {
             std::string name = testCase.getTestCaseInfo().name;
-            if( name == "" ) {
+            if( name.empty() ) {
                 std::ostringstream oss;
                 oss << "Anonymous test case " << ++m_unnamedCount;
                 return registerTest( testCase.withName( oss.str() ) );
@@ -6601,7 +7150,7 @@ namespace Catch {
 
     inline std::string extractClassName( std::string const& classOrQualifiedMethodName ) {
         std::string className = classOrQualifiedMethodName;
-        if( startsWith( className, "&" ) )
+        if( startsWith( className, '&' ) )
         {
             std::size_t lastColons = className.rfind( "::" );
             std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
@@ -6819,7 +7368,7 @@ namespace Catch {
 // #included from: catch_notimplemented_exception.hpp
 #define TWOBLUECUBES_CATCH_NOTIMPLEMENTED_EXCEPTION_HPP_INCLUDED
 
-#include <ostream>
+#include <sstream>
 
 namespace Catch {
 
@@ -6891,7 +7440,7 @@ namespace Catch {
         m_ofs.open( filename.c_str() );
         if( m_ofs.fail() ) {
             std::ostringstream oss;
-            oss << "Unable to open file: '" << filename << "'";
+            oss << "Unable to open file: '" << filename << '\'';
             throw std::domain_error( oss.str() );
         }
     }
@@ -6944,6 +7493,11 @@ namespace Catch {
         Context( Context const& );
         void operator=( Context const& );
 
+    public:
+        virtual ~Context() {
+            deleteAllValues( m_generatorsByTestName );
+        }
+
     public: // IContext
         virtual IResultCapture* getResultCapture() {
             return m_resultCapture;
@@ -7057,16 +7611,6 @@ namespace Catch {
 
 #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
 
-#ifndef NOMINMAX
-#define NOMINMAX
-#endif
-
-#ifdef __AFXDLL
-#include <AfxWin.h>
-#else
-#include <windows.h>
-#endif
-
 namespace Catch {
 namespace {
 
@@ -7147,7 +7691,7 @@ namespace {
                 case Colour::White:     return setColour( "[0m" );
                 case Colour::Red:       return setColour( "[0;31m" );
                 case Colour::Green:     return setColour( "[0;32m" );
-                case Colour::Blue:      return setColour( "[0:34m" );
+                case Colour::Blue:      return setColour( "[0;34m" );
                 case Colour::Cyan:      return setColour( "[0;36m" );
                 case Colour::Yellow:    return setColour( "[0;33m" );
                 case Colour::Grey:      return setColour( "[1;30m" );
@@ -7333,7 +7877,7 @@ namespace Catch {
 
     std::string AssertionResult::getExpression() const {
         if( isFalseTest( m_info.resultDisposition ) )
-            return "!" + m_info.capturedExpression;
+            return '!' + m_info.capturedExpression;
         else
             return m_info.capturedExpression;
     }
@@ -7349,7 +7893,7 @@ namespace Catch {
     }
 
     std::string AssertionResult::getExpandedExpression() const {
-        return m_resultData.reconstructedExpression;
+        return m_resultData.reconstructExpression();
     }
 
     std::string AssertionResult::getMessage() const {
@@ -7363,15 +7907,25 @@ namespace Catch {
         return m_info.macroName;
     }
 
+    void AssertionResult::discardDecomposedExpression() const {
+        m_resultData.decomposedExpression = CATCH_NULL;
+    }
+
+    void AssertionResult::expandDecomposedExpression() const {
+        m_resultData.reconstructExpression();
+    }
+
 } // end namespace Catch
 
 // #included from: catch_test_case_info.hpp
 #define TWOBLUECUBES_CATCH_TEST_CASE_INFO_HPP_INCLUDED
 
+#include <cctype>
+
 namespace Catch {
 
     inline TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
-        if( startsWith( tag, "." ) ||
+        if( startsWith( tag, '.' ) ||
             tag == "hide" ||
             tag == "!hide" )
             return TestCaseInfo::IsHidden;
@@ -7381,11 +7935,13 @@ namespace Catch {
             return TestCaseInfo::ShouldFail;
         else if( tag == "!mayfail" )
             return TestCaseInfo::MayFail;
+        else if( tag == "!nonportable" )
+            return TestCaseInfo::NonPortable;
         else
             return TestCaseInfo::None;
     }
     inline bool isReservedTag( std::string const& tag ) {
-        return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !isalnum( tag[0] );
+        return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( tag[0] );
     }
     inline void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
         if( isReservedTag( tag ) ) {
@@ -7455,7 +8011,7 @@ namespace Catch {
 
         std::ostringstream oss;
         for( std::set<std::string>::const_iterator it = tags.begin(), itEnd = tags.end(); it != itEnd; ++it ) {
-            oss << "[" << *it << "]";
+            oss << '[' << *it << ']';
             std::string lcaseTag = toLower( *it );
             testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
             testCaseInfo.lcaseTags.insert( lcaseTag );
@@ -7571,18 +8127,18 @@ namespace Catch {
     {}
 
     std::ostream& operator << ( std::ostream& os, Version const& version ) {
-        os  << version.majorVersion << "."
-            << version.minorVersion << "."
+        os  << version.majorVersion << '.'
+            << version.minorVersion << '.'
             << version.patchNumber;
 
         if( !version.branchName.empty() ) {
-            os  << "-" << version.branchName
-                << "." << version.buildNumber;
+            os  << '-' << version.branchName
+                << '.' << version.buildNumber;
         }
         return os;
     }
 
-    Version libraryVersion( 1, 5, 9, "", 0 );
+    Version libraryVersion( 1, 8, 1, "", 0 );
 
 }
 
@@ -7753,9 +8309,11 @@ namespace Catch
 #endif
 
 #ifdef CATCH_PLATFORM_WINDOWS
-#include <windows.h>
+
 #else
+
 #include <sys/time.h>
+
 #endif
 
 namespace Catch {
@@ -7802,19 +8360,28 @@ namespace Catch {
 // #included from: catch_common.hpp
 #define TWOBLUECUBES_CATCH_COMMON_HPP_INCLUDED
 
+#include <cstring>
+#include <cctype>
+
 namespace Catch {
 
     bool startsWith( std::string const& s, std::string const& prefix ) {
-        return s.size() >= prefix.size() && s.substr( 0, prefix.size() ) == prefix;
+        return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
+    }
+    bool startsWith( std::string const& s, char prefix ) {
+        return !s.empty() && s[0] == prefix;
     }
     bool endsWith( std::string const& s, std::string const& suffix ) {
-        return s.size() >= suffix.size() && s.substr( s.size()-suffix.size(), suffix.size() ) == suffix;
+        return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
+    }
+    bool endsWith( std::string const& s, char suffix ) {
+        return !s.empty() && s[s.size()-1] == suffix;
     }
     bool contains( std::string const& s, std::string const& infix ) {
         return s.find( infix ) != std::string::npos;
     }
     char toLowerCh(char c) {
-        return static_cast<char>( ::tolower( c ) );
+        return static_cast<char>( std::tolower( c ) );
     }
     void toLowerInPlace( std::string& s ) {
         std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
@@ -7829,7 +8396,7 @@ namespace Catch {
         std::string::size_type start = str.find_first_not_of( whitespaceChars );
         std::string::size_type end = str.find_last_not_of( whitespaceChars );
 
-        return start != std::string::npos ? str.substr( start, 1+end-start ) : "";
+        return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
     }
 
     bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
@@ -7852,29 +8419,25 @@ namespace Catch {
     {}
 
     std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
-        os << pluraliser.m_count << " " << pluraliser.m_label;
+        os << pluraliser.m_count << ' ' << pluraliser.m_label;
         if( pluraliser.m_count != 1 )
-            os << "s";
+            os << 's';
         return os;
     }
 
-    SourceLineInfo::SourceLineInfo() : line( 0 ){}
+    SourceLineInfo::SourceLineInfo() : file(""), line( 0 ){}
     SourceLineInfo::SourceLineInfo( char const* _file, std::size_t _line )
     :   file( _file ),
         line( _line )
     {}
-    SourceLineInfo::SourceLineInfo( SourceLineInfo const& other )
-    :   file( other.file ),
-        line( other.line )
-    {}
     bool SourceLineInfo::empty() const {
-        return file.empty();
+        return file[0] == '\0';
     }
     bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const {
-        return line == other.line && file == other.file;
+        return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
     }
     bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const {
-        return line < other.line || ( line == other.line  && file < other.file );
+        return line < other.line || ( line == other.line && (std::strcmp(file, other.file) < 0));
     }
 
     void seedRng( IConfig const& config ) {
@@ -7887,16 +8450,16 @@ namespace Catch {
 
     std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
 #ifndef __GNUG__
-        os << info.file << "(" << info.line << ")";
+        os << info.file << '(' << info.line << ')';
 #else
-        os << info.file << ":" << info.line;
+        os << info.file << ':' << info.line;
 #endif
         return os;
     }
 
     void throwLogicError( std::string const& message, SourceLineInfo const& locationInfo ) {
         std::ostringstream oss;
-        oss << locationInfo << ": Internal Catch error: '" << message << "'";
+        oss << locationInfo << ": Internal Catch error: '" << message << '\'';
         if( alwaysTrue() )
             throw std::logic_error( oss.str() );
     }
@@ -7943,8 +8506,6 @@ namespace Catch {
 // #included from: catch_debugger.hpp
 #define TWOBLUECUBES_CATCH_DEBUGGER_HPP_INCLUDED
 
-#include <iostream>
-
 #ifdef CATCH_PLATFORM_MAC
 
     #include <assert.h>
@@ -7993,6 +8554,33 @@ namespace Catch {
         }
     } // namespace Catch
 
+#elif defined(CATCH_PLATFORM_LINUX)
+    #include <fstream>
+    #include <string>
+
+    namespace Catch{
+        // The standard POSIX way of detecting a debugger is to attempt to
+        // ptrace() the process, but this needs to be done from a child and not
+        // this process itself to still allow attaching to this process later
+        // if wanted, so is rather heavy. Under Linux we have the PID of the
+        // "debugger" (which doesn't need to be gdb, of course, it could also
+        // be strace, for example) in /proc/$PID/status, so just get it from
+        // there instead.
+        bool isDebuggerActive(){
+            std::ifstream in("/proc/self/status");
+            for( std::string line; std::getline(in, line); ) {
+                static const int PREFIX_LEN = 11;
+                if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
+                    // We're traced if the PID is not 0 and no other PID starts
+                    // with 0 digit, so it's enough to check for just a single
+                    // character.
+                    return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
+                }
+            }
+
+            return false;
+        }
+    } // namespace Catch
 #elif defined(_MSC_VER)
     extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
     namespace Catch {
@@ -8014,7 +8602,7 @@ namespace Catch {
 #endif // Platform
 
 #ifdef CATCH_PLATFORM_WINDOWS
-    extern "C" __declspec(dllimport) void __stdcall OutputDebugStringA( const char* );
+
     namespace Catch {
         void writeToDebugConsole( std::string const& text ) {
             ::OutputDebugStringA( text.c_str() );
@@ -8090,7 +8678,7 @@ std::string toString( std::string const& value ) {
             }
         }
     }
-    return "\"" + s + "\"";
+    return '"' + s + '"';
 }
 std::string toString( std::wstring const& value ) {
 
@@ -8111,19 +8699,19 @@ std::string toString( char* const value ) {
 
 std::string toString( const wchar_t* const value )
 {
-	return value ? Catch::toString( std::wstring(value) ) : std::string( "{null string}" );
+    return value ? Catch::toString( std::wstring(value) ) : std::string( "{null string}" );
 }
 
 std::string toString( wchar_t* const value )
 {
-	return Catch::toString( static_cast<const wchar_t*>( value ) );
+    return Catch::toString( static_cast<const wchar_t*>( value ) );
 }
 
 std::string toString( int value ) {
     std::ostringstream oss;
     oss << value;
     if( value > Detail::hexThreshold )
-        oss << " (0x" << std::hex << value << ")";
+        oss << " (0x" << std::hex << value << ')';
     return oss.str();
 }
 
@@ -8131,7 +8719,7 @@ std::string toString( unsigned long value ) {
     std::ostringstream oss;
     oss << value;
     if( value > Detail::hexThreshold )
-        oss << " (0x" << std::hex << value << ")";
+        oss << " (0x" << std::hex << value << ')';
     return oss.str();
 }
 
@@ -8159,7 +8747,7 @@ std::string toString( const double value ) {
     return fpToString( value, 10 );
 }
 std::string toString( const float value ) {
-    return fpToString( value, 5 ) + "f";
+    return fpToString( value, 5 ) + 'f';
 }
 
 std::string toString( bool value ) {
@@ -8167,9 +8755,19 @@ std::string toString( bool value ) {
 }
 
 std::string toString( char value ) {
-    return value < ' '
-        ? toString( static_cast<unsigned int>( value ) )
-        : Detail::makeString( value );
+    if ( value == '\r' )
+        return "'\\r'";
+    if ( value == '\f' )
+        return "'\\f'";
+    if ( value == '\n' )
+        return "'\\n'";
+    if ( value == '\t' )
+        return "'\\t'";
+    if ( '\0' <= value && value < ' ' )
+        return toString( static_cast<unsigned int>( value ) );
+    char chstr[] = "' '";
+    chstr[1] = value;
+    return chstr;
 }
 
 std::string toString( signed char value ) {
@@ -8185,14 +8783,14 @@ std::string toString( long long value ) {
     std::ostringstream oss;
     oss << value;
     if( value > Detail::hexThreshold )
-        oss << " (0x" << std::hex << value << ")";
+        oss << " (0x" << std::hex << value << ')';
     return oss.str();
 }
 std::string toString( unsigned long long value ) {
     std::ostringstream oss;
     oss << value;
     if( value > Detail::hexThreshold )
-        oss << " (0x" << std::hex << value << ")";
+        oss << " (0x" << std::hex << value << ')';
     return oss.str();
 }
 #endif
@@ -8249,22 +8847,10 @@ namespace Catch {
         m_data.resultType = result ? ResultWas::Ok : ResultWas::ExpressionFailed;
         return *this;
     }
-    ResultBuilder& ResultBuilder::setLhs( std::string const& lhs ) {
-        m_exprComponents.lhs = lhs;
-        return *this;
-    }
-    ResultBuilder& ResultBuilder::setRhs( std::string const& rhs ) {
-        m_exprComponents.rhs = rhs;
-        return *this;
-    }
-    ResultBuilder& ResultBuilder::setOp( std::string const& op ) {
-        m_exprComponents.op = op;
-        return *this;
-    }
 
-    void ResultBuilder::endExpression() {
-        m_exprComponents.testFalse = isFalseTest( m_assertionInfo.resultDisposition );
-        captureExpression();
+    void ResultBuilder::endExpression( DecomposedExpression const& expr ) {
+        AssertionResult result = build( expr );
+        handleResult( result );
     }
 
     void ResultBuilder::useActiveException( ResultDisposition::Flags resultDisposition ) {
@@ -8277,16 +8863,17 @@ namespace Catch {
         setResultType( resultType );
         captureExpression();
     }
+
     void ResultBuilder::captureExpectedException( std::string const& expectedMessage ) {
         if( expectedMessage.empty() )
-            captureExpectedException( Matchers::Impl::Generic::AllOf<std::string>() );
+            captureExpectedException( Matchers::Impl::MatchAllOf<std::string>() );
         else
             captureExpectedException( Matchers::Equals( expectedMessage ) );
     }
 
-    void ResultBuilder::captureExpectedException( Matchers::Impl::Matcher<std::string> const& matcher ) {
+    void ResultBuilder::captureExpectedException( Matchers::Impl::MatcherBase<std::string> const& matcher ) {
 
-        assert( m_exprComponents.testFalse == false );
+        assert( !isFalseTest( m_assertionInfo.resultDisposition ) );
         AssertionResultData data = m_data;
         data.resultType = ResultWas::Ok;
         data.reconstructedExpression = m_assertionInfo.capturedExpression;
@@ -8304,6 +8891,7 @@ namespace Catch {
         AssertionResult result = build();
         handleResult( result );
     }
+
     void ResultBuilder::handleResult( AssertionResult const& result )
     {
         getResultCapture().assertionEnded( result );
@@ -8315,7 +8903,17 @@ namespace Catch {
                 m_shouldThrow = true;
         }
     }
+
     void ResultBuilder::react() {
+#if defined(CATCH_CONFIG_FAST_COMPILE)
+        if (m_shouldDebugBreak) {
+            ///////////////////////////////////////////////////////////////////
+            // To inspect the state during test, you need to go one level up the callstack
+            // To go back to the test and change execution, jump over the throw statement
+            ///////////////////////////////////////////////////////////////////
+            CATCH_BREAK_INTO_DEBUGGER();
+        }
+#endif
         if( m_shouldThrow )
             throw Catch::TestFailureException();
     }
@@ -8325,43 +8923,32 @@ namespace Catch {
 
     AssertionResult ResultBuilder::build() const
     {
-        assert( m_data.resultType != ResultWas::Unknown );
+        return build( *this );
+    }
 
+    // CAVEAT: The returned AssertionResult stores a pointer to the argument expr,
+    //         a temporary DecomposedExpression, which in turn holds references to
+    //         operands, possibly temporary as well.
+    //         It should immediately be passed to handleResult; if the expression
+    //         needs to be reported, its string expansion must be composed before
+    //         the temporaries are destroyed.
+    AssertionResult ResultBuilder::build( DecomposedExpression const& expr ) const
+    {
+        assert( m_data.resultType != ResultWas::Unknown );
         AssertionResultData data = m_data;
 
-        // Flip bool results if testFalse is set
-        if( m_exprComponents.testFalse ) {
-            if( data.resultType == ResultWas::Ok )
-                data.resultType = ResultWas::ExpressionFailed;
-            else if( data.resultType == ResultWas::ExpressionFailed )
-                data.resultType = ResultWas::Ok;
+        // Flip bool results if FalseTest flag is set
+        if( isFalseTest( m_assertionInfo.resultDisposition ) ) {
+            data.negate( expr.isBinaryExpression() );
         }
 
         data.message = m_stream.oss.str();
-        data.reconstructedExpression = reconstructExpression();
-        if( m_exprComponents.testFalse ) {
-            if( m_exprComponents.op == "" )
-                data.reconstructedExpression = "!" + data.reconstructedExpression;
-            else
-                data.reconstructedExpression = "!(" + data.reconstructedExpression + ")";
-        }
+        data.decomposedExpression = &expr; // for lazy reconstruction
         return AssertionResult( m_assertionInfo, data );
     }
-    std::string ResultBuilder::reconstructExpression() const {
-        if( m_exprComponents.op == "" )
-            return m_exprComponents.lhs.empty() ? m_assertionInfo.capturedExpression : m_exprComponents.op + m_exprComponents.lhs;
-        else if( m_exprComponents.op == "matches" )
-            return m_exprComponents.lhs + " " + m_exprComponents.rhs;
-        else if( m_exprComponents.op != "!" ) {
-            if( m_exprComponents.lhs.size() + m_exprComponents.rhs.size() < 40 &&
-                m_exprComponents.lhs.find("\n") == std::string::npos &&
-                m_exprComponents.rhs.find("\n") == std::string::npos )
-                return m_exprComponents.lhs + " " + m_exprComponents.op + " " + m_exprComponents.rhs;
-            else
-                return m_exprComponents.lhs + "\n" + m_exprComponents.op + "\n" + m_exprComponents.rhs;
-        }
-        else
-            return "{can't expand - use " + m_assertionInfo.macroName + "_FALSE( " + m_assertionInfo.capturedExpression.substr(1) + " ) instead of " + m_assertionInfo.macroName + "( " + m_assertionInfo.capturedExpression + " ) for better diagnostics}";
+
+    void ResultBuilder::reconstructExpression( std::string& dest ) const {
+        dest = m_assertionInfo.capturedExpression;
     }
 
 } // end namespace Catch
@@ -8390,9 +8977,6 @@ namespace Catch {
 
 } // end namespace Catch
 
-#include <map>
-#include <iostream>
-
 namespace Catch {
 
     TagAliasRegistry::~TagAliasRegistry() {}
@@ -8422,7 +9006,7 @@ namespace Catch {
 
     void TagAliasRegistry::add( char const* alias, char const* tag, SourceLineInfo const& lineInfo ) {
 
-        if( !startsWith( alias, "[@" ) || !endsWith( alias, "]" ) ) {
+        if( !startsWith( alias, "[@" ) || !endsWith( alias, ']' ) ) {
             std::ostringstream oss;
             oss << "error: tag alias, \"" << alias << "\" is not of the form [@alias name].\n" << lineInfo;
             throw std::domain_error( oss.str().c_str() );
@@ -8430,7 +9014,7 @@ namespace Catch {
         if( !m_registry.insert( std::make_pair( alias, TagAlias( tag, lineInfo ) ) ).second ) {
             std::ostringstream oss;
             oss << "error: tag alias, \"" << alias << "\" already registered.\n"
-                << "\tFirst seen at " << find(alias)->lineInfo << "\n"
+                << "\tFirst seen at " << find(alias)->lineInfo << '\n'
                 << "\tRedefined at " << lineInfo;
             throw std::domain_error( oss.str().c_str() );
         }
@@ -8458,6 +9042,86 @@ namespace Catch {
 
 } // end namespace Catch
 
+// #included from: catch_matchers_string.hpp
+
+namespace Catch {
+namespace Matchers {
+
+    namespace StdString {
+
+        CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
+        :   m_caseSensitivity( caseSensitivity ),
+            m_str( adjustString( str ) )
+        {}
+        std::string CasedString::adjustString( std::string const& str ) const {
+            return m_caseSensitivity == CaseSensitive::No
+                   ? toLower( str )
+                   : str;
+        }
+        std::string CasedString::caseSensitivitySuffix() const {
+            return m_caseSensitivity == CaseSensitive::No
+                   ? " (case insensitive)"
+                   : std::string();
+        }
+
+        StringMatcherBase::StringMatcherBase( std::string operation, CasedString const& comparator )
+        : m_comparator( comparator ),
+          m_operation( operation ) {
+        }
+
+        std::string StringMatcherBase::describe() const {
+            std::string description;
+            description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
+                                        m_comparator.caseSensitivitySuffix().size());
+            description += m_operation;
+            description += ": \"";
+            description += m_comparator.m_str;
+            description += "\"";
+            description += m_comparator.caseSensitivitySuffix();
+            return description;
+        }
+
+        EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
+
+        bool EqualsMatcher::match( std::string const& source ) const {
+            return m_comparator.adjustString( source ) == m_comparator.m_str;
+        }
+
+        ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
+
+        bool ContainsMatcher::match( std::string const& source ) const {
+            return contains( m_comparator.adjustString( source ), m_comparator.m_str );
+        }
+
+        StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
+
+        bool StartsWithMatcher::match( std::string const& source ) const {
+            return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
+        }
+
+        EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
+
+        bool EndsWithMatcher::match( std::string const& source ) const {
+            return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
+        }
+
+    } // namespace StdString
+
+    StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
+        return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
+    }
+    StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
+        return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
+    }
+    StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
+        return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
+    }
+    StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
+        return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
+    }
+
+} // namespace Matchers
+} // namespace Catch
 // #included from: ../reporters/catch_reporter_multi.hpp
 #define TWOBLUECUBES_CATCH_REPORTER_MULTI_HPP_INCLUDED
 
@@ -8601,6 +9265,7 @@ Ptr<IStreamingReporter> addReporter( Ptr<IStreamingReporter> const& existingRepo
 #define TWOBLUECUBES_CATCH_REPORTER_BASES_HPP_INCLUDED
 
 #include <cstring>
+#include <assert.h>
 
 namespace Catch {
 
@@ -8698,12 +9363,12 @@ namespace Catch {
 
         struct BySectionInfo {
             BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
-			BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
+            BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
             bool operator() ( Ptr<SectionNode> const& node ) const {
                 return node->stats.sectionInfo.lineInfo == m_other.lineInfo;
             }
         private:
-			void operator=( BySectionInfo const& );
+            void operator=( BySectionInfo const& );
             SectionInfo const& m_other;
         };
 
@@ -8759,6 +9424,12 @@ namespace Catch {
             assert( !m_sectionStack.empty() );
             SectionNode& sectionNode = *m_sectionStack.back();
             sectionNode.assertions.push_back( assertionStats );
+            // AssertionResult holds a pointer to a temporary DecomposedExpression,
+            // which getExpandedExpression() calls to build the expression string.
+            // Our section stack copy of the assertionResult will likely outlive the
+            // temporary, so it must be expanded or discarded now to avoid calling
+            // a destroyed object later.
+            prepareExpandedExpression( sectionNode.assertions.back().assertionResult );
             return true;
         }
         virtual void sectionEnded( SectionStats const& sectionStats ) CATCH_OVERRIDE {
@@ -8793,6 +9464,13 @@ namespace Catch {
 
         virtual void skipTest( TestCaseInfo const& ) CATCH_OVERRIDE {}
 
+        virtual void prepareExpandedExpression( AssertionResult& result ) const {
+            if( result.isOk() )
+                result.discardDecomposedExpression();
+            else
+                result.expandDecomposedExpression();
+        }
+
         Ptr<IConfig const> m_config;
         std::ostream& stream;
         std::vector<AssertionStats> m_assertions;
@@ -8813,7 +9491,7 @@ namespace Catch {
     char const* getLineOfChars() {
         static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
         if( !*line ) {
-            memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
+            std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
             line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
         }
         return line;
@@ -8898,7 +9576,7 @@ namespace Catch {
                 return new T( config );
             }
             virtual std::string getDescription() const {
-                return "";
+                return std::string();
             }
         };
 
@@ -8967,8 +9645,11 @@ namespace Catch {
                     default:
                         // Escape control chars - based on contribution by @espenalb in PR #465 and
                         // by @mrpi PR #588
-                        if ( ( c < '\x09' ) || ( c > '\x0D' && c < '\x20') || c=='\x7F' )
-                            os << "&#x" << std::uppercase << std::hex << std::setfill('0') << std::setw(2) << static_cast<int>( c ) << ';';
+                        if ( ( c >= 0 && c < '\x09' ) || ( c > '\x0D' && c < '\x20') || c=='\x7F' ) {
+                            // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
+                            os << "\\x" << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
+                               << static_cast<int>( c );
+                        }
                         else
                             os << c;
                 }
@@ -9022,20 +9703,17 @@ namespace Catch {
         XmlWriter()
         :   m_tagIsOpen( false ),
             m_needsNewline( false ),
-            m_os( &Catch::cout() )
+            m_os( Catch::cout() )
         {
-            // We encode control characters, which requires
-            // XML 1.1
-            // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
-            *m_os << "<?xml version=\"1.1\" encoding=\"UTF-8\"?>\n";
+            writeDeclaration();
         }
 
         XmlWriter( std::ostream& os )
         :   m_tagIsOpen( false ),
             m_needsNewline( false ),
-            m_os( &os )
+            m_os( os )
         {
-            *m_os << "<?xml version=\"1.1\" encoding=\"UTF-8\"?>\n";
+            writeDeclaration();
         }
 
         ~XmlWriter() {
@@ -9046,7 +9724,7 @@ namespace Catch {
         XmlWriter& startElement( std::string const& name ) {
             ensureTagClosed();
             newlineIfNecessary();
-            stream() << m_indent << "<" << name;
+            m_os << m_indent << '<' << name;
             m_tags.push_back( name );
             m_indent += "  ";
             m_tagIsOpen = true;
@@ -9063,24 +9741,25 @@ namespace Catch {
             newlineIfNecessary();
             m_indent = m_indent.substr( 0, m_indent.size()-2 );
             if( m_tagIsOpen ) {
-                stream() << "/>\n";
+                m_os << "/>";
                 m_tagIsOpen = false;
             }
             else {
-                stream() << m_indent << "</" << m_tags.back() << ">\n";
+                m_os << m_indent << "</" << m_tags.back() << ">";
             }
+            m_os << std::endl;
             m_tags.pop_back();
             return *this;
         }
 
         XmlWriter& writeAttribute( std::string const& name, std::string const& attribute ) {
             if( !name.empty() && !attribute.empty() )
-                stream() << " " << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << "\"";
+                m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
             return *this;
         }
 
         XmlWriter& writeAttribute( std::string const& name, bool attribute ) {
-            stream() << " " << name << "=\"" << ( attribute ? "true" : "false" ) << "\"";
+            m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
             return *this;
         }
 
@@ -9096,8 +9775,8 @@ namespace Catch {
                 bool tagWasOpen = m_tagIsOpen;
                 ensureTagClosed();
                 if( tagWasOpen && indent )
-                    stream() << m_indent;
-                stream() << XmlEncode( text );
+                    m_os << m_indent;
+                m_os << XmlEncode( text );
                 m_needsNewline = true;
             }
             return *this;
@@ -9105,39 +9784,39 @@ namespace Catch {
 
         XmlWriter& writeComment( std::string const& text ) {
             ensureTagClosed();
-            stream() << m_indent << "<!--" << text << "-->";
+            m_os << m_indent << "<!--" << text << "-->";
             m_needsNewline = true;
             return *this;
         }
 
+        void writeStylesheetRef( std::string const& url ) {
+            m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
+        }
+
         XmlWriter& writeBlankLine() {
             ensureTagClosed();
-            stream() << "\n";
+            m_os << '\n';
             return *this;
         }
 
-        void setStream( std::ostream& os ) {
-            m_os = &os;
+        void ensureTagClosed() {
+            if( m_tagIsOpen ) {
+                m_os << ">" << std::endl;
+                m_tagIsOpen = false;
+            }
         }
 
     private:
         XmlWriter( XmlWriter const& );
         void operator=( XmlWriter const& );
 
-        std::ostream& stream() {
-            return *m_os;
-        }
-
-        void ensureTagClosed() {
-            if( m_tagIsOpen ) {
-                stream() << ">\n";
-                m_tagIsOpen = false;
-            }
+        void writeDeclaration() {
+            m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
         }
 
         void newlineIfNecessary() {
             if( m_needsNewline ) {
-                stream() << "\n";
+                m_os << std::endl;
                 m_needsNewline = false;
             }
         }
@@ -9146,7 +9825,7 @@ namespace Catch {
         bool m_needsNewline;
         std::vector<std::string> m_tags;
         std::string m_indent;
-        std::ostream* m_os;
+        std::ostream& m_os;
     };
 
 }
@@ -9182,6 +9861,16 @@ namespace Catch {
             return "Reports test results as an XML document";
         }
 
+        virtual std::string getStylesheetRef() const {
+            return std::string();
+        }
+
+        void writeSourceInfo( SourceLineInfo const& sourceInfo ) {
+            m_xml
+                .writeAttribute( "filename", sourceInfo.file )
+                .writeAttribute( "line", sourceInfo.line );
+        }
+
     public: // StreamingReporterBase
 
         virtual void noMatchingTestCases( std::string const& s ) CATCH_OVERRIDE {
@@ -9190,6 +9879,9 @@ namespace Catch {
 
         virtual void testRunStarting( TestRunInfo const& testInfo ) CATCH_OVERRIDE {
             StreamingReporterBase::testRunStarting( testInfo );
+            std::string stylesheetRef = getStylesheetRef();
+            if( !stylesheetRef.empty() )
+                m_xml.writeStylesheetRef( stylesheetRef );
             m_xml.startElement( "Catch" );
             if( !m_config->name().empty() )
                 m_xml.writeAttribute( "name", m_config->name() );
@@ -9203,10 +9895,16 @@ namespace Catch {
 
         virtual void testCaseStarting( TestCaseInfo const& testInfo ) CATCH_OVERRIDE {
             StreamingReporterBase::testCaseStarting(testInfo);
-            m_xml.startElement( "TestCase" ).writeAttribute( "name", testInfo.name );
+            m_xml.startElement( "TestCase" )
+                .writeAttribute( "name", trim( testInfo.name ) )
+                .writeAttribute( "description", testInfo.description )
+                .writeAttribute( "tags", testInfo.tagsAsString );
+
+            writeSourceInfo( testInfo.lineInfo );
 
             if ( m_config->showDurations() == ShowDurations::Always )
                 m_testCaseTimer.start();
+            m_xml.ensureTagClosed();
         }
 
         virtual void sectionStarting( SectionInfo const& sectionInfo ) CATCH_OVERRIDE {
@@ -9215,6 +9913,8 @@ namespace Catch {
                 m_xml.startElement( "Section" )
                     .writeAttribute( "name", trim( sectionInfo.name ) )
                     .writeAttribute( "description", sectionInfo.description );
+                writeSourceInfo( sectionInfo.lineInfo );
+                m_xml.ensureTagClosed();
             }
         }
 
@@ -9246,9 +9946,9 @@ namespace Catch {
             if( assertionResult.hasExpression() ) {
                 m_xml.startElement( "Expression" )
                     .writeAttribute( "success", assertionResult.succeeded() )
-					.writeAttribute( "type", assertionResult.getTestMacroName() )
-                    .writeAttribute( "filename", assertionResult.getSourceInfo().file )
-                    .writeAttribute( "line", assertionResult.getSourceInfo().line );
+                    .writeAttribute( "type", assertionResult.getTestMacroName() );
+
+                writeSourceInfo( assertionResult.getSourceInfo() );
 
                 m_xml.scopedElement( "Original" )
                     .writeText( assertionResult.getExpression() );
@@ -9259,16 +9959,16 @@ namespace Catch {
             // And... Print a result applicable to each result type.
             switch( assertionResult.getResultType() ) {
                 case ResultWas::ThrewException:
-                    m_xml.scopedElement( "Exception" )
-                        .writeAttribute( "filename", assertionResult.getSourceInfo().file )
-                        .writeAttribute( "line", assertionResult.getSourceInfo().line )
-                        .writeText( assertionResult.getMessage() );
+                    m_xml.startElement( "Exception" );
+                    writeSourceInfo( assertionResult.getSourceInfo() );
+                    m_xml.writeText( assertionResult.getMessage() );
+                    m_xml.endElement();
                     break;
                 case ResultWas::FatalErrorCondition:
-                    m_xml.scopedElement( "FatalErrorCondition" )
-                        .writeAttribute( "filename", assertionResult.getSourceInfo().file )
-                        .writeAttribute( "line", assertionResult.getSourceInfo().line )
-                        .writeText( assertionResult.getMessage() );
+                    m_xml.startElement( "FatalErrorCondition" );
+                    writeSourceInfo( assertionResult.getSourceInfo() );
+                    m_xml.writeText( assertionResult.getMessage() );
+                    m_xml.endElement();
                     break;
                 case ResultWas::Info:
                     m_xml.scopedElement( "Info" )
@@ -9278,8 +9978,10 @@ namespace Catch {
                     // Warning will already have been written
                     break;
                 case ResultWas::ExplicitFailure:
-                    m_xml.scopedElement( "Failure" )
-                        .writeText( assertionResult.getMessage() );
+                    m_xml.startElement( "Failure" );
+                    writeSourceInfo( assertionResult.getSourceInfo() );
+                    m_xml.writeText( assertionResult.getMessage() );
+                    m_xml.endElement();
                     break;
                 default:
                     break;
@@ -9314,6 +10016,11 @@ namespace Catch {
             if ( m_config->showDurations() == ShowDurations::Always )
                 e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
 
+            if( !testCaseStats.stdOut.empty() )
+                m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false );
+            if( !testCaseStats.stdErr.empty() )
+                m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false );
+
             m_xml.endElement();
         }
 
@@ -9353,6 +10060,35 @@ namespace Catch {
 
 namespace Catch {
 
+    namespace {
+        std::string getCurrentTimestamp() {
+            // Beware, this is not reentrant because of backward compatibility issues
+            // Also, UTC only, again because of backward compatibility (%z is C++11)
+            time_t rawtime;
+            std::time(&rawtime);
+            const size_t timeStampSize = sizeof("2017-01-16T17:06:45Z");
+
+#ifdef _MSC_VER
+            std::tm timeInfo = {};
+            gmtime_s(&timeInfo, &rawtime);
+#else
+            std::tm* timeInfo;
+            timeInfo = std::gmtime(&rawtime);
+#endif
+
+            char timeStamp[timeStampSize];
+            const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
+
+#ifdef _MSC_VER
+            std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
+#else
+            std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
+#endif
+            return std::string(timeStamp);
+        }
+
+    }
+
     class JunitReporter : public CumulativeReporterBase {
     public:
         JunitReporter( ReporterConfig const& _config )
@@ -9417,7 +10153,7 @@ namespace Catch {
                 xml.writeAttribute( "time", "" );
             else
                 xml.writeAttribute( "time", suiteTime );
-            xml.writeAttribute( "timestamp", "tbd" ); // !TBD
+            xml.writeAttribute( "timestamp", getCurrentTimestamp() );
 
             // Write test cases
             for( TestGroupNode::ChildNodes::const_iterator
@@ -9452,7 +10188,7 @@ namespace Catch {
                             SectionNode const& sectionNode ) {
             std::string name = trim( sectionNode.stats.sectionInfo.name );
             if( !rootName.empty() )
-                name = rootName + "/" + name;
+                name = rootName + '/' + name;
 
             if( !sectionNode.assertions.empty() ||
                 !sectionNode.stdOut.empty() ||
@@ -9530,14 +10266,14 @@ namespace Catch {
 
                 std::ostringstream oss;
                 if( !result.getMessage().empty() )
-                    oss << result.getMessage() << "\n";
+                    oss << result.getMessage() << '\n';
                 for( std::vector<MessageInfo>::const_iterator
                         it = stats.infoMessages.begin(),
                         itEnd = stats.infoMessages.end();
                             it != itEnd;
                             ++it )
                     if( it->type == ResultWas::Info )
-                        oss << it->message << "\n";
+                        oss << it->message << '\n';
 
                 oss << "at " << result.getSourceInfo();
                 xml.writeText( oss.str(), false );
@@ -9558,8 +10294,30 @@ namespace Catch {
 // #included from: ../reporters/catch_reporter_console.hpp
 #define TWOBLUECUBES_CATCH_REPORTER_CONSOLE_HPP_INCLUDED
 
+#include <cfloat>
+#include <cstdio>
+
 namespace Catch {
 
+    namespace {
+        // Because formatting using c++ streams is stateful, drop down to C is required
+        // Alternatively we could use stringstream, but its performance is... not good.
+        std::string getFormattedDuration( double duration ) {
+            // Max exponent + 1 is required to represent the whole part
+            // + 1 for decimal point
+            // + 3 for the 3 decimal places
+            // + 1 for null terminator
+            const size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
+            char buffer[maxDoubleSize];
+#ifdef _MSC_VER
+            sprintf_s(buffer, "%.3f", duration);
+#else
+            sprintf(buffer, "%.3f", duration);
+#endif
+            return std::string(buffer);
+        }
+    }
+
     struct ConsoleReporter : StreamingReporterBase {
         ConsoleReporter( ReporterConfig const& _config )
         :   StreamingReporterBase( _config ),
@@ -9572,7 +10330,7 @@ namespace Catch {
         }
 
         virtual void noMatchingTestCases( std::string const& spec ) CATCH_OVERRIDE {
-            stream << "No test cases matched '" << spec << "'" << std::endl;
+            stream << "No test cases matched '" << spec << '\'' << std::endl;
         }
 
         virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE {
@@ -9612,15 +10370,12 @@ namespace Catch {
                     stream << "\nNo assertions in test case";
                 stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
             }
+            if( m_config->showDurations() == ShowDurations::Always ) {
+                stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
+            }
             if( m_headerPrinted ) {
-                if( m_config->showDurations() == ShowDurations::Always )
-                    stream << "Completed in " << _sectionStats.durationInSeconds << "s" << std::endl;
                 m_headerPrinted = false;
             }
-            else {
-                if( m_config->showDurations() == ShowDurations::Always )
-                    stream << _sectionStats.sectionInfo.name << " completed in " << _sectionStats.durationInSeconds << "s" << std::endl;
-            }
             StreamingReporterBase::sectionEnded( _sectionStats );
         }
 
@@ -9633,7 +10388,7 @@ namespace Catch {
                 printSummaryDivider();
                 stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
                 printTotals( _testGroupStats.totals );
-                stream << "\n" << std::endl;
+                stream << '\n' << std::endl;
             }
             StreamingReporterBase::testGroupEnded( _testGroupStats );
         }
@@ -9725,13 +10480,13 @@ namespace Catch {
                 printSourceInfo();
                 if( stats.totals.assertions.total() > 0 ) {
                     if( result.isOk() )
-                        stream << "\n";
+                        stream << '\n';
                     printResultType();
                     printOriginalExpression();
                     printReconstructedExpression();
                 }
                 else {
-                    stream << "\n";
+                    stream << '\n';
                 }
                 printMessage();
             }
@@ -9748,25 +10503,25 @@ namespace Catch {
                     Colour colourGuard( Colour::OriginalExpression );
                     stream  << "  ";
                     stream << result.getExpressionInMacro();
-                    stream << "\n";
+                    stream << '\n';
                 }
             }
             void printReconstructedExpression() const {
                 if( result.hasExpandedExpression() ) {
                     stream << "with expansion:\n";
                     Colour colourGuard( Colour::ReconstructedExpression );
-                    stream << Text( result.getExpandedExpression(), TextAttributes().setIndent(2) ) << "\n";
+                    stream << Text( result.getExpandedExpression(), TextAttributes().setIndent(2) ) << '\n';
                 }
             }
             void printMessage() const {
                 if( !messageLabel.empty() )
-                    stream << messageLabel << ":" << "\n";
+                    stream << messageLabel << ':' << '\n';
                 for( std::vector<MessageInfo>::const_iterator it = messages.begin(), itEnd = messages.end();
                         it != itEnd;
                         ++it ) {
                     // If this assertion is a warning ignore any INFO messages
                     if( printInfoMessages || it->type != ResultWas::Info )
-                        stream << Text( it->message, TextAttributes().setIndent(2) ) << "\n";
+                        stream << Text( it->message, TextAttributes().setIndent(2) ) << '\n';
                 }
             }
             void printSourceInfo() const {
@@ -9798,7 +10553,7 @@ namespace Catch {
             }
         }
         void lazyPrintRunInfo() {
-            stream  << "\n" << getLineOfChars<'~'>() << "\n";
+            stream  << '\n' << getLineOfChars<'~'>() << '\n';
             Colour colour( Colour::SecondaryText );
             stream  << currentTestRunInfo->name
                     << " is a Catch v"  << libraryVersion << " host application.\n"
@@ -9829,22 +10584,22 @@ namespace Catch {
                     printHeaderString( it->name, 2 );
             }
 
-            SourceLineInfo lineInfo = m_sectionStack.front().lineInfo;
+            SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
 
             if( !lineInfo.empty() ){
-                stream << getLineOfChars<'-'>() << "\n";
+                stream << getLineOfChars<'-'>() << '\n';
                 Colour colourGuard( Colour::FileName );
-                stream << lineInfo << "\n";
+                stream << lineInfo << '\n';
             }
-            stream << getLineOfChars<'.'>() << "\n" << std::endl;
+            stream << getLineOfChars<'.'>() << '\n' << std::endl;
         }
 
         void printClosedHeader( std::string const& _name ) {
             printOpenHeader( _name );
-            stream << getLineOfChars<'.'>() << "\n";
+            stream << getLineOfChars<'.'>() << '\n';
         }
         void printOpenHeader( std::string const& _name ) {
-            stream  << getLineOfChars<'-'>() << "\n";
+            stream  << getLineOfChars<'-'>() << '\n';
             {
                 Colour colourGuard( Colour::Headers );
                 printHeaderString( _name );
@@ -9861,7 +10616,7 @@ namespace Catch {
                 i = 0;
             stream << Text( _string, TextAttributes()
                                         .setIndent( indent+i)
-                                        .setInitialIndent( indent ) ) << "\n";
+                                        .setInitialIndent( indent ) ) << '\n';
         }
 
         struct SummaryColumn {
@@ -9876,9 +10631,9 @@ namespace Catch {
                 std::string row = oss.str();
                 for( std::vector<std::string>::iterator it = rows.begin(); it != rows.end(); ++it ) {
                     while( it->size() < row.size() )
-                        *it = " " + *it;
+                        *it = ' ' + *it;
                     while( it->size() > row.size() )
-                        row = " " + row;
+                        row = ' ' + row;
                 }
                 rows.push_back( row );
                 return *this;
@@ -9898,8 +10653,8 @@ namespace Catch {
                 stream << Colour( Colour::ResultSuccess ) << "All tests passed";
                 stream << " ("
                         << pluralise( totals.assertions.passed, "assertion" ) << " in "
-                        << pluralise( totals.testCases.passed, "test case" ) << ")"
-                        << "\n";
+                        << pluralise( totals.testCases.passed, "test case" ) << ')'
+                        << '\n';
             }
             else {
 
@@ -9934,10 +10689,10 @@ namespace Catch {
                 else if( value != "0" ) {
                     stream  << Colour( Colour::LightGrey ) << " | ";
                     stream  << Colour( it->colour )
-                            << value << " " << it->label;
+                            << value << ' ' << it->label;
                 }
             }
-            stream << "\n";
+            stream << '\n';
         }
 
         static std::size_t makeRatio( std::size_t number, std::size_t total ) {
@@ -9973,10 +10728,10 @@ namespace Catch {
             else {
                 stream << Colour( Colour::Warning ) << std::string( CATCH_CONFIG_CONSOLE_WIDTH-1, '=' );
             }
-            stream << "\n";
+            stream << '\n';
         }
         void printSummaryDivider() {
-            stream << getLineOfChars<'-'>() << "\n";
+            stream << getLineOfChars<'-'>() << '\n';
         }
 
     private:
@@ -10011,7 +10766,7 @@ namespace Catch {
         }
 
         virtual void noMatchingTestCases( std::string const& spec ) {
-            stream << "No test cases matched '" << spec << "'" << std::endl;
+            stream << "No test cases matched '" << spec << '\'' << std::endl;
         }
 
         virtual void assertionStarting( AssertionInfo const& ) {
@@ -10038,7 +10793,7 @@ namespace Catch {
 
         virtual void testRunEnded( TestRunStats const& _testRunStats ) {
             printTotals( _testRunStats.totals );
-            stream << "\n" << std::endl;
+            stream << '\n' << std::endl;
             StreamingReporterBase::testRunEnded( _testRunStats );
         }
 
@@ -10138,26 +10893,26 @@ namespace Catch {
 
             void printSourceInfo() const {
                 Colour colourGuard( Colour::FileName );
-                stream << result.getSourceInfo() << ":";
+                stream << result.getSourceInfo() << ':';
             }
 
             void printResultType( Colour::Code colour, std::string passOrFail ) const {
                 if( !passOrFail.empty() ) {
                     {
                         Colour colourGuard( colour );
-                        stream << " " << passOrFail;
+                        stream << ' ' << passOrFail;
                     }
-                    stream << ":";
+                    stream << ':';
                 }
             }
 
             void printIssue( std::string issue ) const {
-                stream << " " << issue;
+                stream << ' ' << issue;
             }
 
             void printExpressionWas() {
                 if( result.hasExpression() ) {
-                    stream << ";";
+                    stream << ';';
                     {
                         Colour colour( dimColour() );
                         stream << " expression was:";
@@ -10168,7 +10923,7 @@ namespace Catch {
 
             void printOriginalExpression() const {
                 if( result.hasExpression() ) {
-                    stream << " " << result.getExpression();
+                    stream << ' ' << result.getExpression();
                 }
             }
 
@@ -10184,7 +10939,7 @@ namespace Catch {
 
             void printMessage() {
                 if ( itMessage != messages.end() ) {
-                    stream << " '" << itMessage->message << "'";
+                    stream << " '" << itMessage->message << '\'';
                     ++itMessage;
                 }
             }
@@ -10199,13 +10954,13 @@ namespace Catch {
 
                 {
                     Colour colourGuard( colour );
-                    stream << " with " << pluralise( N, "message" ) << ":";
+                    stream << " with " << pluralise( N, "message" ) << ':';
                 }
 
                 for(; itMessage != itEnd; ) {
                     // If this assertion is a warning ignore any INFO messages
                     if( printInfoMessages || itMessage->type != ResultWas::Info ) {
-                        stream << " '" << itMessage->message << "'";
+                        stream << " '" << itMessage->message << '\'';
                         if ( ++itMessage != itEnd ) {
                             Colour colourGuard( dimColour() );
                             stream << " and";
@@ -10231,7 +10986,7 @@ namespace Catch {
         // - green: Passed [both/all] N tests cases with M assertions.
 
         std::string bothOrAll( std::size_t count ) const {
-            return count == 1 ? "" : count == 2 ? "both " : "all " ;
+            return count == 1 ? std::string() : count == 2 ? "both " : "all " ;
         }
 
         void printTotals( const Totals& totals ) const {
@@ -10242,12 +10997,12 @@ namespace Catch {
                 Colour colour( Colour::ResultError );
                 const std::string qualify_assertions_failed =
                     totals.assertions.failed == totals.assertions.total() ?
-                        bothOrAll( totals.assertions.failed ) : "";
+                        bothOrAll( totals.assertions.failed ) : std::string();
                 stream <<
                     "Failed " << bothOrAll( totals.testCases.failed )
                               << pluralise( totals.testCases.failed, "test case"  ) << ", "
                     "failed " << qualify_assertions_failed <<
-                                 pluralise( totals.assertions.failed, "assertion" ) << ".";
+                                 pluralise( totals.assertions.failed, "assertion" ) << '.';
             }
             else if( totals.assertions.total() == 0 ) {
                 stream <<
@@ -10259,14 +11014,14 @@ namespace Catch {
                 Colour colour( Colour::ResultError );
                 stream <<
                     "Failed " << pluralise( totals.testCases.failed, "test case"  ) << ", "
-                    "failed " << pluralise( totals.assertions.failed, "assertion" ) << ".";
+                    "failed " << pluralise( totals.assertions.failed, "assertion" ) << '.';
             }
             else {
                 Colour colour( Colour::ResultSuccess );
                 stream <<
                     "Passed " << bothOrAll( totals.testCases.passed )
                               << pluralise( totals.testCases.passed, "test case"  ) <<
-                    " with "  << pluralise( totals.assertions.passed, "assertion" ) << ".";
+                    " with "  << pluralise( totals.assertions.passed, "assertion" ) << '.';
             }
         }
     };
@@ -10323,11 +11078,6 @@ namespace Catch {
     TestSpec::TagPattern::~TagPattern() {}
     TestSpec::ExcludedPattern::~ExcludedPattern() {}
 
-    Matchers::Impl::StdString::Equals::~Equals() {}
-    Matchers::Impl::StdString::Contains::~Contains() {}
-    Matchers::Impl::StdString::StartsWith::~StartsWith() {}
-    Matchers::Impl::StdString::EndsWith::~EndsWith() {}
-
     void Config::dummy() {}
 
     namespace TestCaseTracking {
@@ -10352,7 +11102,8 @@ namespace Catch {
 
 // Standard C/C++ main entry point
 int main (int argc, char * argv[]) {
-    return Catch::Session().run( argc, argv );
+	int result = Catch::Session().run( argc, argv );
+    return ( result < 0xff ? result : 0xff );
 }
 
 #else // __OBJC__
@@ -10370,7 +11121,7 @@ int main (int argc, char * const argv[]) {
     [pool drain];
 #endif
 
-    return result;
+    return ( result < 0xff ? result : 0xff );
 }
 
 #endif // __OBJC__
@@ -10400,12 +11151,12 @@ int main (int argc, char * const argv[]) {
 #define CATCH_CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECKED_ELSE" )
 #define CATCH_CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, "CATCH_CHECK_NOFAIL" )
 
-#define CATCH_CHECK_THROWS( expr )  INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THROWS" )
+#define CATCH_CHECK_THROWS( expr )  INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, "", "CATCH_CHECK_THROWS" )
 #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THROWS_AS" )
 #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, matcher, "CATCH_CHECK_THROWS_WITH" )
 #define CATCH_CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_NOTHROW" )
 
-#define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THAT" )
+#define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THAT" )
 #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_THAT" )
 
 #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( msg, "CATCH_INFO" )
diff --git a/test/t/area/test_assembler.cpp b/test/t/area/test_assembler.cpp
new file mode 100644
index 0000000..e25ad0f
--- /dev/null
+++ b/test/t/area/test_assembler.cpp
@@ -0,0 +1,143 @@
+#include "catch.hpp"
+
+#include <osmium/area/assembler.hpp>
+#include <osmium/builder/attr.hpp>
+#include <osmium/memory/buffer.hpp>
+#include <osmium/osm/area.hpp>
+
+using namespace osmium::builder::attr;
+
+TEST_CASE("Build area from way") {
+    osmium::memory::Buffer buffer{10240};
+
+    const auto wpos = osmium::builder::add_way(buffer,
+        _id(1),
+        _nodes({
+            {1, {1.0, 1.0}},
+            {2, {1.0, 2.0}},
+            {3, {2.0, 2.0}},
+            {4, {2.0, 1.0}},
+            {1, {1.0, 1.0}}
+        })
+    );
+
+    osmium::area::AssemblerConfig config;
+    osmium::area::Assembler assembler{config};
+
+    osmium::memory::Buffer area_buffer{10240};
+    REQUIRE(assembler(buffer.get<osmium::Way>(wpos), area_buffer));
+
+    const auto& area = area_buffer.get<osmium::Area>(0);
+    REQUIRE(area.from_way());
+    REQUIRE(area.id() == 2);
+
+    const auto it = area.outer_rings().begin();
+    REQUIRE(it != area.outer_rings().end());
+    REQUIRE(it->size() == 5);
+
+    const auto& s = assembler.stats();
+    REQUIRE(s.area_simple_case == 1);
+    REQUIRE(s.from_ways == 1);
+    REQUIRE(s.nodes == 4);
+    REQUIRE(s.duplicate_nodes == 0);
+    REQUIRE(s.invalid_locations == 0);
+}
+
+TEST_CASE("Build area from way with duplicate nodes") {
+    osmium::memory::Buffer buffer{10240};
+
+    const auto wpos = osmium::builder::add_way(buffer,
+        _id(1),
+        _nodes({
+            {1, {1.0, 1.0}},
+            {2, {1.0, 2.0}},
+            {3, {2.0, 2.0}},
+            {3, {2.0, 2.0}},
+            {4, {2.0, 1.0}},
+            {1, {1.0, 1.0}}
+        })
+    );
+
+    osmium::area::AssemblerConfig config;
+    osmium::area::Assembler assembler{config};
+
+    osmium::memory::Buffer area_buffer{10240};
+    REQUIRE(assembler(buffer.get<osmium::Way>(wpos), area_buffer));
+
+    const auto& area = area_buffer.get<osmium::Area>(0);
+    REQUIRE(area.from_way());
+    REQUIRE(area.id() == 2);
+
+    const auto it = area.outer_rings().begin();
+    REQUIRE(it != area.outer_rings().end());
+    REQUIRE(it->size() == 5);
+
+    const auto& s = assembler.stats();
+    REQUIRE(s.area_simple_case == 1);
+    REQUIRE(s.from_ways == 1);
+    REQUIRE(s.nodes == 4);
+    REQUIRE(s.duplicate_nodes == 1);
+    REQUIRE(s.invalid_locations == 0);
+}
+
+TEST_CASE("Build area from way with invalid location") {
+    osmium::memory::Buffer buffer{10240};
+
+    const auto wpos = osmium::builder::add_way(buffer,
+        _id(1),
+        _nodes({
+            {1, {1.0, 1.0}},
+            {2, {1.0, 2.0}},
+            {3},
+            {4, {2.0, 1.0}},
+            {1, {1.0, 1.0}}
+        })
+    );
+
+    osmium::area::AssemblerConfig config;
+    osmium::area::Assembler assembler{config};
+
+    osmium::memory::Buffer area_buffer{10240};
+    REQUIRE_FALSE(assembler(buffer.get<osmium::Way>(wpos), area_buffer));
+
+    const auto& s = assembler.stats();
+    REQUIRE(s.duplicate_nodes == 0);
+    REQUIRE(s.invalid_locations == 1);
+}
+
+TEST_CASE("Build area from way with ignored invalid location") {
+    osmium::memory::Buffer buffer{10240};
+
+    const auto wpos = osmium::builder::add_way(buffer,
+        _id(1),
+        _nodes({
+            {1, {1.0, 1.0}},
+            {2, {1.0, 2.0}},
+            {3},
+            {4, {2.0, 1.0}},
+            {1, {1.0, 1.0}}
+        })
+    );
+
+    osmium::area::AssemblerConfig config;
+    config.ignore_invalid_locations = true;
+    osmium::area::Assembler assembler{config};
+
+    osmium::memory::Buffer area_buffer{10240};
+    REQUIRE(assembler(buffer.get<osmium::Way>(wpos), area_buffer));
+
+    const auto& area = area_buffer.get<osmium::Area>(0);
+    REQUIRE(area.from_way());
+    REQUIRE(area.id() == 2);
+
+    const auto it = area.outer_rings().begin();
+    REQUIRE(it != area.outer_rings().end());
+    REQUIRE(it->size() == 4);
+
+    const auto& s = assembler.stats();
+    REQUIRE(s.area_simple_case == 1);
+    REQUIRE(s.from_ways == 1);
+    REQUIRE(s.nodes == 3);
+    REQUIRE(s.invalid_locations == 1);
+}
+
diff --git a/test/t/geom/test_projection.cpp b/test/t/geom/test_projection.cpp
index 14df3bf..ab6a004 100644
--- a/test/t/geom/test_projection.cpp
+++ b/test/t/geom/test_projection.cpp
@@ -33,11 +33,11 @@ TEST_CASE("Projection 4326 from init string") {
 }
 
 TEST_CASE("Creating projection from unknown init string") {
-    REQUIRE_THROWS_AS(osmium::geom::Projection projection{"abc"}, osmium::projection_error);
+    REQUIRE_THROWS_AS(osmium::geom::Projection{"abc"}, osmium::projection_error);
 }
 
 TEST_CASE("Creating projection from unknown EPSG code") {
-    REQUIRE_THROWS_AS(osmium::geom::Projection projection{9999999}, osmium::projection_error);
+    REQUIRE_THROWS_AS(osmium::geom::Projection{9999999}, osmium::projection_error);
 }
 
 TEST_CASE("Projection 3857") {
diff --git a/test/t/index/test_relations_map.cpp b/test/t/index/test_relations_map.cpp
index 8ef0755..1d77af2 100644
--- a/test/t/index/test_relations_map.cpp
+++ b/test/t/index/test_relations_map.cpp
@@ -21,14 +21,17 @@ TEST_CASE("RelationsMapStash lvalue") {
     REQUIRE_FALSE(stash.empty());
     REQUIRE(stash.size() == 2);
 
-    auto index= stash.build_index();
+    const auto index = stash.build_member_to_parent_index();
 
     REQUIRE_FALSE(index.empty());
     REQUIRE(index.size() == 2);
 
-    index.for_each_parent(1, [](osmium::unsigned_object_id_type id) {
+    int count = 0;
+    index.for_each(1, [&](osmium::unsigned_object_id_type id) {
         REQUIRE(id == 2);
+        ++count;
     });
+    REQUIRE(count == 1);
 }
 
 osmium::index::RelationsMapIndex func() {
@@ -37,14 +40,71 @@ osmium::index::RelationsMapIndex func() {
     stash.add(1, 2);
     stash.add(2, 3);
 
-    return stash.build_index();
+    return stash.build_member_to_parent_index();
 }
 
 TEST_CASE("RelationsMapStash rvalue") {
     const osmium::index::RelationsMapIndex index{func()};
 
-    index.for_each_parent(1, [](osmium::unsigned_object_id_type id) {
+    int count = 0;
+    index.for_each(2, [&](osmium::unsigned_object_id_type id) {
+        REQUIRE(id == 3);
+        ++count;
+    });
+    REQUIRE(count == 1);
+}
+
+TEST_CASE("RelationsMapStash reverse index") {
+    osmium::index::RelationsMapStash stash;
+    REQUIRE(stash.empty());
+    REQUIRE(stash.size() == 0);
+
+    stash.add(1, 2);
+    stash.add(2, 3);
+    REQUIRE_FALSE(stash.empty());
+    REQUIRE(stash.size() == 2);
+
+    const auto index = stash.build_parent_to_member_index();
+
+    REQUIRE_FALSE(index.empty());
+    REQUIRE(index.size() == 2);
+
+    int count = 0;
+    index.for_each(2, [&](osmium::unsigned_object_id_type id) {
+        REQUIRE(id == 1);
+        ++count;
+    });
+    index.for_each(3, [&](osmium::unsigned_object_id_type id) {
         REQUIRE(id == 2);
+        ++count;
+    });
+    REQUIRE(count == 2);
+}
+
+TEST_CASE("RelationsMapStash both indexes") {
+    osmium::index::RelationsMapStash stash;
+    REQUIRE(stash.empty());
+    REQUIRE(stash.size() == 0);
+
+    stash.add(1, 2);
+    stash.add(2, 3);
+    REQUIRE_FALSE(stash.empty());
+    REQUIRE(stash.size() == 2);
+
+    const auto index = stash.build_indexes();
+
+    REQUIRE_FALSE(index.empty());
+    REQUIRE(index.size() == 2);
+
+    int count = 0;
+    index.member_to_parent().for_each(2, [&](osmium::unsigned_object_id_type id) {
+        REQUIRE(id == 3);
+        ++count;
+    });
+    index.parent_to_member().for_each(2, [&](osmium::unsigned_object_id_type id) {
+        REQUIRE(id == 1);
+        ++count;
     });
+    REQUIRE(count == 2);
 }
 
diff --git a/test/t/io/test_compression_factory.cpp b/test/t/io/test_compression_factory.cpp
index 5428d82..612d232 100644
--- a/test/t/io/test_compression_factory.cpp
+++ b/test/t/io/test_compression_factory.cpp
@@ -15,13 +15,10 @@ TEST_CASE("Compression factory") {
     }
 
     SECTION("fail on undefined compression") {
-        REQUIRE_THROWS_AS({
-            factory.create_compressor(osmium::io::file_compression::gzip, -1, osmium::io::fsync::no);
-        }, osmium::unsupported_file_format_error);
-        REQUIRE_THROWS_WITH({
-            factory.create_compressor(osmium::io::file_compression::gzip, -1, osmium::io::fsync::no);
-        }, "Support for compression 'gzip' not compiled into this binary");
+        REQUIRE_THROWS_AS(factory.create_compressor(osmium::io::file_compression::gzip, -1, osmium::io::fsync::no),
+                          osmium::unsupported_file_format_error);
+        REQUIRE_THROWS_WITH(factory.create_compressor(osmium::io::file_compression::gzip, -1, osmium::io::fsync::no),
+                            "Support for compression 'gzip' not compiled into this binary");
     }
-
 }
 
diff --git a/test/t/io/test_opl_parser.cpp b/test/t/io/test_opl_parser.cpp
index 9ad6eeb..e5d0df2 100644
--- a/test/t/io/test_opl_parser.cpp
+++ b/test/t/io/test_opl_parser.cpp
@@ -33,17 +33,13 @@ TEST_CASE("Parse OPL: space") {
     std::string d{"a b \t c"};
 
     const char* s = d.data();
-    REQUIRE_THROWS_AS({
-        oid::opl_parse_space(&s);
-    }, osmium::opl_error);
+    REQUIRE_THROWS_AS(oid::opl_parse_space(&s), osmium::opl_error);
 
     s = d.data() + 1;
     oid::opl_parse_space(&s);
     REQUIRE(*s == 'b');
 
-    REQUIRE_THROWS_AS({
-        oid::opl_parse_space(&s);
-    }, osmium::opl_error);
+    REQUIRE_THROWS_AS(oid::opl_parse_space(&s), osmium::opl_error);
 
     ++s;
     oid::opl_parse_space(&s);
@@ -76,30 +72,26 @@ TEST_CASE("Parse OPL: parse escaped") {
 
     SECTION("Empty string") {
         const char* s = "";
-        REQUIRE_THROWS_WITH({
-            oid::opl_parse_escaped(&s, result);
-        }, "OPL error: eol");
+        REQUIRE_THROWS_WITH(oid::opl_parse_escaped(&s, result),
+                            "OPL error: eol");
     }
 
     SECTION("Illegal character for hex") {
         const char* s = "x";
-        REQUIRE_THROWS_WITH({
-            oid::opl_parse_escaped(&s, result);
-        }, "OPL error: not a hex char");
+        REQUIRE_THROWS_WITH(oid::opl_parse_escaped(&s, result),
+                            "OPL error: not a hex char");
     }
 
     SECTION("Illegal character for hex after legal hex characters") {
         const char* s = "0123x";
-        REQUIRE_THROWS_WITH({
-            oid::opl_parse_escaped(&s, result);
-        }, "OPL error: not a hex char");
+        REQUIRE_THROWS_WITH(oid::opl_parse_escaped(&s, result),
+                            "OPL error: not a hex char");
     }
 
     SECTION("Too long") {
         const char* s = "123456780";
-        REQUIRE_THROWS_WITH({
-            oid::opl_parse_escaped(&s, result);
-        }, "OPL error: hex escape too long");
+        REQUIRE_THROWS_WITH(oid::opl_parse_escaped(&s, result),
+                            "OPL error: hex escape too long");
     }
 
     SECTION("No data") {
@@ -237,16 +229,14 @@ TEST_CASE("Parse OPL: parse string") {
 
     SECTION("string with invalid escaping") {
         const char* s = "foo%";
-        REQUIRE_THROWS_WITH({
-            oid::opl_parse_string(&s, result);
-        }, "OPL error: eol");
+        REQUIRE_THROWS_WITH(oid::opl_parse_string(&s, result),
+                            "OPL error: eol");
     }
 
     SECTION("string with invalid escaped characters") {
         const char* s = "foo%x%";
-        REQUIRE_THROWS_WITH({
-            oid::opl_parse_string(&s, result);
-        }, "OPL error: not a hex char");
+        REQUIRE_THROWS_WITH(oid::opl_parse_string(&s, result),
+                            "OPL error: not a hex char");
     }
 
 }
@@ -267,25 +257,20 @@ TEST_CASE("Parse OPL: integer") {
     REQUIRE(test_parse_int("1234567890123x") == 1234567890123);
     REQUIRE(test_parse_int("-1234567890123x") == -1234567890123);
 
-    REQUIRE_THROWS_WITH({
-        test_parse_int("");
-    }, "OPL error: expected integer");
+    REQUIRE_THROWS_WITH(test_parse_int(""),
+                        "OPL error: expected integer");
 
-    REQUIRE_THROWS_WITH({
-        test_parse_int("-x");
-    }, "OPL error: expected integer");
+    REQUIRE_THROWS_WITH(test_parse_int("-x"),
+                        "OPL error: expected integer");
 
-    REQUIRE_THROWS_WITH({
-        test_parse_int(" 1");
-    }, "OPL error: expected integer");
+    REQUIRE_THROWS_WITH(test_parse_int(" 1"),
+                        "OPL error: expected integer");
 
-    REQUIRE_THROWS_WITH({
-        test_parse_int("x");
-    }, "OPL error: expected integer");
+    REQUIRE_THROWS_WITH(test_parse_int("x"),
+                        "OPL error: expected integer");
 
-    REQUIRE_THROWS_WITH({
-        test_parse_int("99999999999999999999999x");
-    }, "OPL error: integer too long");
+    REQUIRE_THROWS_WITH(test_parse_int("99999999999999999999999x"),
+                        "OPL error: integer too long");
 }
 
 TEST_CASE("Parse OPL: int32_t") {
@@ -293,29 +278,24 @@ TEST_CASE("Parse OPL: int32_t") {
     REQUIRE(test_parse_int<int32_t>("123x") == 123);
     REQUIRE(test_parse_int<int32_t>("-123x") == -123);
 
-    REQUIRE_THROWS_WITH({
-        test_parse_int<int32_t>("12345678901x");
-    }, "OPL error: integer too long");
-    REQUIRE_THROWS_WITH({
-        test_parse_int<int32_t>("-12345678901x");
-    }, "OPL error: integer too long");
+    REQUIRE_THROWS_WITH(test_parse_int<int32_t>("12345678901x"),
+                        "OPL error: integer too long");
+    REQUIRE_THROWS_WITH(test_parse_int<int32_t>("-12345678901x"),
+                        "OPL error: integer too long");
 }
 
 TEST_CASE("Parse OPL: uint32_t") {
     REQUIRE(test_parse_int<uint32_t>("0x") == 0);
     REQUIRE(test_parse_int<uint32_t>("123x") == 123);
 
-    REQUIRE_THROWS_WITH({
-        test_parse_int<uint32_t>("-123x");
-    }, "OPL error: integer too long");
+    REQUIRE_THROWS_WITH(test_parse_int<uint32_t>("-123x"),
+                        "OPL error: integer too long");
 
-    REQUIRE_THROWS_WITH({
-        test_parse_int<uint32_t>("12345678901x");
-    }, "OPL error: integer too long");
+    REQUIRE_THROWS_WITH(test_parse_int<uint32_t>("12345678901x"),
+                        "OPL error: integer too long");
 
-    REQUIRE_THROWS_WITH({
-        test_parse_int<uint32_t>("-12345678901x");
-    }, "OPL error: integer too long");
+    REQUIRE_THROWS_WITH(test_parse_int<uint32_t>("-12345678901x"),
+                        "OPL error: integer too long");
 }
 
 TEST_CASE("Parse OPL: visible flag") {
@@ -335,9 +315,8 @@ TEST_CASE("Parse OPL: deleted flag") {
 
 TEST_CASE("Parse OPL: invalid visible flag") {
     const char* data = "x";
-    REQUIRE_THROWS_WITH({
-        oid::opl_parse_visible(&data);
-    }, "OPL error: invalid visible flag");
+    REQUIRE_THROWS_WITH(oid::opl_parse_visible(&data),
+                        "OPL error: invalid visible flag");
 }
 
 TEST_CASE("Parse OPL: timestamp (empty)") {
@@ -363,9 +342,8 @@ TEST_CASE("Parse OPL: timestamp (tab)") {
 
 TEST_CASE("Parse OPL: timestamp (invalid)") {
     const char* data = "abc";
-    REQUIRE_THROWS_WITH({
-        oid::opl_parse_timestamp(&data);
-    }, "OPL error: can not parse timestamp");
+    REQUIRE_THROWS_WITH(oid::opl_parse_timestamp(&data),
+                        "OPL error: can not parse timestamp");
 }
 
 TEST_CASE("Parse OPL: timestamp (valid)") {
@@ -386,9 +364,8 @@ TEST_CASE("Parse OPL: tags") {
 
     SECTION("Empty") {
         const char* data = "";
-        REQUIRE_THROWS_WITH({
-            oid::opl_parse_tags(data, buffer);
-        }, "OPL error: expected '='");
+        REQUIRE_THROWS_WITH(oid::opl_parse_tags(data, buffer),
+                            "OPL error: expected '='");
     }
 
     SECTION("One tag") {
@@ -429,16 +406,14 @@ TEST_CASE("Parse OPL: tags") {
 
     SECTION("No equal signs") {
         const char* data = "a";
-        REQUIRE_THROWS_WITH({
-            oid::opl_parse_tags(data, buffer);
-        }, "OPL error: expected '='");
+        REQUIRE_THROWS_WITH(oid::opl_parse_tags(data, buffer),
+                            "OPL error: expected '='");
     }
 
     SECTION("Two equal signs") {
         const char* data = "a=b=c";
-        REQUIRE_THROWS_WITH({
-            oid::opl_parse_tags(data, buffer);
-        }, "OPL error: expected ','");
+        REQUIRE_THROWS_WITH(oid::opl_parse_tags(data, buffer),
+                            "OPL error: expected ','");
     }
 
 }
@@ -454,16 +429,14 @@ TEST_CASE("Parse OPL: nodes") {
 
     SECTION("Invalid format, missing n") {
         const char* const s = "xyz";
-        REQUIRE_THROWS_WITH({
-            oid::opl_parse_way_nodes(s, s + std::strlen(s), buffer);
-        }, "OPL error: expected 'n'");
+        REQUIRE_THROWS_WITH(oid::opl_parse_way_nodes(s, s + std::strlen(s), buffer),
+                            "OPL error: expected 'n'");
     }
 
     SECTION("Invalid format, missing ID") {
         const char* const s = "nx";
-        REQUIRE_THROWS_WITH({
-            oid::opl_parse_way_nodes(s, s + std::strlen(s), buffer);
-        }, "OPL error: expected integer");
+        REQUIRE_THROWS_WITH(oid::opl_parse_way_nodes(s, s + std::strlen(s), buffer),
+                            "OPL error: expected integer");
     }
 
     SECTION("Valid format: one node") {
@@ -534,23 +507,20 @@ TEST_CASE("Parse OPL: members") {
 
     SECTION("Invalid: unknown object type") {
         const char* const s = "x123 at foo";
-        REQUIRE_THROWS_WITH({
-            oid::opl_parse_relation_members(s, s + std::strlen(s), buffer);
-        }, "OPL error: unknown object type");
+        REQUIRE_THROWS_WITH(oid::opl_parse_relation_members(s, s + std::strlen(s), buffer),
+                            "OPL error: unknown object type");
     }
 
     SECTION("Invalid: illegal ref") {
         const char* const s = "wx";
-        REQUIRE_THROWS_WITH({
-            oid::opl_parse_relation_members(s, s + std::strlen(s), buffer);
-        }, "OPL error: expected integer");
+        REQUIRE_THROWS_WITH(oid::opl_parse_relation_members(s, s + std::strlen(s), buffer),
+                            "OPL error: expected integer");
     }
 
     SECTION("Invalid: missing @") {
         const char* const s = "n123foo";
-        REQUIRE_THROWS_WITH({
-            oid::opl_parse_relation_members(s, s + std::strlen(s), buffer);
-        }, "OPL error: expected '@'");
+        REQUIRE_THROWS_WITH(oid::opl_parse_relation_members(s, s + std::strlen(s), buffer),
+                            "OPL error: expected '@'");
     }
 
     SECTION("Valid format: one member") {
@@ -926,16 +896,14 @@ TEST_CASE("Parse line") {
     }
 
     SECTION("Fail") {
-        REQUIRE_THROWS_WITH({
-            oid::opl_parse_line(0, "X", buffer);
-        }, "OPL error: unknown type on line 0 column 0");
+        REQUIRE_THROWS_WITH(oid::opl_parse_line(0, "X", buffer),
+                            "OPL error: unknown type on line 0 column 0");
         REQUIRE(buffer.written() == 0);
     }
 
     SECTION("New line at end not allowed") {
-        REQUIRE_THROWS_WITH({
-            oid::opl_parse_line(0, "n12 v3\n", buffer);
-        }, "OPL error: expected space or tab character on line 0 column 6");
+        REQUIRE_THROWS_WITH(oid::opl_parse_line(0, "n12 v3\n", buffer),
+                            "OPL error: expected space or tab character on line 0 column 6");
     }
 
     SECTION("Node, but not asking for nodes") {
@@ -1064,9 +1032,8 @@ TEST_CASE("Parse line with external interface") {
     }
 
     SECTION("Failure") {
-        REQUIRE_THROWS_WITH({
-            osmium::opl_parse("x", buffer);
-        }, "OPL error: unknown type on line 0 column 0");
+        REQUIRE_THROWS_WITH(osmium::opl_parse("x", buffer),
+                            "OPL error: unknown type on line 0 column 0");
         REQUIRE(buffer.written() == 0);
         REQUIRE(buffer.committed() == 0);
     }
diff --git a/test/t/io/test_reader.cpp b/test/t/io/test_reader.cpp
index c95c76b..1fef874 100644
--- a/test/t/io/test_reader.cpp
+++ b/test/t/io/test_reader.cpp
@@ -65,9 +65,7 @@ TEST_CASE("Reader should throw after eof") {
 
     REQUIRE(reader.eof());
 
-    REQUIRE_THROWS_AS({
-        reader.read();
-    }, osmium::io_error);
+    REQUIRE_THROWS_AS(reader.read(), osmium::io_error);
 }
 
 TEST_CASE("Reader should not hang when apply() is called twice on reader") {
@@ -76,9 +74,7 @@ TEST_CASE("Reader should not hang when apply() is called twice on reader") {
     osmium::handler::Handler handler;
 
     osmium::apply(reader, handler);
-    REQUIRE_THROWS_AS({
-        osmium::apply(reader, handler);
-    }, osmium::io_error);
+    REQUIRE_THROWS_AS(osmium::apply(reader, handler), osmium::io_error);
 }
 
 TEST_CASE("Reader should work with a buffer with uncompressed data") {
@@ -137,7 +133,7 @@ TEST_CASE("Reader should work with a buffer with bzip2-compressed data") {
 
 TEST_CASE("Reader should decode zero node positions in history (XML)") {
     osmium::io::Reader reader{with_data_dir("t/io/deleted_nodes.osh"),
-                                osmium::osm_entity_bits::node};
+                              osmium::osm_entity_bits::node};
     ZeroPositionNodeCountHandler handler;
 
     REQUIRE(handler.count == 0);
@@ -151,7 +147,7 @@ TEST_CASE("Reader should decode zero node positions in history (XML)") {
 
 TEST_CASE("Reader should decode zero node positions in history (PBF)") {
     osmium::io::Reader reader{with_data_dir("t/io/deleted_nodes.osh.pbf"),
-                                osmium::osm_entity_bits::node};
+                              osmium::osm_entity_bits::node};
     ZeroPositionNodeCountHandler handler;
 
     REQUIRE(handler.count == 0);
@@ -164,21 +160,15 @@ TEST_CASE("Reader should decode zero node positions in history (PBF)") {
 }
 
 TEST_CASE("Reader should fail with nonexistent file") {
-    REQUIRE_THROWS({
-        osmium::io::Reader reader{with_data_dir("t/io/nonexistent-file.osm")};
-    });
+    REQUIRE_THROWS(osmium::io::Reader{with_data_dir("t/io/nonexistent-file.osm")});
 }
 
 TEST_CASE("Reader should fail with nonexistent file (gz)") {
-    REQUIRE_THROWS({
-        osmium::io::Reader reader{with_data_dir("t/io/nonexistent-file.osm.gz")};
-    });
+    REQUIRE_THROWS(osmium::io::Reader{with_data_dir("t/io/nonexistent-file.osm.gz")});
 }
 
 TEST_CASE("Reader should fail with nonexistent file (pbf)") {
-    REQUIRE_THROWS({
-        osmium::io::Reader reader{with_data_dir("t/io/nonexistent-file.osm.pbf")};
-    });
+    REQUIRE_THROWS(osmium::io::Reader{with_data_dir("t/io/nonexistent-file.osm.pbf")});
 }
 
 TEST_CASE("Reader should work when there is an exception in main thread before getting header") {
diff --git a/test/t/io/test_reader_fileformat.cpp b/test/t/io/test_reader_fileformat.cpp
new file mode 100644
index 0000000..a64932e
--- /dev/null
+++ b/test/t/io/test_reader_fileformat.cpp
@@ -0,0 +1,10 @@
+
+#include "catch.hpp"
+#include "utils.hpp"
+
+#include <osmium/io/reader.hpp>
+
+TEST_CASE("Reader throws on unsupported file format") {
+    REQUIRE_THROWS_AS(osmium::io::Reader{with_data_dir("t/io/data.osm")}, osmium::unsupported_file_format_error);
+}
+
diff --git a/test/t/io/test_writer.cpp b/test/t/io/test_writer.cpp
index 3d61759..38ec6ad 100644
--- a/test/t/io/test_writer.cpp
+++ b/test/t/io/test_writer.cpp
@@ -28,7 +28,7 @@ TEST_CASE("Writer") {
         SECTION("Empty buffer") {
             filename = "test-writer-out-empty-buffer.osm";
             osmium::io::Writer writer{filename, header, osmium::io::overwrite::allow};
-            osmium::memory::Buffer empty_buffer(1024);
+            osmium::memory::Buffer empty_buffer{1024};
             writer(std::move(empty_buffer));
             writer.close();
         }
@@ -54,9 +54,7 @@ TEST_CASE("Writer") {
             writer(std::move(buffer));
             writer.close();
 
-            REQUIRE_THROWS_AS({
-                writer(osmium::memory::Buffer{});
-            }, osmium::io_error);
+            REQUIRE_THROWS_AS(writer(osmium::memory::Buffer{}), osmium::io_error);
         }
 
         SECTION("Writer item") {
diff --git a/test/t/io/test_writer_with_mock_compression.cpp b/test/t/io/test_writer_with_mock_compression.cpp
index 186ce25..a4f9de2 100644
--- a/test/t/io/test_writer_with_mock_compression.cpp
+++ b/test/t/io/test_writer_with_mock_compression.cpp
@@ -62,11 +62,11 @@ TEST_CASE("Write with mock compressor") {
 
         fail_in = "constructor";
 
-        REQUIRE_THROWS_AS({
+        REQUIRE_THROWS_AS([&](){
             osmium::io::Writer writer("test-writer-mock-fail-on-construction.osm.gz", header, osmium::io::overwrite::allow);
             writer(std::move(buffer));
             writer.close();
-        }, std::logic_error);
+        }(), std::logic_error);
 
     }
 
@@ -74,11 +74,11 @@ TEST_CASE("Write with mock compressor") {
 
         fail_in = "write";
 
-        REQUIRE_THROWS_AS({
+        REQUIRE_THROWS_AS([&](){
             osmium::io::Writer writer("test-writer-mock-fail-on-write.osm.gz", header, osmium::io::overwrite::allow);
             writer(std::move(buffer));
             writer.close();
-        }, std::logic_error);
+        }(), std::logic_error);
 
     }
 
@@ -86,11 +86,11 @@ TEST_CASE("Write with mock compressor") {
 
         fail_in = "close";
 
-        REQUIRE_THROWS_AS({
+        REQUIRE_THROWS_AS([&](){
             osmium::io::Writer writer("test-writer-mock-fail-on-close.osm.gz", header, osmium::io::overwrite::allow);
             writer(std::move(buffer));
             writer.close();
-        }, std::logic_error);
+        }(), std::logic_error);
 
     }
 
diff --git a/test/t/io/test_writer_with_mock_encoder.cpp b/test/t/io/test_writer_with_mock_encoder.cpp
index b00b096..af20dbe 100644
--- a/test/t/io/test_writer_with_mock_encoder.cpp
+++ b/test/t/io/test_writer_with_mock_encoder.cpp
@@ -68,11 +68,11 @@ TEST_CASE("Test Writer with MockOutputFormat") {
 
         fail_in = "header";
 
-        REQUIRE_THROWS_AS({
+        REQUIRE_THROWS_AS([&](){
             osmium::io::Writer writer("test-writer-mock-fail-on-construction.osm", header, osmium::io::overwrite::allow);
             writer(std::move(buffer));
             writer.close();
-        }, std::logic_error);
+        }(), std::logic_error);
 
     }
 
@@ -80,11 +80,11 @@ TEST_CASE("Test Writer with MockOutputFormat") {
 
         fail_in = "write";
 
-        REQUIRE_THROWS_AS({
+        REQUIRE_THROWS_AS([&](){
             osmium::io::Writer writer("test-writer-mock-fail-on-construction.osm", header, osmium::io::overwrite::allow);
             writer(std::move(buffer));
             writer.close();
-        }, std::logic_error);
+        }(), std::logic_error);
 
     }
 
@@ -92,11 +92,11 @@ TEST_CASE("Test Writer with MockOutputFormat") {
 
         fail_in = "write_end";
 
-        REQUIRE_THROWS_AS({
+        REQUIRE_THROWS_AS([&](){
             osmium::io::Writer writer("test-writer-mock-fail-on-construction.osm", header, osmium::io::overwrite::allow);
             writer(std::move(buffer));
             writer.close();
-        }, std::logic_error);
+        }(), std::logic_error);
 
     }
 
diff --git a/test/t/osm/test_location.cpp b/test/t/osm/test_location.cpp
index 6aba91d..0adfc95 100644
--- a/test/t/osm/test_location.cpp
+++ b/test/t/osm/test_location.cpp
@@ -381,12 +381,8 @@ TEST_CASE("set lon/lat from string") {
 
 TEST_CASE("set lon/lat from string with trailing characters") {
     osmium::Location loc;
-    REQUIRE_THROWS_AS({
-        loc.set_lon("1.2x");
-    }, osmium::invalid_location);
-    REQUIRE_THROWS_AS({
-        loc.set_lat("3.4e1 ");
-    }, osmium::invalid_location);
+    REQUIRE_THROWS_AS(loc.set_lon("1.2x"), osmium::invalid_location);
+    REQUIRE_THROWS_AS(loc.set_lat("3.4e1 "), osmium::invalid_location);
 }
 
 TEST_CASE("set lon/lat from string with trailing characters using partial") {
diff --git a/test/t/tags/test_tag_list.cpp b/test/t/tags/test_tag_list.cpp
index 3bdf5e9..db3f165 100644
--- a/test/t/tags/test_tag_list.cpp
+++ b/test/t/tags/test_tag_list.cpp
@@ -11,7 +11,7 @@
 using namespace osmium::builder::attr;
 
 TEST_CASE("create tag list") {
-    osmium::memory::Buffer buffer(10240);
+    osmium::memory::Buffer buffer{10240};
 
     SECTION("with TagListBuilder from char*") {
         {
@@ -160,13 +160,6 @@ TEST_CASE("create tag list") {
         osmium::builder::add_tag_list(buffer, _tags(m));
     }
 
-    SECTION("with build_tag_list_from_func") {
-        osmium::builder::build_tag_list_from_func(buffer, [](osmium::builder::TagListBuilder& tlb) {
-            tlb.add_tag("highway", "primary");
-            tlb.add_tag("name", "Main Street");
-        });
-    }
-
     const osmium::TagList& tl = *buffer.select<osmium::TagList>().cbegin();
     REQUIRE(osmium::item_type::tag_list == tl.type());
     REQUIRE(2 == tl.size());
@@ -194,9 +187,9 @@ TEST_CASE("create tag list") {
 }
 
 TEST_CASE("empty keys and values are okay") {
-    osmium::memory::Buffer buffer(10240);
+    osmium::memory::Buffer buffer{10240};
 
-    auto pos = osmium::builder::add_tag_list(buffer,
+    const auto pos = osmium::builder::add_tag_list(buffer,
         _tag("empty value", ""),
         _tag("", "empty key")
     );
@@ -219,8 +212,8 @@ TEST_CASE("empty keys and values are okay") {
 }
 
 TEST_CASE("tag key or value is too long") {
-    osmium::memory::Buffer buffer(10240);
-    osmium::builder::TagListBuilder builder(buffer);
+    osmium::memory::Buffer buffer{10240};
+    osmium::builder::TagListBuilder builder{buffer};
 
     const char kv[2000] = "";
     builder.add_tag(kv, 1, kv, 1000);
diff --git a/test/t/tags/test_tag_matcher.cpp b/test/t/tags/test_tag_matcher.cpp
new file mode 100644
index 0000000..d498062
--- /dev/null
+++ b/test/t/tags/test_tag_matcher.cpp
@@ -0,0 +1,93 @@
+#include "catch.hpp"
+
+#include <type_traits>
+
+#include <osmium/builder/attr.hpp>
+#include <osmium/memory/buffer.hpp>
+#include <osmium/tags/matcher.hpp>
+
+static_assert(std::is_default_constructible<osmium::TagMatcher>::value, "TagMatcher should be default constructible");
+static_assert(std::is_copy_constructible<osmium::TagMatcher>::value, "TagMatcher should be copy constructible");
+static_assert(std::is_move_constructible<osmium::TagMatcher>::value, "TagMatcher should be move constructible");
+static_assert(std::is_copy_assignable<osmium::TagMatcher>::value, "TagMatcher should be copyable");
+static_assert(std::is_move_assignable<osmium::TagMatcher>::value, "TagMatcher should be moveable");
+
+TEST_CASE("Tag matcher") {
+    osmium::memory::Buffer buffer{10240};
+
+    const auto pos = osmium::builder::add_tag_list(buffer,
+        osmium::builder::attr::_tags({
+            { "highway", "primary" },
+            { "name", "Main Street" },
+            { "source", "GPS" }
+    }));
+    const osmium::TagList& tag_list = buffer.get<osmium::TagList>(pos);
+
+    SECTION("Matching keys only") {
+        osmium::TagMatcher m{osmium::StringMatcher::equal{"highway"}};
+        REQUIRE(m(tag_list));
+
+        REQUIRE(m(*tag_list.begin()));
+        REQUIRE_FALSE(m(*std::next(tag_list.begin())));
+    }
+
+    SECTION("Matching keys only with shortcut const char*") {
+        osmium::TagMatcher m{"highway"};
+        REQUIRE(m(tag_list));
+
+        REQUIRE(m(*tag_list.begin()));
+        REQUIRE_FALSE(m(*std::next(tag_list.begin())));
+    }
+
+    SECTION("Matching keys only with shortcut std::string") {
+        std::string s{"highway"};
+        osmium::TagMatcher m{s};
+        REQUIRE(m(tag_list));
+
+        REQUIRE(m(*tag_list.begin()));
+        REQUIRE_FALSE(m(*std::next(tag_list.begin())));
+    }
+
+    SECTION("Matching key and value") {
+        osmium::TagMatcher m{osmium::StringMatcher::equal{"highway"},
+                             osmium::StringMatcher::equal{"primary"}};
+        REQUIRE(m(tag_list));
+
+        REQUIRE(m(*tag_list.begin()));
+        REQUIRE_FALSE(m(*std::next(tag_list.begin())));
+    }
+
+    SECTION("Matching key and value with shortcut") {
+        osmium::TagMatcher m{"highway", "primary", false};
+        REQUIRE(m(tag_list));
+
+        REQUIRE(m(*tag_list.begin()));
+        REQUIRE_FALSE(m(*std::next(tag_list.begin())));
+    }
+
+    SECTION("Matching key and value") {
+        osmium::TagMatcher m{osmium::StringMatcher::equal{"highway"},
+                             osmium::StringMatcher::equal{"secondary"}};
+        REQUIRE_FALSE(m(tag_list));
+    }
+
+    SECTION("Matching key and value inverted") {
+        osmium::TagMatcher m{osmium::StringMatcher::equal{"highway"},
+                             osmium::StringMatcher::equal{"secondary"},
+                             true};
+        REQUIRE(m(tag_list));
+
+        REQUIRE(m(*tag_list.begin()));
+        REQUIRE_FALSE(m(*std::next(tag_list.begin())));
+    }
+
+    SECTION("Matching key and value list") {
+        osmium::TagMatcher m{osmium::StringMatcher::equal{"highway"},
+                             osmium::StringMatcher::list{{"primary", "secondary"}}};
+        REQUIRE(m(tag_list));
+
+        REQUIRE(m(*tag_list.begin()));
+        REQUIRE_FALSE(m(*std::next(tag_list.begin())));
+    }
+}
+
diff --git a/test/t/tags/test_tags_filter.cpp b/test/t/tags/test_tags_filter.cpp
new file mode 100644
index 0000000..a537228
--- /dev/null
+++ b/test/t/tags/test_tags_filter.cpp
@@ -0,0 +1,79 @@
+#include "catch.hpp"
+
+#include <functional>
+
+#include <osmium/builder/attr.hpp>
+#include <osmium/memory/buffer.hpp>
+#include <osmium/tags/tags_filter.hpp>
+
+TEST_CASE("Tags filter") {
+    osmium::memory::Buffer buffer{10240};
+
+    const auto pos1 = osmium::builder::add_tag_list(buffer,
+        osmium::builder::attr::_tags({
+            { "highway", "primary" },
+            { "name", "Main Street" },
+            { "source", "GPS" }
+    }));
+    const auto pos2 = osmium::builder::add_tag_list(buffer,
+        osmium::builder::attr::_tags({
+            { "amenity", "restaurant" },
+            { "name", "The Golden Goose" }
+    }));
+    const osmium::TagList& tag_list1 = buffer.get<osmium::TagList>(pos1);
+    const osmium::TagList& tag_list2 = buffer.get<osmium::TagList>(pos2);
+
+    SECTION("Filter based on key only: okay") {
+        osmium::TagsFilter filter;
+        filter.add_rule(true, osmium::TagMatcher{osmium::StringMatcher::equal{"highway"}});
+        filter.add_rule(true, osmium::TagMatcher{osmium::StringMatcher::equal{"amenity"}});
+        REQUIRE(filter(*tag_list1.begin()));
+        REQUIRE(filter(*tag_list2.begin()));
+        REQUIRE_FALSE(filter(*std::next(tag_list1.begin())));
+        REQUIRE_FALSE(filter(*std::next(tag_list2.begin())));
+    }
+
+    SECTION("Filter based string: shortcut") {
+        osmium::TagsFilter filter;
+        filter.add_rule(true, "highway");
+        filter.add_rule(true, "amenity", "restaurant");
+        REQUIRE(filter(*tag_list1.begin()));
+        REQUIRE(filter(*tag_list2.begin()));
+        REQUIRE_FALSE(filter(*std::next(tag_list1.begin())));
+        REQUIRE_FALSE(filter(*std::next(tag_list2.begin())));
+    }
+
+    SECTION("Filter based on key only: fail") {
+        osmium::TagsFilter filter;
+        filter.add_rule(true, osmium::StringMatcher::equal{"foo"});
+        filter.add_rule(true, osmium::StringMatcher::equal{"bar"});
+        REQUIRE_FALSE(filter(*tag_list1.begin()));
+        REQUIRE_FALSE(filter(*tag_list2.begin()));
+        REQUIRE_FALSE(filter(*std::next(tag_list1.begin())));
+        REQUIRE_FALSE(filter(*std::next(tag_list2.begin())));
+    }
+
+    SECTION("KeyFilter iterator filters tags") {
+        osmium::TagsFilter filter;
+        filter.add_rule(true, osmium::StringMatcher::equal{"highway"})
+              .add_rule(true, osmium::StringMatcher::equal{"source"});
+
+        osmium::TagsFilter::iterator it{std::cref(filter), tag_list1.begin(),
+                                                           tag_list1.end()};
+
+        const osmium::TagsFilter::iterator end{std::cref(filter), tag_list1.end(),
+                                                                  tag_list1.end()};
+
+        REQUIRE(2 == std::distance(it, end));
+
+        REQUIRE(it != end);
+        REQUIRE(std::string("highway") == it->key());
+        REQUIRE(std::string("primary") == it->value());
+        ++it;
+        REQUIRE(std::string("source") == it->key());
+        REQUIRE(std::string("GPS") == it->value());
+        REQUIRE(++it == end);
+    }
+
+}
+
diff --git a/test/t/util/test_cast_with_assert.cpp b/test/t/util/test_cast_with_assert.cpp
index 044176e..2c65e0c 100644
--- a/test/t/util/test_cast_with_assert.cpp
+++ b/test/t/util/test_cast_with_assert.cpp
@@ -10,80 +10,75 @@ struct assert_error : public std::runtime_error {
 
 #include <osmium/util/cast.hpp>
 
-TEST_CASE("static_cast_with_assert") {
-
-    SECTION("same types is always okay") {
-        int f = 10;
-        auto t = osmium::static_cast_with_assert<int>(f);
-        REQUIRE(t == f);
-    }
-
-    SECTION("casting to larger type is always okay") {
-        int16_t f = 10;
-        auto t = osmium::static_cast_with_assert<int32_t>(f);
-        REQUIRE(t == f);
-    }
-
+TEST_CASE("static_cast_with_assert: same types is always okay") {
+    const int f = 10;
+    const auto t = osmium::static_cast_with_assert<int>(f);
+    REQUIRE(t == f);
+}
 
-    SECTION("cast int32_t -> int_16t should not trigger assert for small int") {
-        int32_t f = 100;
-        auto t = osmium::static_cast_with_assert<int16_t>(f);
-        REQUIRE(t == f);
-    }
+TEST_CASE("static_cast_with_assert: casting to larger type is always okay") {
+    const int16_t f = 10;
+    const auto t = osmium::static_cast_with_assert<int32_t>(f);
+    REQUIRE(t == f);
+}
 
-    SECTION("cast int32_t -> int_16t should trigger assert for large int") {
-        int32_t f = 100000;
-        REQUIRE_THROWS_AS(osmium::static_cast_with_assert<int16_t>(f), assert_error);
-    }
 
+TEST_CASE("static_cast_with_assert: cast int32_t -> int16_t should not trigger assert for small int") {
+    const int32_t f = 100;
+    const auto t = osmium::static_cast_with_assert<int16_t>(f);
+    REQUIRE(t == f);
+}
 
-    SECTION("cast int16_t -> uint16_t should not trigger assert for zero") {
-        int16_t f = 0;
-        auto t = osmium::static_cast_with_assert<uint16_t>(f);
-        REQUIRE(t == f);
-    }
+TEST_CASE("static_cast_with_assert: cast int32_t -> int16_t should trigger assert for large int") {
+    const int32_t f = 100000;
+    REQUIRE_THROWS_AS(osmium::static_cast_with_assert<int16_t>(f), assert_error);
+}
 
-    SECTION("cast int16_t -> uint16_t should not trigger assert for positive int") {
-        int16_t f = 1;
-        auto t = osmium::static_cast_with_assert<uint16_t>(f);
-        REQUIRE(t == f);
-    }
 
-    SECTION("cast int16_t -> uint16_t should trigger assert for negative int") {
-        int16_t f = -1;
-        REQUIRE_THROWS_AS(osmium::static_cast_with_assert<uint16_t>(f), assert_error);
-    }
+TEST_CASE("static_cast_with_assert: cast int16_t -> uint16_t should not trigger assert for zero") {
+    const int16_t f = 0;
+    const auto t = osmium::static_cast_with_assert<uint16_t>(f);
+    REQUIRE(t == f);
+}
 
+TEST_CASE("static_cast_with_assert: cast int16_t -> uint16_t should not trigger assert for positive int") {
+    const int16_t f = 1;
+    const auto t = osmium::static_cast_with_assert<uint16_t>(f);
+    REQUIRE(t == f);
+}
 
-    SECTION("cast uint32_t -> uint_16t should not trigger assert for zero") {
-        uint32_t f = 0;
-        auto t = osmium::static_cast_with_assert<uint16_t>(f);
-        REQUIRE(t == f);
-    }
+TEST_CASE("static_cast_with_assert: cast int16_t -> uint16_t should trigger assert for negative int") {
+    const int16_t f = -1;
+    REQUIRE_THROWS_AS(osmium::static_cast_with_assert<uint16_t>(f), assert_error);
+}
 
-    SECTION("cast uint32_t -> uint_16t should not trigger assert for small int") {
-        uint32_t f = 100;
-        auto t = osmium::static_cast_with_assert<uint16_t>(f);
-        REQUIRE(t == f);
-    }
 
-    SECTION("cast int32_t -> int_16t should trigger assert for large int") {
-        uint32_t f = 100000;
-        REQUIRE_THROWS_AS(osmium::static_cast_with_assert<uint16_t>(f), assert_error);
-    }
+TEST_CASE("static_cast_with_assert: cast uint32_t -> uint16_t should not trigger assert for zero") {
+    const uint32_t f = 0;
+    const auto t = osmium::static_cast_with_assert<uint16_t>(f);
+    REQUIRE(t == f);
+}
 
+TEST_CASE("static_cast_with_assert: cast uint32_t -> uint16_t should not trigger assert for small int") {
+    const uint32_t f = 100;
+    const auto t = osmium::static_cast_with_assert<uint16_t>(f);
+    REQUIRE(t == f);
+}
 
-    SECTION("cast uint16_t -> int16_t should not trigger assert for small int") {
-        uint16_t f = 1;
-        auto t = osmium::static_cast_with_assert<int16_t>(f);
-        REQUIRE(t == f);
-    }
+TEST_CASE("static_cast_with_assert: cast uint32_t -> uint16_t should trigger assert for large int") {
+    const uint32_t f = 100000;
+    REQUIRE_THROWS_AS(osmium::static_cast_with_assert<uint16_t>(f), assert_error);
+}
 
-    SECTION("cast uint16_t -> int16_t should trigger assert for large int") {
-        uint16_t f = 65000;
-        REQUIRE_THROWS_AS(osmium::static_cast_with_assert<int16_t>(f), assert_error);
-    }
 
+TEST_CASE("static_cast_with_assert: cast uint16_t -> int16_t should not trigger assert for small int") {
+    const uint16_t f = 1;
+    const auto t = osmium::static_cast_with_assert<int16_t>(f);
+    REQUIRE(t == f);
+}
 
+TEST_CASE("static_cast_with_assert: cast uint16_t -> int16_t should trigger assert for large int") {
+    const uint16_t f = 65000;
+    REQUIRE_THROWS_AS(osmium::static_cast_with_assert<int16_t>(f), assert_error);
 }
 
diff --git a/test/t/util/test_delta.cpp b/test/t/util/test_delta.cpp
index 27bd8be..31b4276 100644
--- a/test/t/util/test_delta.cpp
+++ b/test/t/util/test_delta.cpp
@@ -5,56 +5,39 @@
 #include <osmium/util/delta.hpp>
 
 TEST_CASE("delta encode int") {
-
     osmium::util::DeltaEncode<int> x;
 
-    SECTION("int") {
-        REQUIRE(x.update(17) == 17);
-        REQUIRE(x.update(10) == -7);
-        REQUIRE(x.update(-10) == -20);
-    }
-
+    REQUIRE(x.update(17) == 17);
+    REQUIRE(x.update(10) == -7);
+    REQUIRE(x.update(-10) == -20);
 }
 
 TEST_CASE("delta decode int") {
-
     osmium::util::DeltaDecode<int> x;
 
-    SECTION("int") {
-        REQUIRE(x.update(17) == 17);
-        REQUIRE(x.update(10) == 27);
-        REQUIRE(x.update(-40) == -13);
-    }
-
+    REQUIRE(x.update(17) == 17);
+    REQUIRE(x.update(10) == 27);
+    REQUIRE(x.update(-40) == -13);
 }
 
 TEST_CASE("delta encode unsigned int") {
-
     osmium::util::DeltaEncode<unsigned int> x;
 
-    SECTION("int") {
-        REQUIRE(x.update(17) == 17);
-        REQUIRE(x.update(10) == -7);
-        REQUIRE(x.update(0) == -10);
-    }
-
+    REQUIRE(x.update(17) == 17);
+    REQUIRE(x.update(10) == -7);
+    REQUIRE(x.update(0) == -10);
 }
 
 TEST_CASE("delta decode unsigned int") {
-
     osmium::util::DeltaDecode<unsigned int> x;
 
-    SECTION("int") {
-        REQUIRE(x.update(17) == 17);
-        REQUIRE(x.update(10) == 27);
-        REQUIRE(x.update(-15) == 12);
-    }
-
+    REQUIRE(x.update(17) == 17);
+    REQUIRE(x.update(10) == 27);
+    REQUIRE(x.update(-15) == 12);
 }
 
 TEST_CASE("delta encode and decode") {
-
-    std::vector<int> a = { 5, -9, 22, 13, 0, 23 };
+    const std::vector<int> a = { 5, -9, 22, 13, 0, 23 };
 
     osmium::util::DeltaEncode<int, int> de;
     std::vector<int> b;
@@ -68,5 +51,6 @@ TEST_CASE("delta encode and decode") {
         c.push_back(dd.update(x));
     }
 
+    REQUIRE(a == c);
 }
 
diff --git a/test/t/util/test_double.cpp b/test/t/util/test_double.cpp
index 6cc87a0..3ffaa93 100644
--- a/test/t/util/test_double.cpp
+++ b/test/t/util/test_double.cpp
@@ -2,32 +2,29 @@
 
 #include <osmium/util/double.hpp>
 
-TEST_CASE("Double") {
-
-    SECTION("double2string") {
-        std::string s1;
-        osmium::util::double2string(s1, 1.123, 7);
-        REQUIRE(s1 == "1.123");
-
-        std::string s2;
-        osmium::util::double2string(s2, 1.000, 7);
-        REQUIRE(s2 == "1");
-
-        std::string s3;
-        osmium::util::double2string(s3, 0.0, 7);
-        REQUIRE(s3 == "0");
-
-        std::string s4;
-        osmium::util::double2string(s4, 0.020, 7);
-        REQUIRE(s4 == "0.02");
-
-        std::string s5;
-        osmium::util::double2string(s5, -0.020, 7);
-        REQUIRE(s5 == "-0.02");
-
-        std::string s6;
-        osmium::util::double2string(s6, -0.0, 7);
-        REQUIRE(s6 == "-0");
-    }
+TEST_CASE("Check double2string function") {
+    std::string s1;
+    osmium::util::double2string(s1, 1.123, 7);
+    REQUIRE(s1 == "1.123");
+
+    std::string s2;
+    osmium::util::double2string(s2, 1.000, 7);
+    REQUIRE(s2 == "1");
+
+    std::string s3;
+    osmium::util::double2string(s3, 0.0, 7);
+    REQUIRE(s3 == "0");
+
+    std::string s4;
+    osmium::util::double2string(s4, 0.020, 7);
+    REQUIRE(s4 == "0.02");
+
+    std::string s5;
+    osmium::util::double2string(s5, -0.020, 7);
+    REQUIRE(s5 == "-0.02");
+
+    std::string s6;
+    osmium::util::double2string(s6, -0.0, 7);
+    REQUIRE(s6 == "-0");
 }
 
diff --git a/test/t/util/test_memory_mapping.cpp b/test/t/util/test_memory_mapping.cpp
index 647d2a0..966f670 100644
--- a/test/t/util/test_memory_mapping.cpp
+++ b/test/t/util/test_memory_mapping.cpp
@@ -1,7 +1,8 @@
 #include "catch.hpp"
 
-#include <sys/types.h>
+#include <cstdlib>
 #include <limits>
+#include <utility>
 
 #include <osmium/util/file.hpp>
 #include <osmium/util/memory_mapping.hpp>
@@ -12,403 +13,382 @@
 
 static const size_t huge = std::numeric_limits<size_t>::max();
 
-TEST_CASE("anonymous mapping") {
+TEST_CASE("Anonymous mapping: simple memory mapping should work") {
+    osmium::util::MemoryMapping mapping{1000, osmium::util::MemoryMapping::mapping_mode::write_private};
+    REQUIRE(mapping.get_addr() != nullptr);
 
-    SECTION("simple memory mapping should work") {
-        osmium::util::MemoryMapping mapping(1000, osmium::util::MemoryMapping::mapping_mode::write_private);
-        REQUIRE(mapping.get_addr() != nullptr);
+    REQUIRE(mapping.size() >= 1000);
 
-        REQUIRE(mapping.size() >= 1000);
+    volatile int* addr = mapping.get_addr<int>();
 
-        volatile int* addr = mapping.get_addr<int>();
+    REQUIRE(mapping.writable());
 
-        REQUIRE(mapping.writable());
-
-        *addr = 42;
-        REQUIRE(*addr == 42);
+    *addr = 42;
+    REQUIRE(*addr == 42);
 
-        REQUIRE(!!mapping);
-        mapping.unmap();
-        REQUIRE(!mapping);
-        mapping.unmap(); // second unmap is okay
-    }
+    REQUIRE(!!mapping);
+    mapping.unmap();
+    REQUIRE(!mapping);
+    mapping.unmap(); // second unmap is okay
+}
 
-    SECTION("memory mapping of zero length should fail") {
-        REQUIRE_THROWS({
-             osmium::util::MemoryMapping mapping(0, osmium::util::MemoryMapping::mapping_mode::write_private);
-        });
-    }
+TEST_CASE("Anonymous mapping: memory mapping of zero length should fail") {
+    REQUIRE_THROWS(osmium::util::MemoryMapping(0, osmium::util::MemoryMapping::mapping_mode::write_private));
+}
 
-    SECTION("moving a memory mapping should work") {
-        osmium::util::MemoryMapping mapping1(1000, osmium::util::MemoryMapping::mapping_mode::write_private);
-        int* addr1 = mapping1.get_addr<int>();
-        *addr1 = 42;
+TEST_CASE("Anonymous mapping: moving a memory mapping should work") {
+    osmium::util::MemoryMapping mapping1{1000, osmium::util::MemoryMapping::mapping_mode::write_private};
+    int* addr1 = mapping1.get_addr<int>();
+    *addr1 = 42;
 
-        REQUIRE(!!mapping1);
-        osmium::util::MemoryMapping mapping2(std::move(mapping1));
-        REQUIRE(!!mapping2);
-        REQUIRE(!mapping1);
-        mapping1.unmap();
+    REQUIRE(!!mapping1);
+    osmium::util::MemoryMapping mapping2{std::move(mapping1)};
+    REQUIRE(!!mapping2);
+    REQUIRE(!mapping1);
+    mapping1.unmap();
 
-        int* addr2 = mapping2.get_addr<int>();
-        REQUIRE(*addr2 == 42);
+    int* addr2 = mapping2.get_addr<int>();
+    REQUIRE(*addr2 == 42);
 
-        mapping2.unmap();
-        REQUIRE(!mapping2);
-    }
+    mapping2.unmap();
+    REQUIRE(!mapping2);
+}
 
-    SECTION("move assignment should work") {
-        osmium::util::MemoryMapping mapping1(1000, osmium::util::MemoryMapping::mapping_mode::write_private);
-        osmium::util::MemoryMapping mapping2(1000, osmium::util::MemoryMapping::mapping_mode::write_private);
+TEST_CASE("Anonymous mapping: move assignment should work") {
+    osmium::util::MemoryMapping mapping1{1000, osmium::util::MemoryMapping::mapping_mode::write_private};
+    osmium::util::MemoryMapping mapping2{1000, osmium::util::MemoryMapping::mapping_mode::write_private};
 
-        REQUIRE(!!mapping1);
-        REQUIRE(!!mapping2);
+    REQUIRE(!!mapping1);
+    REQUIRE(!!mapping2);
 
-        int* addr1 = mapping1.get_addr<int>();
-        *addr1 = 42;
+    int* addr1 = mapping1.get_addr<int>();
+    *addr1 = 42;
 
-        mapping2 = std::move(mapping1);
-        REQUIRE(!!mapping2);
-        REQUIRE(!mapping1);
+    mapping2 = std::move(mapping1);
+    REQUIRE(!!mapping2);
+    REQUIRE(!mapping1);
 
-        int* addr2 = mapping2.get_addr<int>();
-        REQUIRE(*addr2 == 42);
+    int* addr2 = mapping2.get_addr<int>();
+    REQUIRE(*addr2 == 42);
 
-        mapping2.unmap();
-        REQUIRE(!mapping2);
-    }
+    mapping2.unmap();
+    REQUIRE(!mapping2);
+}
 
 #ifdef __linux__
-    SECTION("remapping to larger size should work") {
-        osmium::util::MemoryMapping mapping(1000, osmium::util::MemoryMapping::mapping_mode::write_private);
-        REQUIRE(mapping.size() >= 1000);
+TEST_CASE("Anonymous mapping: remapping to larger size should work") {
+    osmium::util::MemoryMapping mapping{1000, osmium::util::MemoryMapping::mapping_mode::write_private};
+    REQUIRE(mapping.size() >= 1000);
 
-        size_t size1 = mapping.size();
+    const size_t size1 = mapping.size();
 
-        int* addr1 = mapping.get_addr<int>();
-        *addr1 = 42;
+    int* addr1 = mapping.get_addr<int>();
+    *addr1 = 42;
 
-        mapping.resize(8000);
-        REQUIRE(mapping.size() > size1);
+    mapping.resize(8000);
+    REQUIRE(mapping.size() > size1);
 
-        int* addr2 = mapping.get_addr<int>();
-        REQUIRE(*addr2 == 42);
-    }
+    int* addr2 = mapping.get_addr<int>();
+    REQUIRE(*addr2 == 42);
+}
 
-    SECTION("remapping to smaller size should work") {
-        osmium::util::MemoryMapping mapping(8000, osmium::util::MemoryMapping::mapping_mode::write_private);
-        REQUIRE(mapping.size() >= 1000);
+TEST_CASE("Anonymous mapping: remapping to smaller size should work") {
+    osmium::util::MemoryMapping mapping{8000, osmium::util::MemoryMapping::mapping_mode::write_private};
+    REQUIRE(mapping.size() >= 1000);
 
-        size_t size1 = mapping.size();
+    const size_t size1 = mapping.size();
 
-        int* addr1 = mapping.get_addr<int>();
-        *addr1 = 42;
+    int* addr1 = mapping.get_addr<int>();
+    *addr1 = 42;
 
-        mapping.resize(500);
-        REQUIRE(mapping.size() < size1);
-
-        int* addr2 = mapping.get_addr<int>();
-        REQUIRE(*addr2 == 42);
-    }
-#endif
+    mapping.resize(500);
+    REQUIRE(mapping.size() < size1);
 
+    int* addr2 = mapping.get_addr<int>();
+    REQUIRE(*addr2 == 42);
 }
+#endif
 
-TEST_CASE("file-based mapping") {
-
-    SECTION("writing to a mapped file should work") {
-        char filename[] = "test_mmap_write_XXXXXX";
-        const int fd = mkstemp(filename);
-        REQUIRE(fd > 0);
-
-        osmium::util::resize_file(fd, 100);
+TEST_CASE("File-based mapping: writing to a mapped file should work") {
+    char filename[] = "test_mmap_write_XXXXXX";
+    const int fd = mkstemp(filename);
+    REQUIRE(fd > 0);
 
-        {
-            osmium::util::MemoryMapping mapping(100, osmium::util::MemoryMapping::mapping_mode::write_shared, fd);
-            REQUIRE(mapping.writable());
+    osmium::util::resize_file(fd, 100);
 
-            REQUIRE(!!mapping);
-            REQUIRE(mapping.size() >= 100);
+    {
+        osmium::util::MemoryMapping mapping{100, osmium::util::MemoryMapping::mapping_mode::write_shared, fd};
+        REQUIRE(mapping.writable());
 
-            *mapping.get_addr<int>() = 1234;
+        REQUIRE(!!mapping);
+        REQUIRE(mapping.size() >= 100);
 
-            mapping.unmap();
-        }
+        *mapping.get_addr<int>() = 1234;
 
-        REQUIRE(osmium::util::file_size(fd) == 100);
+        mapping.unmap();
+    }
 
-        {
-            osmium::util::MemoryMapping mapping(100, osmium::util::MemoryMapping::mapping_mode::readonly, fd);
-            REQUIRE(!mapping.writable());
+    REQUIRE(osmium::util::file_size(fd) == 100);
 
-            REQUIRE(!!mapping);
-            REQUIRE(mapping.size() >= 100);
-            REQUIRE(*mapping.get_addr<int>() == 1234);
+    {
+        osmium::util::MemoryMapping mapping{100, osmium::util::MemoryMapping::mapping_mode::readonly, fd};
+        REQUIRE(!mapping.writable());
 
-            mapping.unmap();
-        }
+        REQUIRE(!!mapping);
+        REQUIRE(mapping.size() >= 100);
+        REQUIRE(*mapping.get_addr<int>() == 1234);
 
-        REQUIRE(0 == close(fd));
-        REQUIRE(0 == unlink(filename));
+        mapping.unmap();
     }
 
-    SECTION("writing to a privately mapped file should work") {
-        char filename[] = "test_mmap_write_XXXXXX";
-        const int fd = mkstemp(filename);
-        REQUIRE(fd > 0);
+    REQUIRE(0 == close(fd));
+    REQUIRE(0 == unlink(filename));
+}
 
-        osmium::util::resize_file(fd, 100);
+TEST_CASE("File-based mapping: writing to a privately mapped file should work") {
+    char filename[] = "test_mmap_write_XXXXXX";
+    const int fd = mkstemp(filename);
+    REQUIRE(fd > 0);
 
-        {
-            osmium::util::MemoryMapping mapping(100, osmium::util::MemoryMapping::mapping_mode::write_private, fd);
-            REQUIRE(mapping.writable());
+    osmium::util::resize_file(fd, 100);
 
-            REQUIRE(!!mapping);
-            REQUIRE(mapping.size() >= 100);
+    {
+        osmium::util::MemoryMapping mapping{100, osmium::util::MemoryMapping::mapping_mode::write_private, fd};
+        REQUIRE(mapping.writable());
 
-            *mapping.get_addr<int>() = 1234;
+        REQUIRE(!!mapping);
+        REQUIRE(mapping.size() >= 100);
 
-            mapping.unmap();
-        }
+        *mapping.get_addr<int>() = 1234;
 
-        REQUIRE(osmium::util::file_size(fd) == 100);
+        mapping.unmap();
+    }
 
-        {
-            osmium::util::MemoryMapping mapping(100, osmium::util::MemoryMapping::mapping_mode::readonly, fd);
-            REQUIRE(!mapping.writable());
+    REQUIRE(osmium::util::file_size(fd) == 100);
 
-            REQUIRE(!!mapping);
-            REQUIRE(mapping.size() >= 100);
-            REQUIRE(*mapping.get_addr<int>() == 0); // should not see the value set above
+    {
+        osmium::util::MemoryMapping mapping{100, osmium::util::MemoryMapping::mapping_mode::readonly, fd};
+        REQUIRE(!mapping.writable());
 
-            mapping.unmap();
-        }
+        REQUIRE(!!mapping);
+        REQUIRE(mapping.size() >= 100);
+        REQUIRE(*mapping.get_addr<int>() == 0); // should not see the value set above
 
-        REQUIRE(0 == close(fd));
-        REQUIRE(0 == unlink(filename));
+        mapping.unmap();
     }
 
-    SECTION("remapping to larger size should work") {
-        char filename[] = "test_mmap_grow_XXXXXX";
-        const int fd = mkstemp(filename);
-        REQUIRE(fd > 0);
+    REQUIRE(0 == close(fd));
+    REQUIRE(0 == unlink(filename));
+}
 
-        osmium::util::MemoryMapping mapping(100, osmium::util::MemoryMapping::mapping_mode::write_shared, fd);
-        REQUIRE(mapping.size() >= 100);
-        size_t size1 = mapping.size();
+TEST_CASE("File-based mapping: remapping to larger size should work") {
+    char filename[] = "test_mmap_grow_XXXXXX";
+    const int fd = mkstemp(filename);
+    REQUIRE(fd > 0);
 
-        int* addr1 = mapping.get_addr<int>();
-        *addr1 = 42;
+    osmium::util::MemoryMapping mapping{100, osmium::util::MemoryMapping::mapping_mode::write_shared, fd};
+    REQUIRE(mapping.size() >= 100);
+    const size_t size1 = mapping.size();
 
-        mapping.resize(8000);
-        REQUIRE(mapping.size() >= 8000);
-        REQUIRE(mapping.size() > size1);
+    int* addr1 = mapping.get_addr<int>();
+    *addr1 = 42;
 
-        int* addr2 = mapping.get_addr<int>();
-        REQUIRE(*addr2 == 42);
+    mapping.resize(8000);
+    REQUIRE(mapping.size() >= 8000);
+    REQUIRE(mapping.size() > size1);
 
-        mapping.unmap();
+    int* addr2 = mapping.get_addr<int>();
+    REQUIRE(*addr2 == 42);
 
-        REQUIRE(0 == close(fd));
-        REQUIRE(0 == unlink(filename));
-    }
+    mapping.unmap();
 
-    SECTION("remapping to smaller size should work") {
-        char filename[] = "test_mmap_shrink_XXXXXX";
-        const int fd = mkstemp(filename);
-        REQUIRE(fd > 0);
+    REQUIRE(0 == close(fd));
+    REQUIRE(0 == unlink(filename));
+}
 
-        {
-            osmium::util::MemoryMapping mapping(8000, osmium::util::MemoryMapping::mapping_mode::write_shared, fd);
-            REQUIRE(mapping.size() >= 8000);
-            size_t size1 = mapping.size();
+TEST_CASE("File-based mapping: remapping to smaller size should work") {
+    char filename[] = "test_mmap_shrink_XXXXXX";
+    const int fd = mkstemp(filename);
+    REQUIRE(fd > 0);
 
-            int* addr1 = mapping.get_addr<int>();
-            *addr1 = 42;
+    {
+        osmium::util::MemoryMapping mapping{8000, osmium::util::MemoryMapping::mapping_mode::write_shared, fd};
+        REQUIRE(mapping.size() >= 8000);
+        const size_t size1 = mapping.size();
 
-            mapping.resize(50);
-            REQUIRE(mapping.size() >= 50);
-            REQUIRE(mapping.size() < size1);
+        int* addr1 = mapping.get_addr<int>();
+        *addr1 = 42;
 
-            int* addr2 = mapping.get_addr<int>();
-            REQUIRE(*addr2 == 42);
-        }
+        mapping.resize(50);
+        REQUIRE(mapping.size() >= 50);
+        REQUIRE(mapping.size() < size1);
 
-        REQUIRE(0 == close(fd));
-        REQUIRE(0 == unlink(filename));
+        int* addr2 = mapping.get_addr<int>();
+        REQUIRE(*addr2 == 42);
     }
+
+    REQUIRE(0 == close(fd));
+    REQUIRE(0 == unlink(filename));
 }
 
-TEST_CASE("typed anonymous mapping") {
+TEST_CASE("Typed anonymous mapping: simple memory mapping should work") {
+    osmium::util::TypedMemoryMapping<uint32_t> mapping{1000};
+    volatile uint32_t* addr = mapping.begin();
 
-    SECTION("simple memory mapping should work") {
-        osmium::util::TypedMemoryMapping<uint32_t> mapping(1000);
-        volatile uint32_t* addr = mapping.begin();
+    REQUIRE(mapping.writable());
 
-        REQUIRE(mapping.writable());
+    *addr = 42;
+    REQUIRE(*addr == 42);
 
-        *addr = 42;
-        REQUIRE(*addr == 42);
+    REQUIRE(!!mapping);
+    mapping.unmap();
+    REQUIRE(!mapping);
+    mapping.unmap(); // second unmap is okay
+}
 
-        REQUIRE(!!mapping);
-        mapping.unmap();
-        REQUIRE(!mapping);
-        mapping.unmap(); // second unmap is okay
-    }
+TEST_CASE("Typed anonymous mapping: moving a memory mapping should work") {
+    osmium::util::TypedMemoryMapping<uint32_t> mapping1{1000};
+    uint32_t* addr1 = mapping1.begin();
+    *addr1 = 42;
 
-    SECTION("moving a memory mapping should work") {
-        osmium::util::TypedMemoryMapping<uint32_t> mapping1(1000);
-        uint32_t* addr1 = mapping1.begin();
-        *addr1 = 42;
+    REQUIRE(!!mapping1);
+    osmium::util::TypedMemoryMapping<uint32_t> mapping2{std::move(mapping1)};
+    REQUIRE(!!mapping2);
+    REQUIRE(!mapping1);
+    mapping1.unmap();
 
-        REQUIRE(!!mapping1);
-        osmium::util::TypedMemoryMapping<uint32_t> mapping2(std::move(mapping1));
-        REQUIRE(!!mapping2);
-        REQUIRE(!mapping1);
-        mapping1.unmap();
+    const auto addr2 = mapping2.begin();
+    REQUIRE(*addr2 == 42);
 
-        auto addr2 = mapping2.begin();
-        REQUIRE(*addr2 == 42);
+    mapping2.unmap();
+    REQUIRE(!mapping2);
+}
 
-        mapping2.unmap();
-        REQUIRE(!mapping2);
-    }
+TEST_CASE("Typed anonymous mapping: move assignment should work") {
+    osmium::util::TypedMemoryMapping<uint32_t> mapping1{1000};
+    osmium::util::TypedMemoryMapping<uint32_t> mapping2{1000};
 
-    SECTION("move assignment should work") {
-        osmium::util::TypedMemoryMapping<uint32_t> mapping1(1000);
-        osmium::util::TypedMemoryMapping<uint32_t> mapping2(1000);
+    REQUIRE(!!mapping1);
+    REQUIRE(!!mapping2);
 
-        REQUIRE(!!mapping1);
-        REQUIRE(!!mapping2);
+    auto addr1 = mapping1.begin();
+    *addr1 = 42;
 
-        auto addr1 = mapping1.begin();
-        *addr1 = 42;
+    mapping2 = std::move(mapping1);
+    REQUIRE(!!mapping2);
+    REQUIRE(!mapping1);
 
-        mapping2 = std::move(mapping1);
-        REQUIRE(!!mapping2);
-        REQUIRE(!mapping1);
+    const auto addr2 = mapping2.begin();
+    REQUIRE(*addr2 == 42);
 
-        auto addr2 = mapping2.begin();
-        REQUIRE(*addr2 == 42);
-
-        mapping2.unmap();
-        REQUIRE(!mapping2);
-    }
+    mapping2.unmap();
+    REQUIRE(!mapping2);
+}
 
 #ifdef __linux__
-    SECTION("remapping to larger size should work") {
-        osmium::util::TypedMemoryMapping<uint32_t> mapping(1000);
-        REQUIRE(mapping.size() >= 1000);
+TEST_CASE("Typed anonymous mapping: remapping to larger size should work") {
+    osmium::util::TypedMemoryMapping<uint32_t> mapping{1000};
+    REQUIRE(mapping.size() >= 1000);
 
-        auto addr1 = mapping.begin();
-        *addr1 = 42;
-
-        mapping.resize(8000);
+    auto addr1 = mapping.begin();
+    *addr1 = 42;
 
-        auto addr2 = mapping.begin();
-        REQUIRE(*addr2 == 42);
-    }
+    mapping.resize(8000);
 
-    SECTION("remapping to smaller size should work") {
-        osmium::util::TypedMemoryMapping<uint32_t> mapping(8000);
-        REQUIRE(mapping.size() >= 8000);
+    const auto addr2 = mapping.begin();
+    REQUIRE(*addr2 == 42);
+}
 
-        auto addr1 = mapping.begin();
-        *addr1 = 42;
+TEST_CASE("Typed anonymous mapping: remapping to smaller size should work") {
+    osmium::util::TypedMemoryMapping<uint32_t> mapping{8000};
+    REQUIRE(mapping.size() >= 8000);
 
-        mapping.resize(500);
+    auto addr1 = mapping.begin();
+    *addr1 = 42;
 
-        auto addr2 = mapping.begin();
-        REQUIRE(*addr2 == 42);
-    }
-#endif
+    mapping.resize(500);
 
+    const auto addr2 = mapping.begin();
+    REQUIRE(*addr2 == 42);
 }
+#endif
 
-TEST_CASE("typed file-based mapping") {
-
-    SECTION("writing to a mapped file should work") {
-        char filename[] = "test_mmap_file_size_XXXXXX";
-        const int fd = mkstemp(filename);
-        REQUIRE(fd > 0);
-
-        osmium::util::resize_file(fd, 100);
+TEST_CASE("Typed file-based mapping: writing to a mapped file should work") {
+    char filename[] = "test_mmap_file_size_XXXXXX";
+    const int fd = mkstemp(filename);
+    REQUIRE(fd > 0);
 
-        {
-            osmium::util::TypedMemoryMapping<uint32_t> mapping(100, osmium::util::MemoryMapping::mapping_mode::write_shared, fd);
-            REQUIRE(mapping.writable());
+    osmium::util::resize_file(fd, 100);
 
-            REQUIRE(!!mapping);
-            REQUIRE(mapping.size() >= 100);
+    {
+        osmium::util::TypedMemoryMapping<uint32_t> mapping{100, osmium::util::MemoryMapping::mapping_mode::write_shared, fd};
+        REQUIRE(mapping.writable());
 
-            *mapping.begin() = 1234;
+        REQUIRE(!!mapping);
+        REQUIRE(mapping.size() >= 100);
 
-            mapping.unmap();
-        }
+        *mapping.begin() = 1234;
 
-        {
-            osmium::util::TypedMemoryMapping<uint32_t> mapping(100, osmium::util::MemoryMapping::mapping_mode::readonly, fd);
-            REQUIRE(!mapping.writable());
+        mapping.unmap();
+    }
 
-            REQUIRE(!!mapping);
-            REQUIRE(mapping.size() >= 100);
-            REQUIRE(*mapping.begin() == 1234);
+    {
+        osmium::util::TypedMemoryMapping<uint32_t> mapping{100, osmium::util::MemoryMapping::mapping_mode::readonly, fd};
+        REQUIRE(!mapping.writable());
 
-            mapping.unmap();
-        }
+        REQUIRE(!!mapping);
+        REQUIRE(mapping.size() >= 100);
+        REQUIRE(*mapping.begin() == 1234);
 
-        REQUIRE(0 == close(fd));
-        REQUIRE(0 == unlink(filename));
+        mapping.unmap();
     }
 
+    REQUIRE(0 == close(fd));
+    REQUIRE(0 == unlink(filename));
 }
 
-TEST_CASE("anonymous memory mapping class") {
+TEST_CASE("Anonymous memory mapping class: simple memory mapping should work") {
+    osmium::util::AnonymousMemoryMapping mapping{1000};
+    REQUIRE(mapping.get_addr() != nullptr);
 
-    SECTION("simple memory mapping should work") {
-        osmium::util::AnonymousMemoryMapping mapping(1000);
-        REQUIRE(mapping.get_addr() != nullptr);
+    volatile int* addr = mapping.get_addr<int>();
 
-        volatile int* addr = mapping.get_addr<int>();
-
-        REQUIRE(mapping.writable());
+    REQUIRE(mapping.writable());
 
-        *addr = 42;
-        REQUIRE(*addr == 42);
+    *addr = 42;
+    REQUIRE(*addr == 42);
 
-        REQUIRE(!!mapping);
-        mapping.unmap();
-        REQUIRE(!mapping);
-        mapping.unmap(); // second unmap is okay
-    }
+    REQUIRE(!!mapping);
+    mapping.unmap();
+    REQUIRE(!mapping);
+    mapping.unmap(); // second unmap is okay
+}
 
 #ifdef __linux__
-    SECTION("remapping to larger size should work") {
-        osmium::util::AnonymousMemoryMapping mapping(1000);
-        REQUIRE(mapping.size() >= 1000);
+TEST_CASE("Anonymous memory mapping class: remapping to larger size should work") {
+    osmium::util::AnonymousMemoryMapping mapping{1000};
+    REQUIRE(mapping.size() >= 1000);
 
-        int* addr1 = mapping.get_addr<int>();
-        *addr1 = 42;
+    int* addr1 = mapping.get_addr<int>();
+    *addr1 = 42;
 
-        mapping.resize(2000);
+    mapping.resize(2000);
 
-        int* addr2 = mapping.get_addr<int>();
-        REQUIRE(*addr2 == 42);
-    }
+    const int* addr2 = mapping.get_addr<int>();
+    REQUIRE(*addr2 == 42);
+}
 
-    SECTION("remapping to smaller size should work") {
-        osmium::util::AnonymousMemoryMapping mapping(2000);
-        REQUIRE(mapping.size() >= 2000);
+TEST_CASE("Anonymous memory mapping class: remapping to smaller size should work") {
+    osmium::util::AnonymousMemoryMapping mapping{2000};
+    REQUIRE(mapping.size() >= 2000);
 
-        int* addr1 = mapping.get_addr<int>();
-        *addr1 = 42;
+    int* addr1 = mapping.get_addr<int>();
+    *addr1 = 42;
 
-        mapping.resize(500);
-
-        int* addr2 = mapping.get_addr<int>();
-        REQUIRE(*addr2 == 42);
-    }
-#endif
+    mapping.resize(500);
 
+    const int* addr2 = mapping.get_addr<int>();
+    REQUIRE(*addr2 == 42);
 }
+#endif
 
diff --git a/test/t/util/test_minmax.cpp b/test/t/util/test_minmax.cpp
index 8b40f85..f84d4e4 100644
--- a/test/t/util/test_minmax.cpp
+++ b/test/t/util/test_minmax.cpp
@@ -3,66 +3,57 @@
 #include <osmium/util/minmax.hpp>
 #include <osmium/osm/timestamp.hpp>
 
-TEST_CASE("minmax numeric") {
+TEST_CASE("min_op numeric") {
+    osmium::min_op<int> x;
+    REQUIRE(x() == std::numeric_limits<int>::max());
 
-    SECTION("min") {
-        osmium::min_op<int> x;
-        REQUIRE(x() == std::numeric_limits<int>::max());
+    x.update(17);
+    REQUIRE(x() == 17);
 
-        x.update(17);
-        REQUIRE(x() == 17);
+    x.update(10);
+    REQUIRE(x() == 10);
 
-        x.update(10);
-        REQUIRE(x() == 10);
-
-        x.update(22);
-        REQUIRE(x() == 10);
-    }
-
-    SECTION("max") {
-        osmium::max_op<uint32_t> x;
-        REQUIRE(x() == 0);
+    x.update(22);
+    REQUIRE(x() == 10);
+}
 
-        x.update(17);
-        REQUIRE(x() == 17);
+TEST_CASE("max_op numeric") {
+    osmium::max_op<uint32_t> x;
+    REQUIRE(x() == 0);
 
-        x.update(10);
-        REQUIRE(x() == 17);
+    x.update(17);
+    REQUIRE(x() == 17);
 
-        x.update(22);
-        REQUIRE(x() == 22);
-    }
+    x.update(10);
+    REQUIRE(x() == 17);
 
+    x.update(22);
+    REQUIRE(x() == 22);
 }
 
-TEST_CASE("minmax timestamp") {
-
-    SECTION("min") {
-        osmium::min_op<osmium::Timestamp> x;
+TEST_CASE("min_op timestamp") {
+    osmium::min_op<osmium::Timestamp> x;
 
-        x.update(osmium::Timestamp("2010-01-01T00:00:00Z"));
-        REQUIRE(x().to_iso() == "2010-01-01T00:00:00Z");
+    x.update(osmium::Timestamp("2010-01-01T00:00:00Z"));
+    REQUIRE(x().to_iso() == "2010-01-01T00:00:00Z");
 
-        x.update(osmium::Timestamp("2015-01-01T00:00:00Z"));
-        REQUIRE(x().to_iso() == "2010-01-01T00:00:00Z");
+    x.update(osmium::Timestamp("2015-01-01T00:00:00Z"));
+    REQUIRE(x().to_iso() == "2010-01-01T00:00:00Z");
 
-        x.update(osmium::Timestamp("2000-01-01T00:00:00Z"));
-        REQUIRE(x().to_iso() == "2000-01-01T00:00:00Z");
-    }
-
-    SECTION("max") {
-        osmium::max_op<osmium::Timestamp> x;
-
-        x.update(osmium::Timestamp("2010-01-01T00:00:00Z"));
-        REQUIRE(x().to_iso() == "2010-01-01T00:00:00Z");
+    x.update(osmium::Timestamp("2000-01-01T00:00:00Z"));
+    REQUIRE(x().to_iso() == "2000-01-01T00:00:00Z");
+}
 
-        x.update(osmium::Timestamp("2015-01-01T00:00:00Z"));
-        REQUIRE(x().to_iso() == "2015-01-01T00:00:00Z");
+TEST_CASE("max_op timestamp") {
+    osmium::max_op<osmium::Timestamp> x;
 
-        x.update(osmium::Timestamp("2000-01-01T00:00:00Z"));
-        REQUIRE(x().to_iso() == "2015-01-01T00:00:00Z");
+    x.update(osmium::Timestamp("2010-01-01T00:00:00Z"));
+    REQUIRE(x().to_iso() == "2010-01-01T00:00:00Z");
 
-    }
+    x.update(osmium::Timestamp("2015-01-01T00:00:00Z"));
+    REQUIRE(x().to_iso() == "2015-01-01T00:00:00Z");
 
+    x.update(osmium::Timestamp("2000-01-01T00:00:00Z"));
+    REQUIRE(x().to_iso() == "2015-01-01T00:00:00Z");
 }
 
diff --git a/test/t/util/test_options.cpp b/test/t/util/test_options.cpp
index 8cba095..00bc1da 100644
--- a/test/t/util/test_options.cpp
+++ b/test/t/util/test_options.cpp
@@ -1,7 +1,5 @@
 #include "catch.hpp"
 
-#include <iterator>
-
 #include <osmium/util/options.hpp>
 
 TEST_CASE("Options") {
diff --git a/test/t/util/test_string.cpp b/test/t/util/test_string.cpp
index 0960afe..e6b4e00 100644
--- a/test/t/util/test_string.cpp
+++ b/test/t/util/test_string.cpp
@@ -2,67 +2,63 @@
 
 #include <osmium/util/string.hpp>
 
-TEST_CASE("split_string") {
+TEST_CASE("split_string string") {
+    std::string str { "foo,baramba,baz" };
+    std::vector<std::string> result = {"foo", "baramba", "baz"};
 
-    SECTION("split_string string") {
-        std::string str { "foo,baramba,baz" };
-        std::vector<std::string> result = {"foo", "baramba", "baz"};
-
-        REQUIRE(result == osmium::split_string(str, ','));
-        REQUIRE(result == osmium::split_string(str, ',', true));
-    }
-
-    SECTION("split_string string without sep") {
-        std::string str { "foo" };
-        std::vector<std::string> result = {"foo"};
+    REQUIRE(result == osmium::split_string(str, ','));
+    REQUIRE(result == osmium::split_string(str, ',', true));
+}
 
-        REQUIRE(result == osmium::split_string(str, ','));
-        REQUIRE(result == osmium::split_string(str, ',', true));
-    }
+TEST_CASE("split_string string without sep") {
+    std::string str { "foo" };
+    std::vector<std::string> result = {"foo"};
 
-    SECTION("split_string string with empty at end") {
-        std::string str { "foo,bar," };
-        std::vector<std::string> result = {"foo", "bar", ""};
-        std::vector<std::string> resultc = {"foo", "bar"};
+    REQUIRE(result == osmium::split_string(str, ','));
+    REQUIRE(result == osmium::split_string(str, ',', true));
+}
 
-        REQUIRE(result == osmium::split_string(str, ','));
-        REQUIRE(resultc == osmium::split_string(str, ',', true));
-    }
+TEST_CASE("split_string string with empty at end") {
+    std::string str { "foo,bar," };
+    std::vector<std::string> result = {"foo", "bar", ""};
+    std::vector<std::string> resultc = {"foo", "bar"};
 
-    SECTION("split_string string with empty in middle") {
-        std::string str { "foo,,bar" };
-        std::vector<std::string> result = {"foo", "", "bar"};
-        std::vector<std::string> resultc = {"foo", "bar"};
+    REQUIRE(result == osmium::split_string(str, ','));
+    REQUIRE(resultc == osmium::split_string(str, ',', true));
+}
 
-        REQUIRE(result == osmium::split_string(str, ','));
-        REQUIRE(resultc == osmium::split_string(str, ',', true));
-    }
+TEST_CASE("split_string string with empty in middle") {
+    std::string str { "foo,,bar" };
+    std::vector<std::string> result = {"foo", "", "bar"};
+    std::vector<std::string> resultc = {"foo", "bar"};
 
-    SECTION("split_string string with empty at start") {
-        std::string str { ",bar,baz" };
-        std::vector<std::string> result = {"", "bar", "baz"};
-        std::vector<std::string> resultc = {"bar", "baz"};
+    REQUIRE(result == osmium::split_string(str, ','));
+    REQUIRE(resultc == osmium::split_string(str, ',', true));
+}
 
-        REQUIRE(result == osmium::split_string(str, ','));
-        REQUIRE(resultc == osmium::split_string(str, ',', true));
-    }
+TEST_CASE("split_string string with empty at start") {
+    std::string str { ",bar,baz" };
+    std::vector<std::string> result = {"", "bar", "baz"};
+    std::vector<std::string> resultc = {"bar", "baz"};
 
-    SECTION("split_string sep") {
-        std::string str { "," };
-        std::vector<std::string> result = {"", ""};
-        std::vector<std::string> resultc;
+    REQUIRE(result == osmium::split_string(str, ','));
+    REQUIRE(resultc == osmium::split_string(str, ',', true));
+}
 
-        REQUIRE(result == osmium::split_string(str, ','));
-        REQUIRE(resultc == osmium::split_string(str, ',', true));
-    }
+TEST_CASE("split_string sep") {
+    std::string str { "," };
+    std::vector<std::string> result = {"", ""};
+    std::vector<std::string> resultc;
 
-    SECTION("split_string empty string") {
-        std::string str { "" };
-        std::vector<std::string> result;
+    REQUIRE(result == osmium::split_string(str, ','));
+    REQUIRE(resultc == osmium::split_string(str, ',', true));
+}
 
-        REQUIRE(result == osmium::split_string(str, ','));
-        REQUIRE(result == osmium::split_string(str, ',', true));
-    }
+TEST_CASE("split_string empty string") {
+    std::string str { "" };
+    std::vector<std::string> result;
 
+    REQUIRE(result == osmium::split_string(str, ','));
+    REQUIRE(result == osmium::split_string(str, ',', true));
 }
 
diff --git a/test/t/util/test_string_matcher.cpp b/test/t/util/test_string_matcher.cpp
new file mode 100644
index 0000000..e9cd39e
--- /dev/null
+++ b/test/t/util/test_string_matcher.cpp
@@ -0,0 +1,156 @@
+#include "catch.hpp"
+
+#include <sstream>
+#include <type_traits>
+
+#include <osmium/util/string_matcher.hpp>
+
+static_assert(std::is_default_constructible<osmium::StringMatcher>::value, "StringMatcher should be default constructible");
+static_assert(std::is_copy_constructible<osmium::StringMatcher>::value, "StringMatcher should be copy constructible");
+static_assert(std::is_move_constructible<osmium::StringMatcher>::value, "StringMatcher should be move constructible");
+static_assert(std::is_copy_assignable<osmium::StringMatcher>::value, "StringMatcher should be copyable");
+static_assert(std::is_move_assignable<osmium::StringMatcher>::value, "StringMatcher should be moveable");
+
+template <typename T>
+std::string print(const T& matcher) {
+    std::stringstream ss;
+    ss << matcher;
+    return ss.str();
+}
+
+TEST_CASE("String matcher: always false") {
+    osmium::StringMatcher::always_false m;
+    REQUIRE_FALSE(m.match("foo"));
+}
+
+TEST_CASE("String matcher: always true") {
+    osmium::StringMatcher::always_true m;
+    REQUIRE(m.match("foo"));
+}
+
+TEST_CASE("String matcher: equal") {
+    osmium::StringMatcher::equal m{"foo"};
+    REQUIRE(m.match("foo"));
+    REQUIRE_FALSE(m.match("bar"));
+    REQUIRE_FALSE(m.match("foobar"));
+}
+
+TEST_CASE("String matcher: prefix") {
+    osmium::StringMatcher::prefix m{"foo"};
+    REQUIRE(m.match("foo"));
+    REQUIRE_FALSE(m.match("bar"));
+    REQUIRE(m.match("foobar"));
+    REQUIRE_FALSE(m.match(""));
+}
+
+TEST_CASE("String matcher: substring") {
+    osmium::StringMatcher::substring m{"foo"};
+    REQUIRE(m.match("foo"));
+    REQUIRE_FALSE(m.match("bar"));
+    REQUIRE(m.match("foobar"));
+    REQUIRE(m.match("barfoo"));
+    REQUIRE(m.match("xfoox"));
+}
+
+TEST_CASE("String matcher: empty prefix") {
+    osmium::StringMatcher::prefix m{""};
+    REQUIRE(m.match("foo"));
+    REQUIRE(m.match("bar"));
+    REQUIRE(m.match("foobar"));
+    REQUIRE(m.match(""));
+}
+
+#ifdef OSMIUM_WITH_REGEX
+TEST_CASE("String matcher: regex prefix") {
+    osmium::StringMatcher::regex m{std::regex{"^foo", std::regex::optimize}};
+    REQUIRE(m.match("foo"));
+    REQUIRE_FALSE(m.match("bar"));
+    REQUIRE(m.match("foobar"));
+    REQUIRE_FALSE(m.match(""));
+}
+
+TEST_CASE("String matcher: regex substr") {
+    osmium::StringMatcher::regex m{std::regex{"foo", std::regex::optimize}};
+    REQUIRE(m.match("foo"));
+    REQUIRE_FALSE(m.match("bar"));
+    REQUIRE(m.match("foobar"));
+    REQUIRE(m.match("xfoox"));
+    REQUIRE_FALSE(m.match(""));
+}
+#endif
+
+TEST_CASE("String matcher: list") {
+    osmium::StringMatcher::list m{{"foo", "bar"}};
+    REQUIRE(m.match("foo"));
+    REQUIRE(m.match("bar"));
+    REQUIRE_FALSE(m.match("foobar"));
+    REQUIRE_FALSE(m.match("baz"));
+    REQUIRE_FALSE(m.match(""));
+}
+
+TEST_CASE("String matcher: list with add") {
+    osmium::StringMatcher::list m;
+    REQUIRE_FALSE(m.match("foo"));
+    REQUIRE_FALSE(m.match("bar"));
+    m.add_string("foo");
+    REQUIRE(m.match("foo"));
+    m.add_string("bar");
+    REQUIRE(m.match("bar"));
+    REQUIRE_FALSE(m.match("foobar"));
+    REQUIRE_FALSE(m.match("baz"));
+    REQUIRE_FALSE(m.match(""));
+}
+
+TEST_CASE("Default constructed StringMatcher matches nothing") {
+    osmium::StringMatcher m;
+    REQUIRE_FALSE(m("foo"));
+    REQUIRE_FALSE(m("bar"));
+    REQUIRE(print(m) == "always_false");
+}
+
+TEST_CASE("Construct StringMatcher from bool") {
+    osmium::StringMatcher m1{false};
+    REQUIRE_FALSE(m1("foo"));
+    REQUIRE_FALSE(m1("bar"));
+    REQUIRE(print(m1) == "always_false");
+
+    osmium::StringMatcher m2{true};
+    REQUIRE(m2("foo"));
+    REQUIRE(m2("bar"));
+    REQUIRE(print(m2) == "always_true");
+}
+
+TEST_CASE("Construct StringMatcher from string") {
+    osmium::StringMatcher m{"foo"};
+    REQUIRE(m("foo"));
+    REQUIRE_FALSE(m("bar"));
+    REQUIRE(print(m) == "equal[foo]");
+}
+
+#ifdef OSMIUM_WITH_REGEX
+TEST_CASE("Construct StringMatcher from regex") {
+    osmium::StringMatcher m{std::regex{"^foo"}};
+    REQUIRE(m("foo"));
+    REQUIRE_FALSE(m("bar"));
+    REQUIRE(print(m) == "regex");
+}
+#endif
+
+TEST_CASE("Construct StringMatcher from list") {
+    std::vector<std::string> v{"foo", "xxx"};
+    osmium::StringMatcher m{v};
+    REQUIRE(m("foo"));
+    REQUIRE_FALSE(m("bar"));
+    REQUIRE(print(m) == "list[[foo][xxx]]");
+}
+
+TEST_CASE("Construct StringMatcher") {
+    osmium::StringMatcher m{osmium::StringMatcher::equal{"foo"}};
+    REQUIRE(m("foo"));
+    REQUIRE_FALSE(m("bar"));
+
+    m = osmium::StringMatcher::list{{"foo", "bar"}};
+    REQUIRE(m("foo"));
+    REQUIRE(m("bar"));
+}
+

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-grass/libosmium.git



More information about the Pkg-grass-devel mailing list